Programs & Examples On #Graniteds

GraniteDS is an open source framework for building Flex/JavaFX/Java solution. It offers solutions for remoting, messaging, code generation and integration with Java frameworks such as Seam and Spring.

Maven: Failed to retrieve plugin descriptor error

For me, the solution given on the page maven is not able to download anything from central because ssl don't work worked, when running Mint 19 in a VM:

sudo apt install ca-certificates-java
sudo update-ca-certificates -f

SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

This error you are receiving :

SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

is because the number of elements in $values & $matches is not the same or $matches contains more than 1 element.

If $matches contains more than 1 element, than the insert will fail, because there is only 1 column name referenced in the query(hash)

If $values & $matches do not contain the same number of elements then the insert will also fail, due to the query expecting x params but it is receiving y data $matches.

I believe you will also need to ensure the column hash has a unique index on it as well.

Try the code here:


/*** mysql hostname ***/
$hostname = 'localhost';

/*** mysql username ***/
$username = 'root';

/*** mysql password ***/
$password = '';

try {
    $dbh = new PDO("mysql:host=$hostname;dbname=test", $username, $password);
    /*** echo a message saying we have connected ***/
    echo 'Connected to database';
catch(PDOException $e)
    echo $e->getMessage();

$matches = array('1');
$count = count($matches);
for($i = 0; $i < $count; ++$i) {
    $values[] = '?';

$sql = "INSERT INTO hashes (hash) VALUES (" . implode(', ', $values) . ") ON DUPLICATE KEY UPDATE hash='hash'";
$stmt = $dbh->prepare($sql);
$data = $stmt->execute($matches);

//Error reporting if something went wrong...


You will need to adapt it a little.

Table structure I used is here:

  `hashid` int(11) NOT NULL AUTO_INCREMENT,
  `hash` varchar(250) NOT NULL,
  PRIMARY KEY (`hashid`),
  UNIQUE KEY `hash1` (`hash`)

Code was run on my XAMPP Server which is using PHP 5.3.8 with MySQL 5.5.16.

I hope this helps.

Capture Signature using HTML5 and iPad

Perhaps the best two browser techs for this are Canvas, with Flash as a back up.

We tried VML on IE as backup for Canvas, but it was much slower than Flash. SVG was slower then all the rest.

With jSignature ( ) we used Canvas as primary, with fallback to Flash-based Canvas emulator (FlashCanvas) for IE8 and less. Id' say worked very well for us.

Div with margin-left and width:100% overflowing on the right side

<div style="width:100%;">
    <div style="margin-left:45px;">
       <asp:TextBox ID="txtTitle" runat="server" Width="100%"></asp:TextBox><br />

Detecting iOS / Android Operating system

One can use navigator.platform to get the operating system on which browser is installed.

function getPlatform() {
   var platform = ["Win32", "Android", "iOS"];

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

       if (navigator.platform.indexOf(platform[i]) >- 1) {

           return platform[i];


What is an 'undeclared identifier' error and how do I fix it?

Another possible situation: accessing parent (a template class) member in a template class.

Fix method: using the parent class member by its full name (by prefixing this-> or parentClassName:: to the name of the member).

see: templates: parent class member variables not visible in inherited class

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

You need to have favicon.ico in the same folder or dictionary as your script because python only searches in the current dictionary or you could put in the full pathname. For example, this works:

from tkinter import *
root = Tk()


But this blows up with your same error:

from tkinter import *
root = Tk()


How to disable Django's CSRF validation?

CSRF can be enforced at the view level, which can't be disabled globally.

In some cases this is a pain, but um, "it's for security". Gotta retain those AAA ratings.

Update a submodule to the latest commit

Andy's response worked for me by escaping $path:

git submodule foreach "(git checkout master; git pull; cd ..; git add \$path; git commit -m 'Submodule Sync')"

What and where are the stack and heap?

Thank you for a really good discussion but as a real noob I wonder where instructions are kept? In the BEGINNING scientists were deciding between two architectures (von NEUMANN where everything is considered DATA and HARVARD where an area of memory was reserved for instructions and another for data). Ultimately, we went with the von Neumann design and now everything is considered 'the same'. This made it hard for me when I was learning assembly because they talk about registers and stack pointers.

Everything above talks about DATA. My guess is that since an instruction is a defined thing with a specific memory footprint, it would go on the stack and so all 'those' registers discussed in assembly are on the stack. Of course then came object oriented programming with instructions and data comingled into a structure that was dynamic so now instructions would be kept on the heap as well?

How to turn off magic quotes on shared hosting?

While I can't say why php_flag is giving you 500 Internal Server Errors, I will point out that the PHP manual has an example of detecting if magic quotes is on and stripping it from the superglobals at runtime. Unlike the others posted, this one is recursive and will correctly strip quotes from arrays:

Update: I noticed today that there's a new version of the following code on the PHP manual that uses references to the super-globals instead.

Old version:

if (get_magic_quotes_gpc()) {
    function stripslashes_deep($value)
        $value = is_array($value) ?
                    array_map('stripslashes_deep', $value) :

        return $value;

    $_POST = array_map('stripslashes_deep', $_POST);
    $_GET = array_map('stripslashes_deep', $_GET);
    $_COOKIE = array_map('stripslashes_deep', $_COOKIE);
    $_REQUEST = array_map('stripslashes_deep', $_REQUEST);

New version:

if (get_magic_quotes_gpc()) {
    $process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
    while (list($key, $val) = each($process)) {
        foreach ($val as $k => $v) {
            if (is_array($v)) {
                $process[$key][stripslashes($k)] = $v;
                $process[] = &$process[$key][stripslashes($k)];
            } else {
                $process[$key][stripslashes($k)] = stripslashes($v);

Avoid printStackTrace(); use a logger call instead

The main reason is that Proguard would remove Log calls from production. Because by logging or printing StackTrace, it is possible to see them (information inside stack trace or Log) inside the Android phone by for example Logcat Reader application. So that it is a bad practice for security. Also, we do not access them during production, it would better to get removed from production. As ProGuard remove all Log calls not stackTrace, so it is better to use Log in catch blocks and let them removed from Production by Proguard.

Why is there no SortedList in Java?

For any newcomers, as of April 2015, Android now has a SortedList class in the support library, designed specifically to work with RecyclerView. Here's the blog post about it.

How to make an unaware datetime timezone aware in python

for those that just want to make a timezone aware datetime

import datetime
import pytz

datetime.datetime(2019, 12, 7, tzinfo=pytz.UTC)

How can I get Maven to stop attempting to check for updates for artifacts from a certain group from maven-central-repo?

Also, you can use -o or --offline in the mvn command line which will put maven in "offline mode" so it won't check for updates. You'll get some warning about not being able to get dependencies not already in your local repo, but no big deal.

Build fails with "Command failed with a nonzero exit code"

For me cleaning the project (Command + Shift + K) and restarting xCode worked for me

How do you rename a MongoDB database?

Although Mongodb does not provide the rename Database command, it provides the rename Collection command, which not only modifies the collection name, but also modifies the database name.

{ renameCollection: "<source_namespace>", to: "<target_namespace>", dropTarget: <true|false>  writeConcern: <document> }
db.adminCommand({renameCollection: "db1.test1", to: "db2.test2"})

This command only modifies the metadata, the cost is very small, we only need to traverse all the collections under db1, renamed to db2 to achieve rename Database name.
you can do it in this Js script

var source = "source";
var dest = "dest";
var colls = db.getSiblingDB(source).getCollectionNames();
for (var i = 0; i < colls.length; i++) {
var from = source + "." + colls[i];
var to = dest + "." + colls[i];
db.adminCommand({renameCollection: from, to: to});

Be careful when you use this command

renameCollection has different performance implications depending on the target namespace.

If the target database is the same as the source database, renameCollection simply changes the namespace. This is a quick operation.

If the target database differs from the source database, renameCollection copies all documents from the source collection to the target collection. Depending on the size of the collection, this may take longer to complete.

Transfer git repositories from GitLab to GitHub - can we, how to and pitfalls (if any)?

I had the opposite problem and finally had to create my own bash shell script for the company to migrate the hundred of repos from Github to Gitlab due to a change in the company policy.
The script use the Gitlab API to remotely create a repo, and push the Github repo into it. There is no file yet, but the sh is well documented.
The same thing can be done opposite way I imagine. Hope this could help.

CSS / HTML Navigation and Logo on same line

Try this CSS:

body {
  margin: 0;
  padding: 0;

.logo {
  float: left;
/* ~~ Top Navigation Bar ~~ */

#navigation-container {
  width: 1200px;
  margin: 0 auto;
  height: 70px;

.navigation-bar {
  background-color: #352d2f;
  height: 70px;
  width: 100%;

#navigation-container img {
  float: left;

#navigation-container ul {
  padding: 0px;
  margin: 0px;
  text-align: center;

#navigation-container li {
  list-style-type: none;
  padding: 0px;
  height: 24px;
  margin-top: 4px;
  margin-bottom: 4px;
  display: inline;

#navigation-container li a {
  color: white;
  font-size: 16px;
  font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
  text-decoration: none;
  line-height: 70px;
  padding: 5px 15px;
  opacity: 0.7;

#menu {
  float: right;

Relative div height

Percentage in width works but percentage in height will not work unless you specify a specific height for any parent in the dependent loop...

See this : percentage in height doesn’t work?

Change div height on button click

Just a silly mistake use quote('') in '200px'


<body >
    <button type="button" onClick = "document.getElementById('chartdiv').style.height = '200px';">Click Me!</button>
    <div id="chartdiv" style="width: 100%; height: 50px; background-color:#E8EDF2"></div>

How to get request URL in Spring Boot RestController

Allows getting any URL on your system, not just a current one.

import org.springframework.hateoas.mvc.ControllerLinkBuilder
ControllerLinkBuilder linkBuilder = ControllerLinkBuilder.linkTo(methodOn(YourController.class).getSomeEntityMethod(parameterId, parameterTwoId))

URI methodUri = linkBuilder.Uri()
String methodUrl = methodUri.getPath()

PG::ConnectionBad - could not connect to server: Connection refused

As suggested above, I just opened up the Postgres App on my Mac, clicked Open Psql, closed the psql window, restarted my rails server in my terminal, and it was working again, no more error.

Trust the elephant:

Reading an integer from user input

Better way is to use TryParse:

Int32 _userInput;
if(Int32.TryParse (Console.Readline(), out _userInput) {// do the stuff on userInput}

What does <T> denote in C#

This feature is known as generics.

An example of this is to make a collection of items of a specific type.

class MyArray<T>
    T[] array = new T[10];

    public T GetItem(int index)
        return array[index];

In your code, you could then do something like this:

MyArray<int> = new MyArray<int>();

In this case, T[] array would work like int[] array, and public T GetItem would work like public int GetItem.

How to have the cp command create any necessary folders for copying a file to a destination

 mkdir -p `dirname /nosuchdirectory/hi.txt` && cp -r urls-resume /nosuchdirectory/hi.txt

How to make a Div appear on top of everything else on the screen?

Try setting position to absolute, ie.

    position: absolute;
    z-index: 10;

Script for rebuilding and reindexing the fragmented index?

Here is the modified script which i took from which i found useful to post here. Although it uses a cursor and i know what is the main problem with cursors it can be easily converted to a cursor-less version.

It is well-documented and you can easily read through it and modify to your needs.

  IF OBJECT_ID('tempdb..#work_to_do') IS NOT NULL 
        DROP TABLE tempdb..#work_to_do


use yourdbname

-- Ensure a USE  statement has been executed first.


    DECLARE @objectid INT;
    DECLARE @indexid INT;
    DECLARE @partitioncount BIGINT;
    DECLARE @schemaname NVARCHAR(130);
    DECLARE @objectname NVARCHAR(130);
    DECLARE @indexname NVARCHAR(130);
    DECLARE @partitionnum BIGINT;
    DECLARE @partitions BIGINT;
    DECLARE @frag FLOAT;
    DECLARE @pagecount INT;
    DECLARE @command NVARCHAR(4000);

    DECLARE @page_count_minimum SMALLINT
    SET @page_count_minimum = 50

    DECLARE @fragmentation_minimum FLOAT
    SET @fragmentation_minimum = 30.0

-- Conditionally select tables and indexes from the sys.dm_db_index_physical_stats function
-- and convert object and index IDs to names.

    SELECT  object_id AS objectid ,
            index_id AS indexid ,
            partition_number AS partitionnum ,
            avg_fragmentation_in_percent AS frag ,
            page_count AS page_count
    INTO    #work_to_do
    FROM    sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL,
    WHERE   avg_fragmentation_in_percent > @fragmentation_minimum
            AND index_id > 0
            AND page_count > @page_count_minimum;

IF CURSOR_STATUS('global', 'partitions') >= -1
 PRINT 'partitions CURSOR DELETED' ;
    CLOSE partitions
    DEALLOCATE partitions
-- Declare the cursor for the list of partitions to be processed.
        SELECT  *
        FROM    #work_to_do;

-- Open the cursor.
    OPEN partitions;

-- Loop through the partitions.
    WHILE ( 1 = 1 )
            FETCH NEXT
FROM partitions
INTO @objectid, @indexid, @partitionnum, @frag, @pagecount;

            IF @@FETCH_STATUS < 0

            SELECT  @objectname = QUOTENAME( ,
                    @schemaname = QUOTENAME(
            FROM    sys.objects AS o
                    JOIN sys.schemas AS s ON s.schema_id = o.schema_id
            WHERE   o.object_id = @objectid;

            SELECT  @indexname = QUOTENAME(name)
            FROM    sys.indexes
            WHERE   object_id = @objectid
                    AND index_id = @indexid;

            SELECT  @partitioncount = COUNT(*)
            FROM    sys.partitions
            WHERE   object_id = @objectid
                    AND index_id = @indexid;

            SET @command = N'ALTER INDEX ' + @indexname + N' ON '
                + @schemaname + N'.' + @objectname + N' REBUILD';

            IF @partitioncount > 1
                SET @command = @command + N' PARTITION='
                    + CAST(@partitionnum AS NVARCHAR(10));

            EXEC (@command);
            --print (@command); //uncomment for testing

            PRINT N'Rebuilding index ' + @indexname + ' on table '
                + @objectname;
            PRINT N'  Fragmentation: ' + CAST(@frag AS VARCHAR(15));
            PRINT N'  Page Count:    ' + CAST(@pagecount AS VARCHAR(15));
            PRINT N' ';

-- Close and deallocate the cursor.
    CLOSE partitions;
    DEALLOCATE partitions;

-- Drop the temporary table.
    DROP TABLE #work_to_do;


Android: how do I check if activity is running?

If you are interested in the lifecycle state of the specific instance of the activity, siliconeagle's solution looks correct except that the new "active" variable should be an instance variable, rather than static.

jQuery’s .bind() vs. .on()

The direct methods and .delegate are superior APIs to .on and there is no intention of deprecating them.

The direct methods are preferable because your code will be less stringly typed. You will get immediate error when you mistype an event name rather than a silent bug. In my opinion, it's also easier to write and read click than on("click"

The .delegate is superior to .on because of the argument's order:

$(elem).delegate( ".selector", {
    click: function() {
    mousemove: function() {
    mouseup: function() {
    mousedown: function() {

You know right away it's delegated because, well, it says delegate. You also instantly see the selector.

With .on it's not immediately clear if it's even delegated and you have to look at the end for the selector:

    click: function() {
    mousemove: function() {
    mouseup: function() {
    mousedown: function() {
}, "selector" );

Now, the naming of .bind is really terrible and is at face value worse than .on. But .delegate cannot do non-delegated events and there are events that don't have a direct method, so in a rare case like this it could be used but only because you want to make a clean separation between delegated and non-delegated events.

How do I make a transparent border with CSS?

The easiest solution to this is to use rgba as the color: border-color: rgba(0,0,0,0); That is fully transparent border color.

proper hibernate annotation for byte[]

On Postgres @Lob is breaking for byte[] as it tries to save it as oid, and for String also same problem occurs. Below code is breaking on postgres which is working fine on oracle.

private String stringField;


private byte[]   someByteStream;

In order to fix above on postgres have written below custom hibernate.dialect

public class PostgreSQLDialectCustom extends PostgreSQL82Dialect{

public PostgreSQLDialectCustom()
    registerColumnType(Types.BLOB, "bytea");

 public SqlTypeDescriptor remapSqlTypeDescriptor(SqlTypeDescriptor sqlTypeDescriptor) {
    if (Types.CLOB == sqlTypeDescriptor.getSqlType()) {
      return LongVarcharTypeDescriptor.INSTANCE;
    return super.remapSqlTypeDescriptor(sqlTypeDescriptor);

Now configure custom dialect in hibernate


X.Y.Z is package name.

Now it working fine. NOTE- My Hibernate version - 5.2.8.Final Postgres version- 9.6.3

TypeError: 'function' object is not subscriptable - Python

You can use this:

bankHoliday= [1, 0, 1, 1, 2, 0, 0, 1, 0, 0, 0, 2] #gives the list of bank holidays in each month

def bank_holiday(month):
   month -= 1#Takes away the numbers from the months, as months start at 1 (January) not at 0. There is no 0 month.

bank_holiday(int(input("Which month would you like to check out: ")))

Loop code for each file in a directory

Looks for the function glob():

$files = glob("dir/*.jpg");
foreach($files as $jpg){
    echo $jpg, "\n";

"installation of package 'FILE_PATH' had non-zero exit status" in R

I have had the same problem with a specific package in R and the solution was I should install in the ubuntu terminal libcurl. Look at the information that appears above explaining to us that curl package has error installation.

I knew this about the message:

Configuration failed because libcurl was not found. Try installing:
 * deb: libcurl4-openssl-dev (Debian, Ubuntu, etc)
 * rpm: libcurl-devel (Fedora, CentOS, RHEL)
 * csw: libcurl_dev (Solaris)
If libcurl is already installed, check that 'pkg-config' is in your
PATH and PKG_CONFIG_PATH contains a libcurl.pc file. If pkg-config
is unavailable you can set INCLUDE_DIR and LIB_DIR manually via:
R CMD INSTALL --configure-vars='INCLUDE_DIR=... LIB_DIR=...'

To install it I used the net command:

sudo apt-get install libcurl4-openssl-dev

Sometimes we can not install a specific package in R because we have problems with packages that must be installed previously as curl package. To know if we should install it we should check the warning errors such as: installation of package ‘curl’ had non-zero exit status.

I hope I have been helpful

PHP Remove elements from associative array

Try this:

$keys = array_keys($array, "Completed");

/edit As mentioned by JohnP, this method only works for non-nested arrays.

How to copy in bash all directory and files recursive?

code for a simple copy.

cp -r ./SourceFolder ./DestFolder

code for a copy with success result

cp -rv ./SourceFolder ./DestFolder

code for Forcefully if source contains any readonly file it will also copy

cp -rf ./SourceFolder ./DestFolder

for details help

cp --help

Why specify @charset "UTF-8"; in your CSS file?

If you're putting a <meta> tag in your css files, you're doing something wrong. The <meta> tag belongs in your html files, and tells the browser how the html is encoded, it doesn't say anything about the css, which is a separate file. You could conceivably have completely different encodings for your html and css, although I can't imagine this would be a good idea.

How to save LogCat contents to file?

To save LogCat log to file programmatically on your device use for example this code:

String filePath = Environment.getExternalStorageDirectory() + "/logcat.txt";
Runtime.getRuntime().exec(new String[]{"logcat", "-f", filepath, "MyAppTAG:V", "*:S"});

"MyAppTAG:V" sets the priority level for all tags to Verbose (lowest priority)

"*:S" sets the priority level for all tags to "silent"

More information about logcat here.

array filter in python?

Yes, the filter function:

filter(lambda x: x not in subset_of_A, A)

How can I change the width and height of slides on Slick Carousel?

Basically you need to edit the JS and add (in this case, inside $('#featured-articles').slick({ ), this:

variableWidth: true,

This will allow you to edit the width in your CSS where you can, generically use:

.slick-slide {
    width: 100%;

or in this case:

.featured {
    width: 100%;

Float sum with javascript

Once you read what What Every Computer Scientist Should Know About Floating-Point Arithmetic you could use the .toFixed() function:

var result = parseFloat('2.3') + parseFloat('2.4');

Getting "TypeError: failed to fetch" when the request hasn't actually failed

I know it's a relative old post but, I would like to share what worked for me: I've simply input "http://" before "localhost" in the url. Hope it helps somebody.

Jquery bind double click and single click separately

Same as the above answer but allows for triple click. (Delay 500)

    var DELAY = 500,
    clicks = 0,
    timer = null;

$(document).ready(function() {
    .on("click", function(e){
        clicks++;  //count clicks
        timer = setTimeout(function() {
        if(clicks === 1) {
           alert('Single Click'); //perform single-click action
        } else if(clicks === 2) {
           alert('Double Click'); //perform single-click action
        } else if(clicks >= 3) {
           alert('Triple Click'); //perform Triple-click action
         clicks = 0;  //after action performed, reset counter
       }, DELAY);
    .on("dblclick", function(e){
        e.preventDefault();  //cancel system double-click event

Get root view from current activity

Another Kotlin Extension solution

If your activity's view is declared in xml (ex activity_root.xml), open the xml and assign an id to the root view:


Now in your class, import the view using:


You can now use root_activity as the view.

How to save a base64 image to user's disk using JavaScript?

In JavaScript you cannot have the direct access to the filesystem. However, you can make browser to pop up a dialog window allowing the user to pick the save location. In order to do this, use the replace method with your Base64String and replace "image/png" with "image/octet-stream":

"data:image/png;base64,iVBORw0KG...".replace("image/png", "image/octet-stream");

Also, W3C-compliant browsers provide 2 methods to work with base64-encoded and binary data:

Probably, you will find them useful in a way...

Here is a refactored version of what I understand you need:

window.addEventListener('DOMContentLoaded', () => {_x000D_
  const img = document.getElementById('embedImage');_x000D_
  img.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA' +_x000D_
  img.addEventListener('load', () => button.removeAttribute('disabled'));_x000D_
  const button = document.getElementById('saveImage');_x000D_
  button.addEventListener('click', () => {_x000D_
    window.location.href = img.src.replace('image/png', 'image/octet-stream');_x000D_
<!DOCTYPE html>_x000D_
  <img id="embedImage" alt="Red dot" />_x000D_
  <button id="saveImage" disabled="disabled">save image</button>_x000D_

ActiveRecord: size vs count

Sometimes size "picks the wrong one" and returns a hash (which is what count would do)

In that case, use length to get an integer instead of hash.

Laravel 5: Display HTML with Blade

If you use the Bootstrap Collapse class sometimes {!! $text !!} is not worked for me but {{ html_entity_decode($text) }} is worked for me.

Package doesn't exist error in intelliJ

menu -> build -> Rebuild Project

has worked for me

(Invalidating caches without this step doesn't help)

Laravel-5 'LIKE' equivalent (Eloquent)

I think this is better, following the good practices of passing parameters to the query:

BookingDates::whereRaw('email = ? or name like ?', [$request->email,"%{$request->name}%"])->get();

You can see it in the documentation, Laravel 5.5.

You can also use the Laravel scout and make it easier with search. Here is the documentation.

presenting ViewController with NavigationViewController swift

Calling presentViewController presents the view controller modally, outside the existing navigation stack; it is not contained by your UINavigationController or any other. If you want your new view controller to have a navigation bar, you have two main options:

Option 1. Push the new view controller onto your existing navigation stack, rather than presenting it modally:

let VC1 = self.storyboard!.instantiateViewControllerWithIdentifier("MyViewController") as! ViewController
self.navigationController!.pushViewController(VC1, animated: true)

Option 2. Embed your new view controller into a new navigation controller and present the new navigation controller modally:

let VC1 = self.storyboard!.instantiateViewControllerWithIdentifier("MyViewController") as! ViewController
let navController = UINavigationController(rootViewController: VC1) // Creating a navigation controller with VC1 at the root of the navigation stack.
self.present(navController, animated:true, completion: nil)

Bear in mind that this option won't automatically include a "back" button. You'll have to build in a close mechanism yourself.

Which one is best for you is a human interface design question, but it's normally clear what makes the most sense.

Running script upon login mac

tl;dr: use OSX's native process launcher and manager, launchd.

To do so, make a launchctl daemon. You'll have full control over all aspects of the script. You can run once or keep alive as a daemon. In most cases, this is the way to go.

  1. Create a .plist file according to the instructions in the Apple Dev docs here or more detail below.
  2. Place in ~/Library/LaunchAgents
  3. Log in (or run manually via launchctl load [filename.plist])

For more on launchd, the wikipedia article is quite good and describes the system and its advantages over other older systems.

Here's the specific plist file to run a script at login.

Updated 2017/09/25 for OSX El Capitan and newer (credit to José Messias Jr):

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "">
<plist version="1.0">

Replace the <string> after the Program key with your desired command (note that any script referenced by that command must be executable: chmod a+x /path/to/executable/ to ensure it is for all users).

Save as ~/Library/LaunchAgents/com.user.loginscript.plist

Run launchctl load ~/Library/LaunchAgents/com.user.loginscript.plist and log out/in to test (or to test directly, run launchctl start com.user.loginscript)

Tail /var/log/system.log for error messages.

The key is that this is a User-specific launchd entry, so it will be run on login for the given user. System-specific launch daemons (placed in /Library/LaunchDaemons) are run on boot.

If you want a script to run on login for all users, I believe LoginHook is your only option, and that's probably the reason it exists.

How to detect the currently pressed key?

You can also look at the following if you use WPF or reference System.Windows.Input

if (Keyboard.Modifiers == ModifierKeys.Shift)

The Keyboard namespace can also be used to check the pressed state of other keys with Keyboard.IsKeyDown(Key), or if you are subscribing to a KeyDownEvent or similar event, the event arguments carry a list of currently pressed keys.

How do I set an absolute include path in PHP?

Not directly answering your question but something to remember:

When using includes with allow_url_include on in your ini beware that, when accessing sessions from included files, if from a script you include one file using an absolute file reference and then include a second file from on your local server using a url file reference that they have different variable scope and the same session will not be seen from both included files. The original session won't be seen from the url included file.


Detecting request type in PHP (GET, POST, PUT or DELETE)

When a method was requested, it will have an array. So simply check with count().

foreach($m as$k=>$v){
    echo count($v)?
    $k.' was requested.':null;

Javascript change Div style

A simple switch statement should do the trick:

function abc() {
    var elem=document.getElementById('test'),color;
    switch( {

Unlocking tables if thread is lost

how will I know that some tables are locked?

You can use SHOW OPEN TABLES command to view locked tables.

how do I unlock tables manually?

If you know the session ID that locked tables - 'SELECT CONNECTION_ID()', then you can run KILL command to terminate session and unlock tables.

How can I escape a single quote?

Probably the easiest way:

<input type='text' id='abc' value="hel'lo">

Setting Short Value Java

There is no such thing as a byte or short literal. You need to cast to short using (short)100

AVD Manager - No system image installed for this target

you should android sdk manager install 4.2 api 17 -> ARM EABI v7a System Image

if not installed ARM EABI v7a System Image, you should install all.

c# datatable insert column at position 0

Just to improve Wael's answer and put it on a single line:

dt.Columns.Add("Better", typeof(Boolean)).SetOrdinal(0);

UPDATE: Note that this works when you don't need to do anything else with the DataColumn. Add() returns the column in question, SetOrdinal() returns nothing.

How can jQuery deferred be used?

A deferred can be used in place of a mutex. This is essentially the same as the multiple ajax usage scenarios.


var mutex = 2;

setTimeout(function() {
}, 800);

setTimeout(function() {
}, 500);

function callback() {
 if (--mutex === 0) {
  //run code


function timeout(x) {
 var dfd = jQuery.Deferred();
 setTimeout(function() {
 }, x);
 return dfd.promise();

timeout(800), timeout(500)).done(function() {
 // run code

When using a Deferred as a mutex only, watch out for performance impacts ( Though the convenience, as well as additional benefits supplied by a Deferred is well worth it, and in actual (user driven event based) usage the performance impact should not be noticeable.

Message 'src refspec master does not match any' when pushing commits in Git

If you have Visual Studio Code:

  1. Delete .git folder if you don’t need changes to track (if yes, git stash)
  2. git init
  3. git commit -m "first commit"
  4. git remote add origin
  5. By Visual Studio Code UI IDE, GOTO source control from the left hand side panel or (Ctrl + Shift + G)
  6. Stage all your changes or part
  7. Commit your changes
  8. Synchronize your changes by left bottom button (like number or like cloud icon). Then Visual Studio Code wants you to enter your username and password.

If you have permissions to the repository, you can see:

> git push -u origin master
Fatal: AggregateException encountered.
 * [new branch]      master -> master
> git status -z -u
> git symbolic-ref --short HEAD
> git rev-parse master
> git rev-parse --symbolic-full-name master@{u}
> git rev-list --left-right master...refs/remotes/origin/master
> git for-each-ref --format %(refname) %(objectname) --sort -committerdate
> git remote --verbose
> git show :ionic.config.json
> git check-ignore -z --stdin

SQL: parse the first, middle and last name from a fullname field

Subject to the caveats that have already been raised regarding spaces in names and other anomalies, the following code will at least handle 98% of names. (Note: messy SQL because I don't have a regex option in the database I use.)

**Warning: messy SQL follows:

create table parsname (fullname char(50), name1 char(30), name2 char(30), name3 char(30), name4 char(40));
insert into parsname (fullname) select fullname from ImportTable;
update parsname set name1 = substring(fullname, 1, locate(' ', fullname)),
 fullname = ltrim(substring(fullname, locate(' ', fullname), length(fullname)))
 where locate(' ', rtrim(fullname)) > 0;
update parsname set name2 = substring(fullname, 1, locate(' ', fullname)),
 fullname = ltrim(substring(fullname, locate(' ', fullname), length(fullname)))
 where locate(' ', rtrim(fullname)) > 0;
update parsname set name3 = substring(fullname, 1, locate(' ', fullname)),
 fullname = ltrim(substring(fullname, locate(' ', fullname), length(fullname)))
 where locate(' ', rtrim(fullname)) > 0;
update parsname set name4 = substring(fullname, 1, locate(' ', fullname)),
 fullname = ltrim(substring(fullname, locate(' ', fullname), length(fullname)))
 where locate(' ', rtrim(fullname)) > 0;
// fullname now contains the last word in the string.
select fullname as FirstName, '' as MiddleName, '' as LastName from parsname where fullname is not null and name1 is null and name2 is null
union all
select name1 as FirstName, name2 as MiddleName, fullname as LastName from parsname where name1 is not null and name3 is null

The code works by creating a temporary table (parsname) and tokenizing the fullname by spaces. Any names ending up with values in name3 or name4 are non-conforming and will need to be dealt with differently.

Swift convert unix time to date and time

func timeStringFromUnixTime(unixTime: Double) -> String {
    let date = NSDate(timeIntervalSince1970: unixTime)

    // Returns date formatted as 12 hour time.
    dateFormatter.dateFormat = "hh:mm a"
    return dateFormatter.stringFromDate(date)

func dayStringFromTime(unixTime: Double) -> String {
    let date = NSDate(timeIntervalSince1970: unixTime)
    dateFormatter.locale = NSLocale(localeIdentifier: NSLocale.currentLocale().localeIdentifier)
    dateFormatter.dateFormat = "EEEE"
    return dateFormatter.stringFromDate(date)

Missing artifact com.sun:tools:jar

If you are seeing this on newly installed/upgraded Operating system, it is just because JAVA_HOME is not set properly.

we need to set JAVA_HOME properly. For example on mac: if I want to use java version 1.8.0_261

export JAVA_HOME=`/usr/libexec/java_home -v 1.8.0_261`

Computational complexity of Fibonacci Sequence

Well, according to me to it is O(2^n) as in this function only recursion is taking the considerable time (divide and conquer). We see that, the above function will continue in a tree until the leaves are approaches when we reach to the level F(n-(n-1)) i.e. F(1). So, here when we jot down the time complexity encountered at each depth of tree, the summation series is:

= 1((2^n)-1)/(2-1)
=2^n -1

that is order of 2^n [ O(2^n) ].

How to read a PEM RSA private key from .NET


under Cryptography Application Block.

Don't know if you will get your answer, but it's worth a try.

Edit after Comment.

Ok then check this code.

using System.Security.Cryptography;

public static string DecryptEncryptedData(stringBase64EncryptedData, stringPathToPrivateKeyFile) { 
    X509Certificate2 myCertificate; 
        myCertificate = new X509Certificate2(PathToPrivateKeyFile); 
    } catch{ 
        throw new CryptographicException("Unable to open key file."); 

    RSACryptoServiceProvider rsaObj; 
    if(myCertificate.HasPrivateKey) { 
         rsaObj = (RSACryptoServiceProvider)myCertificate.PrivateKey; 
    } else 
        throw new CryptographicException("Private key not contained within certificate."); 

    if(rsaObj == null) 
        return String.Empty; 

    byte[] decryptedBytes; 
        decryptedBytes = rsaObj.Decrypt(Convert.FromBase64String(Base64EncryptedData), false); 
    } catch { 
        throw new CryptographicException("Unable to decrypt data."); 

    //    Check to make sure we decrpyted the string 
   if(decryptedBytes.Length == 0) 
        return String.Empty; 
        return System.Text.Encoding.UTF8.GetString(decryptedBytes); 

Java - How Can I Write My ArrayList to a file, and Read (load) that file to the original ArrayList?

To save and load an arraylist of public static ArrayList data = new ArrayList ();

I used (to write)...

static void saveDatabase() {
try {

        FileOutputStream fos = new FileOutputStream("mydb.fil");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        databaseIsSaved = true;         

catch (IOException e) {

} // End of saveDatabase

And used (to read) ...

static void loadDatabase() {

try {           
        FileInputStream fis = new FileInputStream("mydb.fil");
        ObjectInputStream ois = new ObjectInputStream(fis);         
        data = (ArrayList<User>)ois.readObject();
catch (IOException e) {
        System.out.println("***catch ERROR***");

catch (ClassNotFoundException e) {
        System.out.println("***catch ERROR***");
} // End of loadDatabase 

Laravel where on relationship object

    return Deal::with(["redeem" => function($q){
        $q->where('user_id', '=', 1);

this worked for me

Handling the null value from a resultset in JAVA

The description of the getString() method says the following:

 the column value; if the value is SQL NULL, the value returned is null

That means your problem is not that the String value is null, rather some other object is, perhaps your ResultSet or maybe you closed the connection or something like this. Provide the stack trace, that would help.

Certificate has either expired or has been revoked

With Xcode Version 10.1 I solved with these steps:

  1. Go to Xcode, Preferences and select the Accounts tab
  2. In the accounts section click on the gear in the bottom left of the window corner and then click on Export Apple ID and Code Signing Assets... exporting this in a file, for example Test.developerprofile
  3. Delete the profile that you are using
  4. Clicking again on the gear select Import Apple ID and Code Signing Assets... and select your previously exported file Test.developerprofile
  5. Now perform a Clean (Shift(?)+Command(?)+K) and a Build (Command(?)+B)
  6. Run again

What dependency is missing for org.springframework.web.bind.annotation.RequestMapping?

I was using spring-web version 4.3.7

Changing it to a working 4.1.7 immediately solved it.


Cast Int to enum in Java

A good option is to avoid conversion from int to enum: for example, if you need the maximal value, you may compare x.ordinal() to y.ordinal() and return x or y correspondingly. (You may need to re-order you values to make such comparison meaningful.)

If that is not possible, I would store MyEnum.values() into a static array.

How to copy a file to multiple directories using the gnu cp command

To use copying with xargs to directories using wildcards on Mac OS, the only solution that worked for me with spaces in the directory name is:

find ./fs*/* -type d -print0 | xargs -0 -n 1 cp test 

Where test is the file to copy
And ./fs*/* the directories to copy to

The problem is that xargs sees spaces as a new argument, the solutions to change the delimiter character using -d or -E is unfortunately not properly working on Mac OS.

IIS7 deployment - duplicate 'system.web.extensions/scripting/scriptResourceHandler' section

In my case I wanted to manually add urlrewrite rule and couldn't see the obvious error (I missed <rules> tag):

wrong code:

      <rule name="some rule" stopProcessing="true">
        <match url="some-pattenr/(.*)" />        
        <action type="Redirect" url="/some-ne-pattenr/{R:1}" />


proper code (with rules tag):

        <rule name="some rule" stopProcessing="true">
          <match url="some-pattenr/(.*)" />        
          <action type="Redirect" url="/some-ne-pattenr/{R:1}" />


How to make rounded percentages add up to 100%

There are many ways to do just this, provided you are not concerned about reliance on the original decimal data.

The first and perhaps most popular method would be the Largest Remainder Method

Which is basically:

  1. Rounding everything down
  2. Getting the difference in sum and 100
  3. Distributing the difference by adding 1 to items in decreasing order of their decimal parts

In your case, it would go like this:


If you take the integer parts, you get


which adds up to 97, and you want to add three more. Now, you look at the decimal parts, which are


and take the largest ones until the total reaches 100. So you would get:


Alternatively, you can simply choose to show one decimal place instead of integer values. So the numbers would be 48.3 and 23.9 etc. This would drop the variance from 100 by a lot.

Does adding a duplicate value to a HashSet/HashMap replace the previous value

Correct me if I'm wrong but what you're getting at is that with strings, "Hi" == "Hi" doesn't always come out true (because they're not necessarily the same object).

The reason you're getting an answer of 1 though is because the JVM will reuse strings objects where possible. In this case the JVM is reusing the string object, and thus overwriting the item in the Hashmap/Hashset.

But you aren't guaranteed this behavior (because it could be a different string object that has the same value "Hi"). The behavior you see is just because of the JVM's optimization.

How to correctly assign a new string value?

The two structs are different. When you initialize the first struct, about 40 bytes of memory are allocated. When you initialize the second struct, about 10 bytesof memory are allocated. (Actual amount is architecture dependent)

You can use the string literals (string constants) to initalize character arrays. This is why

person p = {"John", "Doe",30};

works in the first example.

You cannot assign (in the conventional sense) a string in C.

The string literals you have ("John") are loaded into memory when your code executes. When you initialize an array with one of these literals, then the string is copied into a new memory location. In your second example, you are merely copying the pointer to (location of) the string literal. Doing something like:

char* string = "Hello";
*string = 'C'

might cause compile or runtime errors (I am not sure.) It is a bad idea because you are modifying the literal string "Hello" which, for example on a microcontroler, could be located in read-only memory.

Open a local HTML file using in Chrome

First, make sure that the source page and the target page are both served through the file URI scheme. You can't force an http page to open a file page (but it works the other way around).

Next, your script that calls should be invoked by a user-initiated event, such as clicks, keypresses and the like. Simply calling won't work.

You can test this right here in this question page. Run these in Chrome's JavaScript console:

// Does nothing'');

// Click anywhere within this page and the new window opens
$(document.body).unbind('click').click(function() {''); });

// This will open a new window, but it would be blank
$(document.body).unbind('click').click(function() {'file:///path/to/a/local/html/file.html'); });

You can also test if this works with a local file. Here's a sample HTML file that simply loads jQuery:

        <script type="text/javascript" src=""></script>
        <h5>Feel the presha</h5>
        <h3>Come play my game, I'll test ya</h3>
        <h1>Psycho- somatic- addict- insane!</h1>

Then open Chrome's JavaScript console and run the statements above. The 3rd one will now work.

BSTR to std::string (std::wstring) and vice versa

You could also do this

#include <comdef.h>

BSTR bs = SysAllocString("Hello");
std::wstring myString = _bstr_t(bs, false); // will take over ownership, so no need to free

or std::string if you prefer

EDIT: if your original string contains multiple embedded \0 this approach will not work.

What are naming conventions for MongoDB?

Until we get SERVER-863 keeping the field names as short as possible is advisable especially where you have a lot of records.

Depending on your use case, field names can have a huge impact on storage. Cant understand why this is not a higher priority for MongoDb, as this will have a positive impact on all users. If nothing else, we can start being more descriptive with our field names, without thinking twice about bandwidth & storage costs.

Please do vote.

C++ Get name of type in template

The answer of Logan Capaldo is correct but can be marginally simplified because it is unnecessary to specialize the class every time. One can write:

// in header
template<typename T>
struct TypeParseTraits
{ static const char* name; };

// in c-file
    template <> const char* TypeParseTraits<X>::name = #X

// etc...

This also allows you to put the REGISTER_PARSE_TYPE instructions in a C++ file...

ClassCastException, casting Integer to Double

Well the code you've shown doesn't actually include adding any Integers to the ArrayList - but if you do know that you've got integers, you can use:

sum = (double) ((Integer) marks.get(i)).intValue();

That will convert it to an int, which can then be converted to double. You can't just cast directly between the boxed classes.

Note that if you can possibly use generics for your ArrayList, your code will be clearer.

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

Font Squirrel has a wonderful web font generator.

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

extract date only from given timestamp in oracle sql

In Oracle 11g, To get the complete date from the Timestamp, use this-

Select TRUNC(timestamp) FROM TABLE_NAME;

To get the Year from the Timestamp, use this-


To get the Month from the Timestamp, use this-


To get the Day from the Timestamp, use this-

Select EXTRACT(DAY FROM TRUNC(timestamp)) from TABLE_NAME;

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project.

This happens when Maven tries to run your test cases while building the jar. You can simply skip running the test cases by adding -DskipTests at the end of your maven command.

Ex: mvn clean install -DskipTests or mvn clean package -DskipTests

How to add title to subplots in Matplotlib?

ax.set_title() should set the titles for separate subplots:

import matplotlib.pyplot as plt

if __name__ == "__main__":
    data = [1, 2, 3, 4, 5]

    fig = plt.figure()
    fig.suptitle("Title for whole figure", fontsize=16)
    ax = plt.subplot("211")
    ax.set_title("Title for first plot")

    ax = plt.subplot("212")
    ax.set_title("Title for second plot")

Can you check if this code works for you? Maybe something overwrites them later?

Opening database file from within SQLite command-line shell

I wonder why no one was able to get what the question actually asked. It stated What is the command within the SQLite shell tool to specify a database file?

A sqlite db is on my hard disk E:\ABCD\efg\mydb.db. How do I access it with sqlite3 command line interface? .open E:\ABCD\efg\mydb.db does not work. This is what question asked.

I found the best way to do the work is

  • copy-paste all your db files in 1 directory (say E:\ABCD\efg\mydbs)
  • switch to that directory in your command line
  • now open sqlite3 and then .open mydb.db

This way you can do the join operation on different tables belonging to different databases as well.

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

You could do this:

find ./ -type f -ls |grep '10 Sep'


[root@pbx etc]# find /var/ -type f -ls | grep "Dec 24"
791235    4 -rw-r--r--   1 root     root           29 Dec 24 03:24 /var/lib/prelink/full
798227  288 -rw-r--r--   1 root     root       292323 Dec 24 23:53 /var/log/sa/sar24
797244  320 -rw-r--r--   1 root     root       321300 Dec 24 23:50 /var/log/sa/sa24

Local package.json exists, but node_modules missing

npm start runs a script that the app maker built for easy starting of the app npm install installs all the packages in package.json

run npm install first

then run npm start

How to edit incorrect commit message in Mercurial?

I know this is an old post and you marked the question as answered. I was looking for the same thing recently and I found the histedit extension very useful. The process is explained here:

How to register multiple servlets in web.xml in one Spring application

Use config something like this:





and then you'll need three files:

  • applicationContext.xml;
  • myservlet-servlet.xml; and
  • user-webservice-servlet.xml.

The *-servlet.xml files are used automatically and each creates an application context for that servlet.

From the Spring documentation, 13.2. The DispatcherServlet:

The framework will, on initialization of a DispatcherServlet, look for a file named [servlet-name]-servlet.xml in the WEB-INF directory of your web application and create the beans defined there (overriding the definitions of any beans defined with the same name in the global scope).

What's a redirect URI? how does it apply to iOS app for OAuth2.0?

redirected uri is the location where the user will be redirected after successfully login to your app. for example to get access token for your app in facebook you need to subimt redirected uri which is nothing only the app Domain that your provide when you create your facebook app.

What is the use of the @ symbol in PHP?

The @ symbol is the error control operator (aka the "silence" or "shut-up" operator). It makes PHP suppress any error messages (notice, warning, fatal, etc) generated by the associated expression. It works just like a unary operator, for example, it has a precedence and associativity. Below are some examples:

@echo 1 / 0;
// generates "Parse error: syntax error, unexpected T_ECHO" since 
// echo is not an expression

echo @(1 / 0);
// suppressed "Warning: Division by zero"

@$i / 0;
// suppressed "Notice: Undefined variable: i"
// displayed "Warning: Division by zero"

@($i / 0);
// suppressed "Notice: Undefined variable: i"
// suppressed "Warning: Division by zero"

$c = @$_POST["a"] + @$_POST["b"];
// suppressed "Notice: Undefined index: a"
// suppressed "Notice: Undefined index: b"

$c = @foobar();
echo "Script was not terminated";
// suppressed "Fatal error: Call to undefined function foobar()"
// however, PHP did not "ignore" the error and terminated the
// script because the error was "fatal"

What exactly happens if you use a custom error handler instead of the standard PHP error handler:

If you have set a custom error handler function with set_error_handler() then it will still get called, but this custom error handler can (and should) call error_reporting() which will return 0 when the call that triggered the error was preceded by an @.

This is illustrated in the following code example:

function bad_error_handler($errno, $errstr, $errfile, $errline, $errcontext) {
    echo "[bad_error_handler]: $errstr";
    return true;
echo @(1 / 0);
// prints "[bad_error_handler]: Division by zero"

The error handler did not check if @ symbol was in effect. The manual suggests the following:

function better_error_handler($errno, $errstr, $errfile, $errline, $errcontext) {
    if(error_reporting() !== 0) {
        echo "[better_error_handler]: $errstr";
    // take appropriate action
    return true;

How to print to stderr in Python?

If you do a simple test:

import time
import sys

def run1(runs):
    x = 0
    cur = time.time()
    while x < runs:
        x += 1
        print >> sys.stderr, 'X'
    elapsed = (time.time()-cur)
    return elapsed

def run2(runs):
    x = 0
    cur = time.time()
    while x < runs:
        x += 1
    elapsed = (time.time()-cur)
    return elapsed

def compare(runs):
    sum1, sum2 = 0, 0
    x = 0
    while x < runs:
        x += 1
        sum1 += run1(runs)
        sum2 += run2(runs)
    return sum1, sum2

if __name__ == '__main__':
    s1, s2 = compare(1000)
    print "Using (print >> sys.stderr, 'X'): %s" %(s1)
    print "Using (sys.stderr.write('X'),sys.stderr.flush()):%s" %(s2)
    print "Ratio: %f" %(float(s1) / float(s2))

You will find that sys.stderr.write() is consistently 1.81 times faster!

How to show progress bar while loading, using ajax

$(document).ready(function () { _x000D_
 $(document).ajaxStart(function () {_x000D_
    $(document).ajaxStop(function () {_x000D_
    $(document).ajaxError(function () {_x000D_
    });   _x000D_
<div id="wait" style="display: none; width: 100%; height: 100%; top: 100px; left: 0px; position: fixed; z-index: 10000; text-align: center;">_x000D_
            <img src="../images/loading_blue2.gif" width="45" height="45" alt="Loading..." style="position: fixed; top: 50%; left: 50%;" />_x000D_

Converting an int to a binary string representation in Java?

This should be quite simple with something like this :

public static String toBinary(int number){
    StringBuilder sb = new StringBuilder();

    if(number == 0)
        return "0";
        number = number / 2;

    return sb.reverse().toString();


Spring Boot REST service exception handling

By default Spring Boot gives json with error details.

curl -v localhost:8080/greet | json_pp
< HTTP/1.1 400 Bad Request
   "timestamp" : 1413313361387,
   "exception" : "org.springframework.web.bind.MissingServletRequestParameterException",
   "status" : 400,
   "error" : "Bad Request",
   "path" : "/greet",
   "message" : "Required String parameter 'name' is not present"

It also works for all kind of request mapping errors. Check this article

If you want to create log it to NoSQL. You can create @ControllerAdvice where you would log it and then re-throw the exception. There is example in documentation

How to compare 2 files fast using .NET?

I think there are applications where "hash" is faster than comparing byte by byte. If you need to compare a file with others or have a thumbnail of a photo that can change. It depends on where and how it is using.

private bool CompareFilesByte(string file1, string file2)
    using (var fs1 = new FileStream(file1, FileMode.Open))
    using (var fs2 = new FileStream(file2, FileMode.Open))
        if (fs1.Length != fs2.Length) return false;
        int b1, b2;
            b1 = fs1.ReadByte();
            b2 = fs2.ReadByte();
            if (b1 != b2 || b1 < 0) return false;
        while (b1 >= 0);
    return true;

private string HashFile(string file)
    using (var fs = new FileStream(file, FileMode.Open))
    using (var reader = new BinaryReader(fs))
        var hash = new SHA512CryptoServiceProvider();
        return Convert.ToBase64String(hash.Hash);

private bool CompareFilesWithHash(string file1, string file2)
    var str1 = HashFile(file1);
    var str2 = HashFile(file2);
    return str1 == str2;

Here, you can get what is the fastest.

var sw = new Stopwatch();
var compare1 = CompareFilesWithHash(receiveLogPath, logPath);
Debug.WriteLine(string.Format("Compare using Hash {0}", sw.ElapsedTicks));
var compare2 = CompareFilesByte(receiveLogPath, logPath);
Debug.WriteLine(string.Format("Compare byte-byte {0}", sw.ElapsedTicks));

Optionally, we can save the hash in a database.

Hope this can help

How to make --no-ri --no-rdoc the default for gem install?

On Windows7 the .gemrc file is not present, you can let Ruby create one like this (it's not easy to do this in explorer).

gem sources --add

You will have to confirm (it's unsafe). Now the file is created in your userprofile folder (c:\users\)

You can edit the textfile to remove the source you added or you can remove it with

gem sources --remove

Why is my toFixed() function not working?

I tried function toFixed(2) many times. Every time console shows "toFixed() is not a function".

but how I resolved is By using Math.round()


if ($(this).attr('name') == 'time') {
    var value = parseFloat($(this).val());
    value = Math.round(value*100)/100; // 10 defines 1 decimals, 100 for 2, 1000 for 3

this thing surely works for me and it might help you guys too...

How do you clear the focus in javascript?


Works wrong on IE9 - it blurs the whole browser window if active element is document body. Better to check for this case:

if (document.activeElement != document.body) document.activeElement.blur();

moving committed (but not pushed) changes to a new branch after pull

A simpler approach, which I have been using (assuming you want to move 4 commits):

git format-patch HEAD~4

(Look in the directory from which you executed the last command for the 4 .patch files)

git reset HEAD~4 --hard

git checkout -b tmp/my-new-branch


git apply /path/to/patch.patch

In whatever order you wanted.

Create a temporary table in a SELECT statement without a separate CREATE TABLE

Engine must be before select:

as (select * from table1)

Using Intent in an Android application to show another activity

b1 = (Button) findViewById(;
        b1.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {

                Intent i = new Intent(MainActivity.this, SecondActivity.class);


Encrypt Password in Configuration Files?

Try using ESAPIs Encryption methods. Its easy to configure and you can also easily change your keys.


1)encrypt 2)decrypt 3)sign 4)unsign 5)hashing 6)time based signatures and much more with just one library.

How to store Node.js deployment settings/configuration files?

I tryied some of suggested solutions here, but was not sattisfied with them, so I created my own module. It is called mikro-config and the main difference is that it honors convention over configuration, so you can just require the module and start using it.

You store your configuration in either plain js, or json files from /config folder. First it loads default.js file, then all other files from /config directory, then it loads environment specific configuration based on $NODE_ENV variable.

It also allows to override this configuration for local development with local.js or environment specific /config/env/$NODE_ENV.local.js.

You can take at look at it here:

Git push error '[remote rejected] master -> master (branch is currently checked out)'

The best way to do this is:

mkdir ..../remote
cd ..../remote
git clone --bare .../currentrepo/

This will clone the repository, but it won't make any working copies in .../remote. If you look at the remote, you'll see one directory created, called currentrepo.git, which is probably what you want.

Then from your local Git repository:

git remote add remoterepo ..../remote/currentrepo.git

After you make changes, you can:

git push remoterepo master

How to find sum of several integers input by user using do/while, While statement or For statement

You should do:

using namespace std;
int main ()

    int sum = 0;
    int number;
    int numberitems;

    cout << "Enter number of items: \n";
    cin >> numberitems;

    for(int i=0;i<numberitems;i++)
        cout << "Enter number <<i<<":" \n";
        cin >> number; sum+=number;
    cout<<"sum is: "<< sum<<endl;

And with a while statement

#include <iostream>
using namespace std;
int main ()
    int sum = 0;
    int number;
    int numberitems;

    cout << "Enter number: \n";

    while (count <=numberitems)
        cin >> number;
    cout << sum << endl;

OAuth: how to test with local URLs?

Or you can use and configure how it should redirect a callback to your local site. You can specify the hostname (if different from localhost, i.e. yourapp.local and the port number). For development purposes only.

Bootstrap button drop-down inside responsive table not visible because of scroll

Cleaned up @Wazime solution a little. Works great as a general solution.

$(document).on('', '.table-responsive', function (e) {
    // The .dropdown container
    var $container = $(;

    // Find the actual .dropdown-menu
    var $dropdown = $container.find('.dropdown-menu');
    if ($dropdown.length) {
        // Save a reference to it, so we can find it after we've attached it to the body
        $'dropdown-menu', $dropdown);
    } else {
        $dropdown = $'dropdown-menu');

    $dropdown.css('top', ($container.offset().top + $container.outerHeight()) + 'px');
    $dropdown.css('left', $container.offset().left + 'px');
    $dropdown.css('position', 'absolute');
    $dropdown.css('display', 'block');

$(document).on('', '.table-responsive', function (e) {
    // Hide the dropdown menu bound to this button
    $('dropdown-menu').css('display', 'none');

How to identify numpy types in python?

Note that the type(numpy.ndarray) is a type itself and watch out for boolean and scalar types. Don't be too discouraged if it's not intuitive or easy, it's a pain at first.

See also: - -

>>> import numpy as np
>>> np.ndarray
<class 'numpy.ndarray'>
>>> type(np.ndarray)
<class 'type'>
>>> a = np.linspace(1,25)
>>> type(a)
<class 'numpy.ndarray'>
>>> type(a) == type(np.ndarray)
>>> type(a) == np.ndarray
>>> isinstance(a, np.ndarray)

Fun with booleans:

>>> b = a.astype('int32') == 11
>>> b[0]
>>> isinstance(b[0], bool)
>>> isinstance(b[0], np.bool)
>>> isinstance(b[0], np.bool_)
>>> isinstance(b[0], np.bool8)
>>> b[0].dtype == np.bool
>>> b[0].dtype == bool  # python equivalent

More fun with scalar types, see: -

>>> x = np.array([1,], dtype=np.uint64)
>>> x[0].dtype
>>> isinstance(x[0], np.uint64)
>>> isinstance(x[0], np.integer)
True  # generic integer
>>> isinstance(x[0], int)
False  # but not a python int in this case

# Try matching the `kind` strings, e.g.
>>> np.dtype('bool').kind                                                                                           
>>> np.dtype('int64').kind                                                                                          
>>> np.dtype('float').kind                                                                                          
>>> np.dtype('half').kind                                                                                           

# But be weary of matching dtypes
>>> np.integer
<class 'numpy.integer'>
>>> np.dtype(np.integer)
>>> x[0].dtype == np.dtype(np.integer)

# Down these paths there be dragons:

# the .dtype attribute returns a kind of dtype, not a specific dtype
>>> isinstance(x[0].dtype, np.dtype)
>>> isinstance(x[0].dtype, np.uint64)
>>> isinstance(x[0].dtype, np.dtype(np.uint64))
Traceback (most recent call last):
  File "<console>", line 1, in <module>
TypeError: isinstance() arg 2 must be a type or tuple of types
# yea, don't go there
>>> isinstance(x[0].dtype, np.int_)
False  # again, confusing the .dtype with a specific dtype

# Inequalities can be tricky, although they might
# work sometimes, try to avoid these idioms:

>>> x[0].dtype <= np.dtype(np.uint64)
>>> x[0].dtype <= np.dtype(np.float)
>>> x[0].dtype <= np.dtype(np.half)
False  # just when things were going well
>>> x[0].dtype <= np.dtype(np.float16)
False  # oh boy
>>> x[0].dtype ==
False  # ya, no luck here either
>>> x[0].dtype == np.int_
False  # or here
>>> x[0].dtype == np.uint64
True  # have to end on a good note!

grant remote access of MySQL database from any IP address

what worked for on Ubuntu is granting all privileges to the user:


and setting the bind address in /etc/mysql/mysql.conf.d/mysqld.cnf:

bind-address            =

then restarting the mysql daemon:

service mysql restart

How to preSelect an html dropdown list with php?

<option value="1" <?php if ($myVar==1) echo 'selected="selected"';?>>Yes</options>
<option value="2" <?php if ($myVar==2) echo 'selected="selected"';?>>No</options>
<option value="3" <?php if ($myVar==3) echo 'selected="selected"';?>>Fine</options>
<input type="text" value="" name="name">
<input type="submit" value="go" name="go">

This is a very simple and straightforward way, if I understand your question correctly.

Insert data into hive table

Although there is an accepted answer I would want to add that as of Hive 0.14, record level operations are allowed. The correct syntax and query would be:

INSERT INTO TABLE tweet_table VALUES ('data');

Looking for simple Java in-memory cache

How about this: (updated to new address, as JCS is now in Apache Commons)

Using unset vs. setting a variable to empty

As has been said, using unset is different with arrays as well

$ foo=(4 5 6)

$ foo[2]=

$ echo ${#foo[*]}

$ unset foo[2]

$ echo ${#foo[*]}

Xcode 4: How do you view the console?

for Xcode 5:

View->Debug Area->Activate Console

shift + cmd + c

#1146 - Table 'phpmyadmin.pma_recent' doesn't exist

This one just worked for me....

The error message displayed is:

“# 1146 – Table ‘phpmyadmin.pma_table_uiprefs’ doesn’t exist“

on your programme files,locate the configuration file phpmyadmin

Then trace the file $Cfg ['Servers'] [$ i] ['table_uiprefs'] = ‘pma_table_uiprefs’;

and replace it to the code : $cfg ['Servers'] [$ i] ['pma__table_uiprefs'] = ‘pma__table_uiprefs’;

restart your XAMMP and start localhost


curl Failed to connect to localhost port 80

If anyone else comes across this and the accepted answer doesn't work (it didn't for me), check to see if you need to specify a port other than 80. In my case, I was running a rails server at localhost:3000 and was just using curl http://localhost, which was hitting port 80.

Changing the command to curl http://localhost:3000 is what worked in my case.

IEnumerable<object> a = new IEnumerable<object>(); Can I do this?

You can for example create an instance of List<object>, which implements IEnumerable<object>. Example:

List<object> list = new List<object>();

IEnumerable<object> en = list;

How to change font-size of a tag using inline css?

Strange it doesn't change, as inline styles are most specific, if style sheet has !important declared, it wont over ride, try this and see

<span style="font-size: 11px !important; color: #aaaaaa;">Hello</span>

String delimiter in string.split method

Double quotes are interpreted as literals in regex; they are not special characters. You are trying to match a literal "||".

Just use Pattern.quote(delimiter):

As requested, here's a line of code (same as Sanjay's)

final String[] tokens = line.split(Pattern.quote(delimiter));

If that doesn't work, you're not passing in the correct delimiter.

how to setup ssh keys for jenkins to publish via ssh

For Windows:

  1. Install the necessary plugins for the repository (ex: GitHub install GitHub and GitHub Authentication plugins) in Jenkins.
  2. You can generate a key with Putty key generator, or by running the following command in git bash: $ ssh-keygen -t rsa -b 4096 -C [email protected]
  3. Private key must be OpenSSH. You can convert your private key to OpenSSH in putty key generator
  4. SSH keys come in pairs, public and private. Public keys are inserted in the repository to be cloned. Private keys are saved as credentials in Jenkins
  5. You need to copy the SSH URL not the HTTPS to work with ssh keys.

Use images instead of radio buttons

Keep radio buttons hidden, and on clicking of images, select them using JavaScript and style your image so that it look like selected. Here is the markup -

<div id="radio-button-wrapper">
    <span class="image-radio">
        <input name="any-name" style="display:none" type="radio"/>
        <img src="...">
    <span class="image-radio">
        <input name="any-name" style="display:none" type="radio"/>
        <img src="...">

and JS

 $(".image-radio img").click(function(){


span.image-radio input[type="radio"]:checked + img{
    border:1px solid red;

jQuery first child of "this"

Have you tried

$(":first-child", element).toggleClass("redClass");

I think you want to set your element as a context for your search. There might be a better way to do this which some other jQuery guru will hop in here and throw out at you :)

How to generate class diagram from project in Visual Studio 2013?

For creating real UML class diagrams:

In Visual Studio 2013 Ultimate you can do this without any external tools.

  • In the menu, click on Architecture, New Diagram Select UML Class Diagram
  • This will ask you to create a new Modeling Project if you don't have one already.

You will have a empty UMLClassDiagram.classdiagram.

  • Again, go to Architecture, Windows, Architecture Explorer.
  • A window will pop up with your namespaces, Choose Class View.
  • Then a list of sub-namespaces will appear, if any. Choose one, select the classes and drag them to the empty UMLClassDiagram1.classdiagram window.

Reference: Create UML Class Diagrams from Code

iPhone: How to get current milliseconds?

I benchmarked all the other answers on an iPhone 4S and iPad 3 (release builds). CACurrentMediaTime has the least overhead by a small margin. timeIntervalSince1970 is far slower than the others, probably due to NSDate instantiation overhead, though it may not matter for many use cases.

I'd recommend CACurrentMediaTime if you want the least overhead and don't mind adding the Quartz Framework dependency. Or gettimeofday if portability is a priority for you.

iPhone 4S

CACurrentMediaTime: 1.33 µs/call
gettimeofday: 1.38 µs/call
[NSDate timeIntervalSinceReferenceDate]: 1.45 µs/call
CFAbsoluteTimeGetCurrent: 1.48 µs/call
[[NSDate date] timeIntervalSince1970]: 4.93 µs/call

iPad 3

CACurrentMediaTime: 1.25 µs/call
gettimeofday: 1.33 µs/call
CFAbsoluteTimeGetCurrent: 1.34 µs/call
[NSDate timeIntervalSinceReferenceDate]: 1.37 µs/call
[[NSDate date] timeIntervalSince1970]: 3.47 µs/call

How to print a two dimensional array?

You should loop by rows and then columns with a structure like

for ...row index...
  for ...column index...

but I guess this is homework so just try it out yourself.

Swap the row/column index in the for loops depending on if you need to go across first and then down, vs. down first and then across.

Sniff HTTP packets for GET and POST requests from an application

You will have to use some sort of network sniffer if you want to get at this sort of data and you're likely to run into the same problem (pulling out the relevant data from the overall network traffic) with those that you do now with Wireshark.

How to negate 'isblank' function

I suggest:


which returns TRUE if A1 is populated and FALSE otherwise. Which compares with:


which returns TRUE if A1 is empty and otherwise FALSE.

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

Content Type for MOV videos are video/quicktime in my case. Adding type="video/mp4" to MOV video file solved issue in my case.

<video width="400" controls Autoplay=autoplay>
  <source src="D:/" type="video/mp4">

adb not finding my device / phone (MacOS X)

None of the above answers worked for me. On macOS Mojave, open console app, you may see an error like this:

001076.240057 adb@(null): IOUSBUserClientLegacy::start: missing entitlement

Even resetting the mac PFRAM didn't help. To fix this issue:

  1. Connect Android device via USB cable(double USB-C cable worked for me).

  2. Go to Settings -> .. -> Developer Options and click Revoke USB debugging authorizations

  3. The Android phone will go for a reboot.

  4. Go to Settings -> .. -> Developer Options and make sure USB debugging is enabled.

  5. Now in macOS terminal enter:

    adb devices
  6. You can see your device listed.

It worked for my Google Pixel 2 phone.

Deserialize json object into dynamic object using

Json.NET allows us to do this:

dynamic d = JObject.Parse("{number:1000, str:'string', array: [1,2,3,4,5,6]}");




Documentation here: LINQ to JSON with Json.NET

See also JObject.Parse and JArray.Parse

Uncaught Invariant Violation: Too many re-renders. React limits the number of renders to prevent an infinite loop

You need to add an event, before call your handleFunction like this:

function SingInContainer() {
handleClose = () => {

return (
        handleClose={() => handleClose}


Difference in System. exit(0) , System.exit(-1), System.exit(1 ) in Java

System.exit(0) by convention, a zero status code indicates successful termination.

System.exit(1) -It means termination unsuccessful due to some error

How to "log in" to a website using Python's Requests module?

Find out the name of the inputs used on the websites form for usernames <> and passwords <> and replace them in the script below. Also replace the URL to point at the desired site to log into.

#!/usr/bin/env python

import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
payload = { 'username': '[email protected]', 'password': 'blahblahsecretpassw0rd' }
url = '', data=payload, verify=False)

The use of disable_warnings(InsecureRequestWarning) will silence any output from the script when trying to log into sites with unverified SSL certificates.


To run this script from the command line on a UNIX based system place it in a directory, i.e. home/scripts and add this directory to your path in ~/.bash_profile or a similar file used by the terminal.

# Custom scripts
export CUSTOM_SCRIPTS=home/scripts

Then create a link to this python script inside home/scripts/

ln -s ~/home/scripts/ ~/home/scripts/login

Close your terminal, start a new one, run login

Question mark and colon in statement. What does it mean?

It's a ternary operator, or the short form for if..else.

condition ? value if true : value if false

See Microsoft Docs | ?: operator (C# reference).

Proper way to assert type of variable in Python

Doing type('') is effectively equivalent to str and types.StringType

so type('') == str == types.StringType will evaluate to "True"

Note that Unicode strings which only contain ASCII will fail if checking types in this way, so you may want to do something like assert type(s) in (str, unicode) or assert isinstance(obj, basestring), the latter of which was suggested in the comments by 007Brendan and is probably preferred.

isinstance() is useful if you want to ask whether an object is an instance of a class, e.g:

class MyClass: pass

print isinstance(MyClass(), MyClass) # -> True
print isinstance(MyClass, MyClass()) # -> TypeError exception

But for basic types, e.g. str, unicode, int, float, long etc asking type(var) == TYPE will work OK.

click or change event on radio using jquery

$( 'input[name="testGroup"]:radio' ).on('change', function(e) {_x000D_
     return false;_x000D_

This syntax is a little more flexible to handle events. Not only can you observe "changes", but also other types of events can be controlled here too by using one single event handler. You can do this by passing the list of events as arguments to the first parameter. See jQuery On

Secondly, .change() is a shortcut for .on( "change", handler ). See here. I prefer using .on() rather than .change because I have more control over the events.

Lastly, I'm simply showing an alternative syntax to attach the event to the element.

If WorkSheet("wsName") Exists

Slightly changed to David Murdoch's code for generic library

Function HasByName(cSheetName As String, _ 
                   Optional oWorkBook As Excel.Workbook) As Boolean

    HasByName = False
    Dim wb

    If oWorkBook Is Nothing Then
        Set oWorkBook = ThisWorkbook
    End If

    For Each wb In oWorkBook.Worksheets
        If wb.Name = cSheetName Then
            HasByName = True
            Exit Function
        End If
    Next wb
End Function

Populate unique values into a VBA array from Excel

OK I did it finally:

Sub CountUniqueRecords()
Dim Array() as variant, UniqueArray() as variant, UniqueNo as Integer,      
Dim i as integer, j as integer, k as integer

Redim UnquiArray(1)

k= Upbound(array)

For i = 1 To k
For j = 1 To UniqueNo + 1
  If Array(i) = UniqueArray(j) Then GoTo Nx
Next j
  UniqueNo = UniqueNo + 1
  ReDim Preserve UniqueArray(UniqueNo + 1)
  UniqueArray(UniqueNo) = Array(i)
Next i

MsgBox UniqueNo

End Sub

Return anonymous type results?

If you have a relationship setup in your database with a foriegn key restraint on BreedId don't you get that already?

DBML relationship mapping

So I can now call:

internal Album GetAlbum(int albumId)
    return Albums.SingleOrDefault(a => a.AlbumID == albumId);

And in the code that calls that:

var album = GetAlbum(1);

foreach (Photo photo in album.Photos)

So in your instance you'd be calling something like dog.Breed.BreedName - as I said, this relies on your database being set up with these relationships.

As others have mentioned, the DataLoadOptions will help reduce the database calls if that's an issue.

Save image from url with curl PHP

Improved version of Komang answer (add referer and user agent, check if you can write the file), return true if it's ok, false if there is an error :

public function downloadImage($url,$filename){
    $fp = fopen($filename,'w');
        $ch = curl_init ($url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
        $result = parse_url($url);
        curl_setopt($ch, CURLOPT_REFERER, $result['scheme'].'://'.$result['host']);
        curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0');
        curl_close ($ch);
            fwrite($fp, $raw);
            return false;
        return true;
    return false;

How to set response header in JAX-RS so that user sees download popup for Excel?

You don't need HttpServletResponse to set a header on the response. You can do it using Just make your method to return Response instead of entity:

return Response.ok(entity).header("Content-Disposition", "attachment; filename=\"" + fileName + "\"").build()

If you still want to use HttpServletResponse you can get it either injected to one of the class fields, or using property, or to method parameter:

class MyResource {

  // one way to get HttpServletResponse
  private HttpServletResponse anotherServletResponse;

  // another way
  Response myMethod(@Context HttpServletResponse servletResponse) {
      // ... code

@JsonProperty annotation on field as well as getter/setter

In addition to existing good answers, note that Jackson 1.9 improved handling by adding "property unification", meaning that ALL annotations from difference parts of a logical property are combined, using (hopefully) intuitive precedence.

In Jackson 1.8 and prior, only field and getter annotations were used when determining what and how to serialize (writing JSON); and only and setter annotations for deserialization (reading JSON). This sometimes required addition of "extra" annotations, like annotating both getter and setter.

With Jackson 1.9 and above these extra annotations are NOT needed. It is still possible to add those; and if different names are used, one can create "split" properties (serializing using one name, deserializing using other): this is occasionally useful for sort of renaming.

How to use an environment variable inside a quoted string in Bash

The following script works for me for multiple values of $COLUMNS. I wonder if you are not setting COLUMNS prior to this call?

svn diff $@ --diff-cmd /usr/bin/diff -x "-y -w -p -W $COLUMNS"

Can you echo $COLUMNS inside your script to see if it set correctly?

Conda update failed: SSL error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed

Conda needs to know where to find you SSL certificate store.

conda config --set ssl_verify <pathToYourFile>.crt

No need to disable SSL verification.

This command add a line to your $HOME/.condarc file or %USERPROFILE%\.condarc file on Windows that looks like:

ssl_verify: <pathToYourFile>.crt

If you leave your organization's network, you can just comment out that line in .condarc with a # and uncomment when you return.

If it still doesn't work, make sure that you are using the latest version of curl, checking both the conda-forge and anaconda channels.

How can I properly handle 404 in ASP.NET MVC?

Quick Answer / TL;DR

enter image description here

For the lazy people out there:

Install-Package MagicalUnicornMvcErrorToolkit -Version 1.0

Then remove this line from global.asax

GlobalFilters.Filters.Add(new HandleErrorAttribute());

And this is only for IIS7+ and IIS Express.

If you're using Cassini .. well .. um .. er.. awkward ... awkward

Long, explained answer

I know this has been answered. But the answer is REALLY SIMPLE (cheers to David Fowler and Damian Edwards for really answering this).

There is no need to do anything custom.

For ASP.NET MVC3, all the bits and pieces are there.

Step 1 -> Update your web.config in TWO spots.

    <customErrors mode="On" defaultRedirect="/ServerError">
      <error statusCode="404" redirect="/NotFound" />


    <httpErrors errorMode="Custom">
      <remove statusCode="404" subStatusCode="-1" />
      <error statusCode="404" path="/NotFound" responseMode="ExecuteURL" />
      <remove statusCode="500" subStatusCode="-1" />
      <error statusCode="500" path="/ServerError" responseMode="ExecuteURL" />


Now take careful note of the ROUTES I've decided to use. You can use anything, but my routes are

  • /NotFound <- for a 404 not found, error page.
  • /ServerError <- for any other error, include errors that happen in my code. this is a 500 Internal Server Error

See how the first section in <system.web> only has one custom entry? The statusCode="404" entry? I've only listed one status code because all other errors, including the 500 Server Error (ie. those pesky error that happens when your code has a bug and crashes the user's request) .. all the other errors are handled by the setting defaultRedirect="/ServerError" .. which says, if you are not a 404 page not found, then please goto the route /ServerError.

Ok. that's out of the way.. now to my routes listed in global.asax

Step 2 - Creating the routes in Global.asax

Here's my full route section..

public static void RegisterRoutes(RouteCollection routes)
    routes.IgnoreRoute("{*favicon}", new {favicon = @"(.*/)?favicon.ico(/.*)?"});

        "Error - 404",
        new { controller = "Error", action = "NotFound" }

        "Error - 500",
        new { controller = "Error", action = "ServerError"}

        "Default", // Route name
        "{controller}/{action}/{id}", // URL with parameters
        new {controller = "Home", action = "Index", id = UrlParameter.Optional}

That lists two ignore routes -> axd's and favicons (ooo! bonus ignore route, for you!) Then (and the order is IMPERATIVE HERE), I have my two explicit error handling routes .. followed by any other routes. In this case, the default one. Of course, I have more, but that's special to my web site. Just make sure the error routes are at the top of the list. Order is imperative.

Finally, while we are inside our global.asax file, we do NOT globally register the HandleError attribute. No, no, no sir. Nadda. Nope. Nien. Negative. Noooooooooo...

Remove this line from global.asax

GlobalFilters.Filters.Add(new HandleErrorAttribute());

Step 3 - Create the controller with the action methods

Now .. we add a controller with two action methods ...

public class ErrorController : Controller
    public ActionResult NotFound()
        Response.StatusCode = (int)HttpStatusCode.NotFound;
        return View();

    public ActionResult ServerError()
        Response.StatusCode = (int)HttpStatusCode.InternalServerError;

        // Todo: Pass the exception into the view model, which you can make.
        //       That's an exercise, dear reader, for -you-.
        //       In case u want to pass it to the view, if you're admin, etc.
        // if (User.IsAdmin) // <-- I just made that up :) U get the idea...
        // {
        //     var exception = Server.GetLastError();
        //     // etc..
        // }

        return View();

    // Shhh .. secret test method .. ooOOooOooOOOooohhhhhhhh
    public ActionResult ThrowError()
        throw new NotImplementedException("Pew ^ Pew");

Ok, lets check this out. First of all, there is NO [HandleError] attribute here. Why? Because the built in ASP.NET framework is already handling errors AND we have specified all the shit we need to do to handle an error :) It's in this method!

Next, I have the two action methods. Nothing tough there. If u wish to show any exception info, then u can use Server.GetLastError() to get that info.

Bonus WTF: Yes, I made a third action method, to test error handling.

Step 4 - Create the Views

And finally, create two views. Put em in the normal view spot, for this controller.

enter image description here

Bonus comments

  • You don't need an Application_Error(object sender, EventArgs e)
  • The above steps all work 100% perfectly with Elmah. Elmah fraking wroxs!

And that, my friends, should be it.

Now, congrats for reading this much and have a Unicorn as a prize!

enter image description here

What does "subject" mean in certificate?

The Subject, in security, is the thing being secured. In this case it could be a persons email or a website or a machine.

If we take the example of an email, say my email, then the subject key container would be the protected location containing my private key.

The certificate store usually refers to Microsoft certificate store which contains certificates form trusted roots, machines on the network, people etc. In my case the subjects certificate store would be the place, within this store, holding my certificates.

If you are working within a microsoft domain then the subject name will invariably hold the Distinguished Name, of the subject, which is how the domain references the subject and holds it in its directory. e.g. CN=Mark Sutton, OU=Developers, O=Mycompany C=UK

To look at your certificates on a microsoft machine:-

Log in as you run>mmc Select File>add/remove snap-in and select certificates then select my user account click Finish then close then ok. Look in the personal area of the store.

In the other areas of the store you will see the other trusted certificates used to validate signatures etc.

A JNI error has occurred, please check your installation and try again in Eclipse x86 Windows 8.1

I hope this helps somebody else. I was suffering with this while working on a project a few years ago and then a job in a newer project started failing a few days ago. I found this post and was trying to recollect what I had modified in my project and then I remembered that I had changed my maven pom and removed the entry for maven-jar-plugin. When you build a jar whose purpose is to be executable, you need to include this so that certain entries get written into the manifest. I opened the old project, copied that entry (with some modifications for project name) and it worked.

Can an XSLT insert the current date?

    xmlns:local="urn:local" extension-element-prefixes="msxsl">

    <msxsl:script language="CSharp" implements-prefix="local">
        public string dateTimeNow()
          return DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ssZ"); 
    <xsl:value-of select="local:dateTimeNow()"/>

T-test in Pandas

it depends what sort of t-test you want to do (one sided or two sided dependent or independent) but it should be as simple as:

from scipy.stats import ttest_ind

cat1 = my_data[my_data['Category']=='cat1']
cat2 = my_data[my_data['Category']=='cat2']

ttest_ind(cat1['values'], cat2['values'])
>>> (1.4927289925706944, 0.16970867501294376)

it returns a tuple with the t-statistic & the p-value

see here for other t-tests

Keyboard shortcut to comment lines in Sublime Text 2

First Open The Sublime Text 2.

And top menu bar on select the Preferences.

And than select the Key Bindings -User.

And than put this code,

    { "keys": ["ctrl+shift+c"], "command": "toggle_comment", "args": { "block": false } },

    { "keys": ["ctrl+shift+c"], "command": "toggle_comment", "args": { "block": true } }

I use Ctrl+Shift+C, You also different short cut key use.

How to add a ScrollBar to a Stackpanel

For horizontally oriented StackPanel, explicitly putting both the scrollbar visibilities worked for me to get the horizontal scrollbar.

    <ScrollViewer VerticalScrollBarVisibility="Hidden" HorizontalScrollBarVisibility="Auto" >
        <StackPanel Orientation="Horizontal" />

Change key pair for ec2 instance

Thanks for the tips guys. Will definitely keep them in mind when I need to rest the key pairs. However, in the interest of efficiency and laziness I've come up with something else:

  1. Create your new key pair and download the credentials
  2. Right-click your instance > Create AMI Once it is done
  3. terminate your instance (or just stop it until you are sure you can create another one from your new shiny AMI)
  4. Start a new EC2 instance from the AMI you just created and specify your new key pair created in step (1) above.

Hope this can be of use to you and save you some time as well as minimize the amount of white hair you get from stuff like this :)

How to find whether or not a variable is empty in Bash?

[ "$variable" ] || echo empty
: ${variable="value_to_set_if_unset"}

Parse an URL in JavaScript

If your string is called s then

var id = s.match(/img_id=([^&]+)/)[1]

will give it to you.

How to add fonts to create-react-app based projects?

You can use the WebFont module, which greatly simplifies the process.

     custom: {
       families: ['MyFont'],
       urls: ['/fonts/MyFont.woff']
  return (
    <div style={your style} >
      your text!

Java SE 6 vs. JRE 1.6 vs. JDK 1.6 - What do these mean?

When you type "java -version", you see three version numbers - the java version (on mine, that's "1.6.0_07"), the Java SE Runtime Environment version ("build 1.6.0_07-b06"), and the HotSpot version (on mine, that's "build 10.0-b23, mixed mode"). I suspect the "11.0" you are seeing is the HotSpot version.

Update: HotSpot is (or used to be, now they seem to use it to mean the whole VM) the just-in-time compiler that is built in to the Java Virtual Machine. God only knows why Sun gives it a separate version number.

Docker official registry (Docker Hub) URL

You're able to get the current registry-url using docker info:

Debug Mode (server): false

That's also the url you may use to run your self hosted-registry:

docker run -d -p 5000:5000 --name registry -e REGISTRY_PROXY_REMOTEURL= registry:2

Grep & use it right away:

$ echo $(docker info | grep -oP "(?<=Registry: ).*")

Impersonate tag in Web.Config

The identity section goes under the system.web section, not under authentication:

  <authentication mode="Windows"/>
  <identity impersonate="true" userName="foo" password="bar"/>

jQuery check if an input is type checkbox?


this is the only work, to solve the issue to detect if checkbox checked or not. It returns true or false, I search it for hours and try everything, now its work to be clear I use EDG as browser and W2UI

Android: how to handle button click

There are also options available in the form of various libraries that can make this process very familiar to people that have used other MVVM frameworks.

Shows an example of an official library, that allows you to bind buttons like this:

    android:text="Start second activity"
    android:onClick="@{() -> presenter.showList()}"

What is the difference between a pandas Series and a single-column DataFrame?

from the pandas doc Series is a one-dimensional labeled array capable of holding any data type. To read data in form of panda Series:

import pandas as pd
ds = pd.Series(data, index=index)

DataFrame is a 2-dimensional labeled data structure with columns of potentially different types.

import pandas as pd
df = pd.DataFrame(data, index=index)

In both of the above index is list

for example: I have a csv file with following data:

IN,India,10458,457787,New Delhi

To read above data as series and data frame:

import pandas as pd
file_data = pd.read_csv("file_path", index_col=0)
d = pd.Series(, index=['BR','RU','IN'] or index =  file_data.index)


>>> d
BR           Brazil
RU           Russia
IN            India

df = pd.DataFrame(file_data.area, index=['BR','RU','IN'] or index = file_data.index )


>>> df
BR   12015
RU     457
IN  457787

How to create a collapsing tree table in html/css/js?

HTML 5 allows summary tag, details element. That can be used to view or hide (collapse/expand) a section. Link

Confused about __str__ on list in Python

Because of the infinite superiority of Python over Java, Python has not one, but two toString operations.

One is __str__, the other is __repr__

__str__ will return a human readable string. __repr__ will return an internal representation.

__repr__ can be invoked on an object by calling repr(obj) or by using backticks `obj`.

When printing lists as well as other container classes, the contained elements will be printed using __repr__.

How to redirect back to form with input - Laravel 5

You can try this:

return redirect()->back()->withInput(Input::all())->with('message', 'Something 
went wrong!');

Replace HTML Table with Divs

You can create simple float-based forms without having to lose your liquid layout. For example:

<style type="text/css">
    .row { clear: left; padding: 6px; }
    .row label { float: left; width: 10em; }
    .row .field { display: block; margin-left: 10em; }
    .row .field input, .row .field select {
        width: 100%;
        box-sizing: border-box;
        -moz-box-sizing: border-box; -webkit-box-sizing: border-box; -khtml-box-sizing: border-box;

<div class="row">
    <label for="f-firstname">First name</label>
    <span class="field"><input name="firstname" id="f-firstname" value="Bob" /></span>
<div class="row">
    <label for="f-state">State</label>
    <span class="field"><select name="state" id="f-state">
        <option value="NY">NY</option>

This does tend to break down, though, when you have complex form layouts where there's a grid of multiple fixed and flexible width columns. At that point you have to decide whether to stick with divs and abandon liquid layout in favour of just dropping everything into fixed pixel positions, or let tables do it.

For me personally, liquid layout is a more important usability feature than the exact elements used to lay out the form, so I usually go for tables.

How do you check what version of SQL Server for a database using TSQL?


SELECT @@MICROSOFTVERSION / 0x01000000 AS MajorVersionNumber

For more information see: Querying for version/edition info

CMD: How do I recursively remove the "Hidden"-Attribute of files and directories

You can't remove hidden without also removing system.

You want:

cd mydir
attrib -H -S /D /S

That will remove the hidden and system attributes from all the files/folders inside of your current directory.

Python Requests library redirect new url

the documentation has this blurb

import requests

r = requests.get('')
#returns instead of the http page you asked for 

Tree data structure in C#

If you would like to write your own, you can start with this six-part document detailing effective usage of C# 2.0 data structures and how to go about analyzing your implementation of data structures in C#. Each article has examples and an installer with samples you can follow along with.

“An Extensive Examination of Data Structures Using C# 2.0” by Scott Mitchell

Find size of Git repository

If you use git LFS, git count-objects does not count your binaries, but only the pointers to them.

If your LFS files are managed by Artifactorys, you should use the REST API:

  • Get the API from any search engine
  • Look at Get Storage Summary Info

Visual Studio debugging/loading very slow

Yet another possible cause is pre-compilation of old projects that exist on the file system but have been removed or partially removed from visual studio.

I had a solution that was taking 3.5 minutes to load after a build, I had a look at the timestamps in Temporary ASP.NET Files and saw that the 3 minute delay was on a file in an old project. Had a look in VS & the project was "unavailable". Deleted it from VS, deleted from the file system, and now we're down to a sweet 8 seconds.

Convert HTML + CSS to PDF

Why don’t you try mPDF version 2.0? I used it for creating PDF a document. It works fine.

Meanwhile mPDF is at version 5.7 and it is actively maintained, in contrast to HTML2PS/HTML2PDF

But keep in mind, that the documentation can really be hard to handle. For example, take a look at this page:

Very basic tasks around html to pdf, can be done with this library, but more complex tasks will take some time reading and "understanding" the documentation.

How do I sleep for a millisecond in Perl?

From perlfaq8:

How can I sleep() or alarm() for under a second?

If you want finer granularity than the 1 second that the sleep() function provides, the easiest way is to use the select() function as documented in select in perlfunc. Try the Time::HiRes and the BSD::Itimer modules (available from CPAN, and starting from Perl 5.8 Time::HiRes is part of the standard distribution).

How/When does Execute Shell mark a build as failure in Jenkins?

Simple and short answer to your question is

Please add following line into your "Execute shell" Build step.


Now let me explain you the reason why we require this line for "Execute Shell" build job.

By default Jenkins take /bin/sh -xe and this means -x will print each and every command.And the other option -e, which causes shell to stop running a script immediately when any command exits with non-zero (when any command fails) exit code.

So by adding the #!/bin/sh will allow you to execute with no option.

How do I check for vowels in JavaScript?

This is a rough RegExp function I would have come up with (it's untested)

function isVowel(char) {
    return /^[aeiou]$/.test(char.toLowerCase());

Which means, if (char.length == 1 && 'aeiou' is contained in char.toLowerCase()) then return true.

How to have jQuery restrict file types on upload?

for my case i used the following codes :

    if (!(/\.(gif|jpg|jpeg|tiff|png)$/i).test(fileName)) {              
    alert('You must select an image file only');               

How to open existing project in Eclipse

Right click in navigator-Import-existing project..-select the base directory of your project

How can I determine installed SQL Server instances and their versions?

Here is a simple method: go to Start then Programs then Microsoft SQL Server 2005 then Configuration Tools then SQL Server Configuration Manager then SQL Server 2005 Network Configuration then Here you can locate all the instance installed onto your machine.

jQuery: selecting each td in a tr

Fully example to demonstrate how jQuery query all data in HTML table.

Assume there is a table like the following in your HTML code.

<table id="someTable">
      <td>title 0</td>
      <td>title 1</td>
      <td>title 2</td>
      <td>row 0 td 0</td>
      <td>row 0 td 1</td>
      <td>row 0 td 2</td>
      <td>row 1 td 0</td>
      <td>row 1 td 1</td>
      <td>row 1 td 2</td>
      <td>row 2 td 0</td>
      <td>row 2 td 1</td>
      <td>row 2 td 2</td>
    <tr> ... </tr>
    <tr> ... </tr>
    <tr> ... </tr>
      <td>row n td 0</td>
      <td>row n td 1</td>
      <td>row n td 2</td>

Then, The Answer, the code to print all row all column, should like this

$('#someTable tbody tr').each( (tr_idx,tr) => {
    $(tr).children('td').each( (td_idx, td) => {
        console.log( '[' +tr_idx+ ',' +td_idx+ '] => ' + $(td).text());

After running the code, the result will show

[0,0] => row 0 td 0
[0,1] => row 0 td 1
[0,2] => row 0 td 2
[1,0] => row 1 td 0
[1,1] => row 1 td 1
[1,2] => row 1 td 2
[2,0] => row 2 td 0
[2,1] => row 2 td 1
[2,2] => row 2 td 2
[n,0] => row n td 0
[n,1] => row n td 1
[n,2] => row n td 2

In the code,
tr_idx is the row index start from 0.
td_idx is the column index start from 0.

From this double-loop code,
you can get all loop-index and data in each td cell after comparing the Answer's source code and the output result.

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

Tested in mysql 5.Dont know about other versions. If you want to keep the row with the lowest id value:

DELETE n1 FROM 'yourTableName' n1, 'yourTableName' n2 WHERE > AND n1.member_id = n2.member_id and n1.answer_num =n2.answer_num

If you want to keep the row with the highest id value:

DELETE n1 FROM 'yourTableName' n1, 'yourTableName' n2 WHERE < AND n1.member_id = n2.member_id and n1.answer_num =n2.answer_num

Importing a GitHub project into Eclipse

When the local git projects are cloned in eclipse and are viewable in git perspective but not in package explorer (workspace), the following steps worked for me:

  • Select the repository in git perspective
  • Right click and select import projects

Switch statement fall-through...should it be allowed?

It's a double-edged sword. It is sometimes very useful, but often dangerous.

When is it good? When you want 10 cases all processed the same way...

switch (c) {
  case 1:
  case 2:
            ... Do some of the work ...
            /* FALLTHROUGH */
  case 17:
            ... Do something ...
  case 5:
  case 43:
            ... Do something else ...

The one rule I like is that if you ever do anything fancy where you exclude the break, you need a clear comment /* FALLTHROUGH */ to indicate that was your intention.

Replacing spaces with underscores in JavaScript?

try this:

key=key.replace(/ /g,"_");

that'll do a global find/replace

javascript replace

How to use LDFLAGS in makefile

In more complicated build scenarios, it is common to break compilation into stages, with compilation and assembly happening first (output to object files), and linking object files into a final executable or library afterward--this prevents having to recompile all object files when their source files haven't changed. That's why including the linking flag -lm isn't working when you put it in CFLAGS (CFLAGS is used in the compilation stage).

The convention for libraries to be linked is to place them in either LOADLIBES or LDLIBS (GNU make includes both, but your mileage may vary):


This should allow you to continue using the built-in rules rather than having to write your own linking rule. For other makes, there should be a flag to output built-in rules (for GNU make, this is -p). If your version of make does not have a built-in rule for linking (or if it does not have a placeholder for -l directives), you'll need to write your own:

client.o: client.c
    $(CC) $(CFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -c -o $@ $<

client: client.o

Replace part of a string in Python?

>>> stuff = "Big and small"
>>> stuff.replace(" and ","/")

Execute a SQL Stored Procedure and process the results

My Stored Procedure Requires 2 Parameters and I needed my function to return a datatable here is 100% working code

Please make sure that your procedure return some rows

Public Shared Function Get_BillDetails(AccountNumber As String) As DataTable
        debug.print("Look up account number " & AccountNumber)
        Dim DP As New SqlDataAdapter("EXEC SP_GET_ACCOUNT_PAYABLES_GROUP  '" & AccountNumber & "' , '" & 08/28/2013 &"'", connection.Con)
        Dim DST As New DataSet
        Return DST.Tables(0)      
    Catch ex As Exception
        Return Nothing
    End Try
End Function

What is the difference between .py and .pyc files?

.pyc contain the compiled bytecode of Python source files. The Python interpreter loads .pyc files before .py files, so if they're present, it can save some time by not having to re-compile the Python source code. You can get rid of them if you want, but they don't cause problems, they're not big, and they may save some time when running programs.

Why use getters and setters/accessors?

I wanted to post a real world example I just finished up:

background - I hibernate tools to generate the mappings for my database, a database I am changing as I develop. I change the database schema, push the changes and then run hibernate tools to generate the java code. All is well and good until I want to add methods to those mapped entities. If I modify the generated files, they will be overwritten every time I make a change to the database. So I extend the generated classes like this:

class User extends{
     public Integer getSomething(){
         return super.getSomething();             
     public void setSomething(Integer something){

What I did above is override the existing methods on the super class with my new functionality (something+1) without ever touching the base class. Same scenario if you wrote a class a year ago and want to go to version 2 without changing your base classes (testing nightmare). hope that helps.

How can I find my Apple Developer Team id and Team Agent Apple ID?

You can find your team id here:

This will get you to your Membership Details, just scroll down to Team ID

What's the fastest way to delete a large folder in Windows?

Using Windows Command Prompt:

rmdir /s /q folder

Using Powershell:

powershell -Command "Remove-Item -LiteralPath 'folder' -Force -Recurse"

Note that in more cases del and rmdir wil leave you with leftover files, where Powershell manages to delete the files.

IIS7 Permissions Overview - ApplicationPoolIdentity

Just to add to the confusion, the (Windows Explorer) Effective Permissions dialog doesn't work for these logins. I have a site "Umbo4" using pass-through authentication, and looked at the user's Effective Permissions in the site root folder. The Check Names test resolved the name "IIS AppPool\Umbo4", but the Effective Permissions shows that the user had no permissions at all on the folder (all checkboxes unchecked).

I then excluded this user from the folder explicitly, using the Explorer Security tab. This resulted in the site failing with a HTTP 500.19 error, as expected. The Effective Permissions however looked exactly as before.

Round button with text and icon in flutter

You can simply use named constructors for creating different types of buttons with icons. For instance

FlatButton.icon(onPressed: null, icon: null, label: null);
RaisedButton.icon(onPressed: null, icon: null, label: null);

But if you have specfic requirements then you can always create custom button with different layouts or simply wrap a widget in GestureDetector.

decompiling DEX into Java sourcecode

This can be done in following five steps:

This gem does these things for you automatically even the installation of required tools

  1. convert apk file to zip
  2. unzip the file
  3. extract classes.dex from it
  4. use dex to jar to convert classes.dex into jar file
  5. use jadx gui to open the jar file as java source code

Turn off axes in subplots

You can turn the axes off by following the advice in Veedrac's comment (linking to here) with one small modification.

Rather than using plt.axis('off') you should use ax.axis('off') where ax is a matplotlib.axes object. To do this for your code you simple need to add axarr[0,0].axis('off') and so on for each of your subplots.

The code below shows the result (I've removed the prune_matrix part because I don't have access to that function, in the future please submit fully working code.)

import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import as cm

img = mpimg.imread("stewie.jpg")

f, axarr = plt.subplots(2, 2)
axarr[0,0].imshow(img, cmap = cm.Greys_r)
axarr[0,0].set_title("Rank = 512")

axarr[0,1].imshow(img, cmap = cm.Greys_r)
axarr[0,1].set_title("Rank = %s" % 128)

axarr[1,0].imshow(img, cmap = cm.Greys_r)
axarr[1,0].set_title("Rank = %s" % 32)

axarr[1,1].imshow(img, cmap = cm.Greys_r)
axarr[1,1].set_title("Rank = %s" % 16)

Stewie example

Note: To turn off only the x or y axis you can use set_visible() e.g.:

axarr[0,0].xaxis.set_visible(False) # Hide only x axis