Programs & Examples On #Overlapped io

Technically what is the main difference between Oracle JDK and OpenJDK?

OpenJDK is a reference model and open source, while Oracle JDK is an implementation of the OpenJDK and is not open source. Oracle JDK is more stable than OpenJDK.

OpenJDK is released under GPL v2 license whereas Oracle JDK is licensed under Oracle Binary Code License Agreement.

OpenJDK and Oracle JDK have almost the same code, but Oracle JDK has more classes and some bugs fixed.

So if you want to develop enterprise/commercial software I would suggest to go for Oracle JDK, as it is thoroughly tested and stable.

I have faced lot of problems with application crashes using OpenJDK, which are fixed just by switching to Oracle JDK

Django check for any exists for a query

As of Django 1.2, you can use exists():

https://docs.djangoproject.com/en/dev/ref/models/querysets/#exists

if some_queryset.filter(pk=entity_id).exists():
    print("Entry contained in queryset")

How to change the background color of a UIButton while it's highlighted?

Try tintColor:

_button.tintColor = [UIColor redColor];

Reset identity seed after deleting records in SQL Server

Use this stored procedure:

IF (object_id('[dbo].[pResetIdentityField]') IS NULL)
  BEGIN
    EXEC('CREATE PROCEDURE [dbo].[pResetIdentityField] AS SELECT 1 FROM DUMMY');
  END
GO

SET  ANSI_NULLS ON
GO
SET  QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[pResetIdentityField]
  @pSchemaName NVARCHAR(1000)
, @pTableName NVARCHAR(1000) AS
DECLARE @max   INT;
DECLARE @fullTableName   NVARCHAR(2000) = @pSchemaName + '.' + @pTableName;

DECLARE @identityColumn   NVARCHAR(1000);

SELECT @identityColumn = c.[name]
FROM sys.tables t
     INNER JOIN sys.schemas s ON t.[schema_id] = s.[schema_id]
     INNER JOIN sys.columns c ON c.[object_id] = t.[object_id]
WHERE     c.is_identity = 1
      AND t.name = @pTableName
      AND s.[name] = @pSchemaName

IF @identityColumn IS NULL
  BEGIN
    RAISERROR(
      'One of the following is true: 1. the table you specified doesn''t have an identity field, 2. you specified an invalid schema, 3. you specified an invalid table'
    , 16
    , 1);
    RETURN;
  END;

DECLARE @sqlString   NVARCHAR(MAX) = N'SELECT @maxOut = max(' + @identityColumn + ') FROM ' + @fullTableName;

EXECUTE sp_executesql @stmt = @sqlString, @params = N'@maxOut int OUTPUT', @maxOut = @max OUTPUT

IF @max IS NULL
  SET @max = 0

print(@max)

DBCC CHECKIDENT (@fullTableName, RESEED, @max)
go

--exec pResetIdentityField 'dbo', 'Table'

Just revisiting my answer. I came across a weird behaviour in sql server 2008 r2 that you should be aware of.

drop table test01

create table test01 (Id int identity(1,1), descr nvarchar(10))

execute pResetIdentityField 'dbo', 'test01'

insert into test01 (descr) values('Item 1')

select * from test01

delete from test01

execute pResetIdentityField 'dbo', 'test01'

insert into test01 (descr) values('Item 1')

select * from test01

The first select produces 0, Item 1.

The second one produces 1, Item 1. If you execute the reset right after the table is created the next value is 0. Honestly, I am not surprised Microsoft cannot get this stuff right. I discovered it because I have a script file that populates reference tables that I sometimes run after I re-create tables and sometimes when the tables are already created.

Postman: How to make multiple requests at the same time

I guess there's no such feature in postman as to run concurrent tests.

If i were you i would consider Apache jMeter which is used exactly for such scenarios.

Regarding Postman, the only thing that could more or less meet your needs is - Postman Runner. enter image description here There you can specify the details:

  • number of iterations,
  • upload csv file with data for different test runs, etc.

The runs won't be concurrent, only consecutive.

Hope that helps. But do consider jMeter (you'll love it).

How can I force users to access my page over HTTPS instead of HTTP?

use htaccess:

#if domain has www. and not https://
  RewriteCond %{HTTPS} =off [NC]
  RewriteCond %{HTTP_HOST} ^(?i:www+\.+[^.]+\.+[^.]+)$
  RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [QSA,L,R=307]

#if domain has not www.
  RewriteCond %{HTTP_HOST} ^([^.]+\.+[^.]+)$
  RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [QSA,L,R=307]

Base64 encoding in SQL Server 2005 T-SQL

You can use just:

Declare @pass2 binary(32)
Set @pass2 =0x4D006A00450034004E0071006B00350000000000000000000000000000000000
SELECT CONVERT(NVARCHAR(16), @pass2)

then after encoding you'll receive text 'MjE4Nqk5'

How to return only 1 row if multiple duplicate rows and still return rows that are not duplicates?

select * from temptable
where rnum --unique key
 in 

( 
 SELECT RNUM --unique key
  FROM temptable
 WHERE (  HistoryStatus
) IN (SELECT                HistoryStatus

                             FROM temptable
                            GROUP BY                
HistoryStatus 
                           HAVING COUNT(*) <= 1));

I have not tested this code. I have used similar code and it works. The syntax is in Oracle.

Using PHP to upload file and add the path to MySQL database

First you should use print_r($_FILES) to debug, and see what it contains. :

your uploads.php would look like:

//This is the directory where images will be saved
$target = "pics/";
$target = $target . basename( $_FILES['Filename']['name']);

//This gets all the other information from the form
$Filename=basename( $_FILES['Filename']['name']);
$Description=$_POST['Description'];


//Writes the Filename to the server
if(move_uploaded_file($_FILES['Filename']['tmp_name'], $target)) {
    //Tells you if its all ok
    echo "The file ". basename( $_FILES['Filename']['name']). " has been uploaded, and your information has been added to the directory";
    // Connects to your Database
    mysql_connect("localhost", "root", "") or die(mysql_error()) ;
    mysql_select_db("altabotanikk") or die(mysql_error()) ;

    //Writes the information to the database
    mysql_query("INSERT INTO picture (Filename,Description)
    VALUES ('$Filename', '$Description')") ;
} else {
    //Gives and error if its not
    echo "Sorry, there was a problem uploading your file.";
}



?>

EDIT: Since this is old post, currently it is strongly recommended to use either mysqli or pdo instead mysql_ functions in php

How can you change Network settings (IP Address, DNS, WINS, Host Name) with code in C#

Just made this in a few minutes:

using System;
using System.Management;

namespace WindowsFormsApplication_CS
{
  class NetworkManagement
  {
    public void setIP(string ip_address, string subnet_mask)
    {
      ManagementClass objMC =
        new ManagementClass("Win32_NetworkAdapterConfiguration");
      ManagementObjectCollection objMOC = objMC.GetInstances();

      foreach (ManagementObject objMO in objMOC)
      {
        if ((bool)objMO["IPEnabled"])
        {
          ManagementBaseObject setIP;
          ManagementBaseObject newIP =
            objMO.GetMethodParameters("EnableStatic");

          newIP["IPAddress"] = new string[] { ip_address };
          newIP["SubnetMask"] = new string[] { subnet_mask };

          setIP = objMO.InvokeMethod("EnableStatic", newIP, null);
        }
      }
    }

    public void setGateway(string gateway)
    {
      ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
      ManagementObjectCollection objMOC = objMC.GetInstances();

      foreach (ManagementObject objMO in objMOC)
      {
        if ((bool)objMO["IPEnabled"])
        {
          ManagementBaseObject setGateway;
          ManagementBaseObject newGateway =
            objMO.GetMethodParameters("SetGateways");

          newGateway["DefaultIPGateway"] = new string[] { gateway };
          newGateway["GatewayCostMetric"] = new int[] { 1 };

          setGateway = objMO.InvokeMethod("SetGateways", newGateway, null);
        }
      }
    }

    public void setDNS(string NIC, string DNS)
    {
      ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
      ManagementObjectCollection objMOC = objMC.GetInstances();

      foreach (ManagementObject objMO in objMOC)
      {
        if ((bool)objMO["IPEnabled"])
        {
          // if you are using the System.Net.NetworkInformation.NetworkInterface
          // you'll need to change this line to
          // if (objMO["Caption"].ToString().Contains(NIC))
          // and pass in the Description property instead of the name 
          if (objMO["Caption"].Equals(NIC))
          {
            ManagementBaseObject newDNS =
              objMO.GetMethodParameters("SetDNSServerSearchOrder");
            newDNS["DNSServerSearchOrder"] = DNS.Split(',');
            ManagementBaseObject setDNS =
              objMO.InvokeMethod("SetDNSServerSearchOrder", newDNS, null);
          }
        }
      }
    }

    public void setWINS(string NIC, string priWINS, string secWINS)
    {
      ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
      ManagementObjectCollection objMOC = objMC.GetInstances();

      foreach (ManagementObject objMO in objMOC)
      {
        if ((bool)objMO["IPEnabled"])
        {
          if (objMO["Caption"].Equals(NIC))
          {
            ManagementBaseObject setWINS;
            ManagementBaseObject wins =
            objMO.GetMethodParameters("SetWINSServer");
            wins.SetPropertyValue("WINSPrimaryServer", priWINS);
            wins.SetPropertyValue("WINSSecondaryServer", secWINS);

            setWINS = objMO.InvokeMethod("SetWINSServer", wins, null);
          }
        }
      }
    } 
  }
}

What is "string[] args" in Main class for?

It's an array of the parameters/arguments (hence args) that you send to the program. For example ping 172.16.0.1 -t -4

These arguments are passed to the program as an array of strings.

string[] args // Array of Strings containing arguments.

How to downgrade Java from 9 to 8 on a MACOS. Eclipse is not running with Java 9

This is how I did it. You don't need to delete Java 9 or newer version.

Step 1: Install Java 8

You can download Java 8 from here: http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html

Step 2: After installation of Java 8. Confirm installation of all versions.Type the following command in your terminal.

/usr/libexec/java_home -V

Step 3: Edit .bash_profile

sudo nano ~/.bash_profile

Step 4: Add 1.8 as default. (Add below line to bash_profile file).

export JAVA_HOME=$(/usr/libexec/java_home -v 1.8)

Now Press CTRL+X to exit the bash. Press 'Y' to save changes.

Step 5: Reload bash_profile

source ~/.bash_profile

Step 6: Confirm current version of Java

java -version

How do I create a right click context menu in Java Swing?

This question is a bit old - as are the answers (and the tutorial as well)

The current api for setting a popupMenu in Swing is

myComponent.setComponentPopupMenu(myPopupMenu);

This way it will be shown automagically, both for mouse and keyboard triggers (the latter depends on LAF). Plus, it supports re-using the same popup across a container's children. To enable that feature:

myChild.setInheritsPopupMenu(true);

How to set image width to be 100% and height to be auto in react native?

For image tag you can use this type of style, it worked for me:

imageStyle: {
    width: Dimensions.get('window').width - 23,
    resizeMode: "contain",
    height: 211,
 },

How to get start and end of previous month in VB

Try this to get the month in number form:

Month(DateAdd("m", -3, Now))

It will give you 12 for December.

So in your case you would use Month(DateAdd("m", -1, Now)) to just subract one month.

How to activate a specific worksheet in Excel?

Would the following Macro help you?

Sub activateSheet(sheetname As String)
'activates sheet of specific name
    Worksheets(sheetname).Activate
End Sub

Basically you want to make use of the .Activate function. Or you can use the .Select function like so:

Sub activateSheet(sheetname As String)
'selects sheet of specific name
    Sheets(sheetname).Select
End Sub

How to get an element by its href in jquery?

Yes, you can use jQuery's attribute selector for that.

var linksToGoogle = $('a[href="http://google.com"]');

Alternatively, if your interest is rather links starting with a certain URL, use the attribute-starts-with selector:

var allLinksToGoogle = $('a[href^="http://google.com"]');

OS detecting makefile

Detect the operating system using two simple tricks:

  • First the environment variable OS
  • Then the uname command
ifeq ($(OS),Windows_NT)     # is Windows_NT on XP, 2000, 7, Vista, 10...
    detected_OS := Windows
else
    detected_OS := $(shell uname)  # same as "uname -s"
endif

Or a more safe way, if not on Windows and uname unavailable:

ifeq ($(OS),Windows_NT) 
    detected_OS := Windows
else
    detected_OS := $(shell sh -c 'uname 2>/dev/null || echo Unknown')
endif

Ken Jackson proposes an interesting alternative if you want to distinguish Cygwin/MinGW/MSYS/Windows. See his answer that looks like that:

ifeq '$(findstring ;,$(PATH))' ';'
    detected_OS := Windows
else
    detected_OS := $(shell uname 2>/dev/null || echo Unknown)
    detected_OS := $(patsubst CYGWIN%,Cygwin,$(detected_OS))
    detected_OS := $(patsubst MSYS%,MSYS,$(detected_OS))
    detected_OS := $(patsubst MINGW%,MSYS,$(detected_OS))
endif

Then you can select the relevant stuff depending on detected_OS:

ifeq ($(detected_OS),Windows)
    CFLAGS += -D WIN32
endif
ifeq ($(detected_OS),Darwin)        # Mac OS X
    CFLAGS += -D OSX
endif
ifeq ($(detected_OS),Linux)
    CFLAGS   +=   -D LINUX
endif
ifeq ($(detected_OS),GNU)           # Debian GNU Hurd
    CFLAGS   +=   -D GNU_HURD
endif
ifeq ($(detected_OS),GNU/kFreeBSD)  # Debian kFreeBSD
    CFLAGS   +=   -D GNU_kFreeBSD
endif
ifeq ($(detected_OS),FreeBSD)
    CFLAGS   +=   -D FreeBSD
endif
ifeq ($(detected_OS),NetBSD)
    CFLAGS   +=   -D NetBSD
endif
ifeq ($(detected_OS),DragonFly)
    CFLAGS   +=   -D DragonFly
endif
ifeq ($(detected_OS),Haiku)
    CFLAGS   +=   -D Haiku
endif

Notes:

  • Command uname is same as uname -s because option -s (--kernel-name) is the default. See why uname -s is better than uname -o.

  • The use of OS (instead of uname) simplifies the identification algorithm. You can still use solely uname, but you have to deal with if/else blocks to check all MinGW, Cygwin, etc. variations.

  • The environment variable OS is always set to "Windows_NT" on different Windows versions (see %OS% environment variable on Wikipedia).

  • An alternative of OS is the environment variable MSVC (it checks the presence of MS Visual Studio, see example using Visual C++).


Below I provide a complete example using make and gcc to build a shared library: *.so or *.dll depending on the platform. The example is as simplest as possible to be more understandable.

To install make and gcc on Windows see Cygwin or MinGW.

My example is based on five files

 +-- lib
 ¦   +-- Makefile
 ¦   +-- hello.h
 ¦   +-- hello.c
 +-- app
     +-- Makefile
     +-- main.c

Reminder: Makefile is indented using tabulation. Caution when copy-pasting below sample files.

The two Makefile files

1. lib/Makefile

ifeq ($(OS),Windows_NT)
    uname_S := Windows
else
    uname_S := $(shell uname -s)
endif

ifeq ($(uname_S), Windows)
    target = hello.dll
endif
ifeq ($(uname_S), Linux)
    target = libhello.so
endif
#ifeq ($(uname_S), .....) #See https://stackoverflow.com/a/27776822/938111
#    target = .....
#endif

%.o: %.c
    gcc  -c $<  -fPIC  -o $@
    # -c $<  => $< is first file after ':' => Compile hello.c
    # -fPIC  => Position-Independent Code (required for shared lib)
    # -o $@  => $@ is the target => Output file (-o) is hello.o

$(target): hello.o
    gcc  $^  -shared  -o $@
    # $^      => $^ expand to all prerequisites (after ':') => hello.o
    # -shared => Generate shared library
    # -o $@   => Output file (-o) is $@ (libhello.so or hello.dll)

2. app/Makefile

ifeq ($(OS),Windows_NT)
    uname_S := Windows
else
    uname_S := $(shell uname -s)
endif

ifeq ($(uname_S), Windows)
    target = app.exe
endif
ifeq ($(uname_S), Linux)
    target = app
endif
#ifeq ($(uname_S), .....) #See https://stackoverflow.com/a/27776822/938111
#    target = .....
#endif

%.o: %.c
    gcc  -c $< -I ../lib  -o $@
    # -c $<     => compile (-c) $< (first file after :) = main.c
    # -I ../lib => search headers (*.h) in directory ../lib
    # -o $@     => output file (-o) is $@ (target) = main.o

$(target): main.o
    gcc  $^  -L../lib  -lhello  -o $@
    # $^       => $^ (all files after the :) = main.o (here only one file)
    # -L../lib => look for libraries in directory ../lib
    # -lhello  => use shared library hello (libhello.so or hello.dll)
    # -o $@    => output file (-o) is $@ (target) = "app.exe" or "app"

To learn more, read Automatic Variables documentation as pointed out by cfi.

The source code

- lib/hello.h

#ifndef HELLO_H_
#define HELLO_H_

const char* hello();

#endif

- lib/hello.c

#include "hello.h"

const char* hello()
{
    return "hello";
}

- app/main.c

#include "hello.h" //hello()
#include <stdio.h> //puts()

int main()
{
    const char* str = hello();
    puts(str);
}

The build

Fix the copy-paste of Makefile (replace leading spaces by one tabulation).

> sed  's/^  */\t/'  -i  */Makefile

The make command is the same on both platforms. The given output is on Unix-like OSes:

> make -C lib
make: Entering directory '/tmp/lib'
gcc  -c hello.c  -fPIC  -o hello.o
# -c hello.c  => hello.c is first file after ':' => Compile hello.c
# -fPIC       => Position-Independent Code (required for shared lib)
# -o hello.o  => hello.o is the target => Output file (-o) is hello.o
gcc  hello.o  -shared  -o libhello.so
# hello.o        => hello.o is the first after ':' => Link hello.o
# -shared        => Generate shared library
# -o libhello.so => Output file (-o) is libhello.so (libhello.so or hello.dll)
make: Leaving directory '/tmp/lib'

> make -C app
make: Entering directory '/tmp/app'
gcc  -c main.c -I ../lib  -o main.o
# -c main.c => compile (-c) main.c (first file after :) = main.cpp
# -I ../lib => search headers (*.h) in directory ../lib
# -o main.o => output file (-o) is main.o (target) = main.o
gcc  main.o  -L../lib  -lhello  -o app
# main.o   => main.o (all files after the :) = main.o (here only one file)
# -L../lib => look for libraries in directory ../lib
# -lhello  => use shared library hello (libhello.so or hello.dll)
# -o app   => output file (-o) is app.exe (target) = "app.exe" or "app"
make: Leaving directory '/tmp/app'

The run

The application requires to know where is the shared library.

On Windows, a simple solution is to copy the library where the application is:

> cp -v lib/hello.dll app
`lib/hello.dll' -> `app/hello.dll'

On Unix-like OSes, you can use the LD_LIBRARY_PATH environment variable:

> export LD_LIBRARY_PATH=lib

Run the command on Windows:

> app/app.exe
hello

Run the command on Unix-like OSes:

> app/app
hello

Pass accepts header parameter to jquery ajax

Although some of them are correct, I've found quite confusing the previous responses. At the same time, the OP asked for a solution without setting a custom header or using beforeSend, so I've being looking for a clearer explanation. I hope my conclusions provide some light to others.

The code

jQuery.ajax({
    .... 
    accepts: "application/json; charset=utf-8",
    ....
});

doesn't work because accepts must be a PlainObject (not a String) according to the jQuery doc (http://api.jquery.com/jquery.ajax/). Specifically, jQuery expect zero or more key-value pairs relating each dataType with the accepted MIME type for them. So what I've finally using is:

jQuery.ajax({
    ....
    dataType: 'json',
    accepts: {
        json: 'application/json'
    },
    ....
});

Can I use an HTML input type "date" to collect only a year?

There is input type month in HTML5 which allows to select month and year. Month selector works with autocomplete.

Check the example in JSFiddle.

<!DOCTYPE html>
<html>
<body>
    <header>
        <h1>Select a month below</h1>
    </header>
    Month example
    <input type="month" />
</body>
</html>

How do I add button on each row in datatable?

var table =$('#example').DataTable( {
    data: yourdata ,
    columns: [
        { data: "id" },
        { data: "name" },
        { data: "parent" },
        { data: "date" },

        {data: "id" , render : function ( data, type, row, meta ) {
              return type === 'display'  ?
                '<a href="<?php echo $delete_url;?>'+ data +'" ><i class="fe fe-delete"></i></a>' :
                data;
            }},
    ],
    }
}

Maximum number of threads in a .NET app?

Mitch is right. It depends on resources (memory).

Although Raymond's article is dedicated to Windows threads, not to C# threads, the logic applies the same (C# threads are mapped to Windows threads).

However, as we are in C#, if we want to be completely precise, we need to distinguish between "started" and "non started" threads. Only started threads actually reserve stack space (as we could expect). Non started threads only allocate the information required by a thread object (you can use reflector if interested in the actual members).

You can actually test it for yourself, compare:

    static void DummyCall()
    {
        Thread.Sleep(1000000000);
    }

    static void Main(string[] args)
    {
        int count = 0;
        var threadList = new List<Thread>();
        try
        {
            while (true)
            {
                Thread newThread = new Thread(new ThreadStart(DummyCall), 1024);
                newThread.Start();
                threadList.Add(newThread);
                count++;
            }
        }
        catch (Exception ex)
        {
        }
    }

with:

   static void DummyCall()
    {
        Thread.Sleep(1000000000);
    }

    static void Main(string[] args)
    {
        int count = 0;
        var threadList = new List<Thread>();
        try
        {
            while (true)
            {
                Thread newThread = new Thread(new ThreadStart(DummyCall), 1024);
                threadList.Add(newThread);
                count++;
            }
        }
        catch (Exception ex)
        {
        }
    }

Put a breakpoint in the exception (out of memory, of course) in VS to see the value of counter. There is a very significant difference, of course.

How to create an empty array in Swift?

Initiating an array with a predefined count:

Array(repeating: 0, count: 10)

I often use this for mapping statements where I need a specified number of mock objects. For example,

let myObjects: [MyObject] = Array(repeating: 0, count: 10).map { _ in return MyObject() }

self referential struct definition?

Clearly a Cell cannot contain another cell as it becomes a never-ending recursion.

However a Cell CAN contain a pointer to another cell.

typedef struct Cell {
  bool isParent;
  struct Cell* child;
} Cell;

C#, Looping through dataset and show each record from a dataset column

DateTime TaskStart = DateTime.Parse(dr["TaskStart"].ToString());

Real mouse position in canvas

The Simple 1:1 Scenario

For situations where the canvas element is 1:1 compared to the bitmap size, you can get the mouse positions by using this snippet:

function getMousePos(canvas, evt) {
    var rect = canvas.getBoundingClientRect();
    return {
      x: evt.clientX - rect.left,
      y: evt.clientY - rect.top
    };
}

Just call it from your event with the event and canvas as arguments. It returns an object with x and y for the mouse positions.

As the mouse position you are getting is relative to the client window you'll have to subtract the position of the canvas element to convert it relative to the element itself.

Example of integration in your code:

//put this outside the event loop..
var canvas = document.getElementById("imgCanvas");
var context = canvas.getContext("2d");

function draw(evt) {
    var pos = getMousePos(canvas, evt);

    context.fillStyle = "#000000";
    context.fillRect (pos.x, pos.y, 4, 4);
}

Note: borders and padding will affect position if applied directly to the canvas element so these needs to be considered via getComputedStyle() - or apply those styles to a parent div instead.

When Element and Bitmap are of different sizes

When there is the situation of having the element at a different size than the bitmap itself, for example, the element is scaled using CSS or there is pixel-aspect ratio etc. you will have to address this.

Example:

function  getMousePos(canvas, evt) {
  var rect = canvas.getBoundingClientRect(), // abs. size of element
      scaleX = canvas.width / rect.width,    // relationship bitmap vs. element for X
      scaleY = canvas.height / rect.height;  // relationship bitmap vs. element for Y

  return {
    x: (evt.clientX - rect.left) * scaleX,   // scale mouse coordinates after they have
    y: (evt.clientY - rect.top) * scaleY     // been adjusted to be relative to element
  }
}

With transformations applied to context (scale, rotation etc.)

Then there is the more complicated case where you have applied transformation to the context such as rotation, skew/shear, scale, translate etc. To deal with this you can calculate the inverse matrix of the current matrix.

Newer browsers let you read the current matrix via the currentTransform property and Firefox (current alpha) even provide a inverted matrix through the mozCurrentTransformInverted. Firefox however, via mozCurrentTransform, will return an Array and not DOMMatrix as it should. Neither Chrome, when enabled via experimental flags, will return a DOMMatrix but a SVGMatrix.

In most cases however you will have to implement a custom matrix solution of your own (such as my own solution here - free/MIT project) until this get full support.

When you eventually have obtained the matrix regardless of path you take to obtain one, you'll need to invert it and apply it to your mouse coordinates. The coordinates are then passed to the canvas which will use its matrix to convert it to back wherever it is at the moment.

This way the point will be in the correct position relative to the mouse. Also here you need to adjust the coordinates (before applying the inverse matrix to them) to be relative to the element.

An example just showing the matrix steps

function draw(evt) {
    var pos = getMousePos(canvas, evt);        // get adjusted coordinates as above
    var imatrix = matrix.inverse();            // get inverted matrix somehow
    pos = imatrix.applyToPoint(pos.x, pos.y);  // apply to adjusted coordinate

    context.fillStyle = "#000000";
    context.fillRect(pos.x-1, pos.y-1, 2, 2);
}

An example of using currentTransform when implemented would be:

    var pos = getMousePos(canvas, e);          // get adjusted coordinates as above
    var matrix = ctx.currentTransform;         // W3C (future)
    var imatrix = matrix.invertSelf();         // invert

    // apply to point:
    var x = pos.x * imatrix.a + pos.y * imatrix.c + imatrix.e;
    var y = pos.x * imatrix.b + pos.y * imatrix.d + imatrix.f;

Update I made a free solution (MIT) to embed all these steps into a single easy-to-use object that can be found here and also takes care of a few other nitty-gritty things most ignore.

Creating a dictionary from a CSV file

This isn't elegant but a one line solution using pandas.

import pandas as pd
pd.read_csv('coors.csv', header=None, index_col=0, squeeze=True).to_dict()

If you want to specify dtype for your index (it can't be specified in read_csv if you use the index_col argument because of a bug):

import pandas as pd
pd.read_csv('coors.csv', header=None, dtype={0: str}).set_index(0).squeeze().to_dict()

What is the difference between POST and GET?

GET and POST are two different types of HTTP requests.

According to Wikipedia:

GET requests a representation of the specified resource. Note that GET should not be used for operations that cause side-effects, such as using it for taking actions in web applications. One reason for this is that GET may be used arbitrarily by robots or crawlers, which should not need to consider the side effects that a request should cause.

and

POST submits data to be processed (e.g., from an HTML form) to the identified resource. The data is included in the body of the request. This may result in the creation of a new resource or the updates of existing resources or both.

So essentially GET is used to retrieve remote data, and POST is used to insert/update remote data.


HTTP/1.1 specification (RFC 2616) section 9 Method Definitions contains more information on GET and POST as well as the other HTTP methods, if you are interested.

In addition to explaining the intended uses of each method, the spec also provides at least one practical reason for why GET should only be used to retrieve data:

Authors of services which use the HTTP protocol SHOULD NOT use GET based forms for the submission of sensitive data, because this will cause this data to be encoded in the Request-URI. Many existing servers, proxies, and user agents will log the request URI in some place where it might be visible to third parties. Servers can use POST-based form submission instead


Finally, an important consideration when using GET for AJAX requests is that some browsers - IE in particular - will cache the results of a GET request. So if you, for example, poll using the same GET request you will always get back the same results, even if the data you are querying is being updated server-side. One way to alleviate this problem is to make the URL unique for each request by appending a timestamp.

How to extract one column of a csv file

You can also use while loop

IFS=,
while read name val; do
        echo "............................"

        echo Name: "$name"
done<itemlst.csv

String replacement in java, similar to a velocity template

Use StringSubstitutor from Apache Commons Text.

https://commons.apache.org/proper/commons-text/

It will do it for you (and its open source...)

 Map<String, String> valuesMap = new HashMap<String, String>();
 valuesMap.put("animal", "quick brown fox");
 valuesMap.put("target", "lazy dog");
 String templateString = "The ${animal} jumped over the ${target}.";
 StringSubstitutor sub = new StringSubstitutor(valuesMap);
 String resolvedString = sub.replace(templateString);

How to set default values in Go structs

type Config struct {
    AWSRegion                               string `default:"us-west-2"`
}

How can I get the root domain URI in ASP.NET?

If example Url is http://www.foobar.com/Page1

HttpContext.Current.Request.Url; //returns "http://www.foobar.com/Page1"


HttpContext.Current.Request.Url.Host; //returns "www.foobar.com"


HttpContext.Current.Request.Url.Scheme; //returns "http/https"


HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority); //returns "http://www.foobar.com"

How to bind multiple values to a single WPF TextBlock?

You can use a MultiBinding combined with the StringFormat property. Usage would resemble the following:

<TextBlock>
    <TextBlock.Text>    
        <MultiBinding StringFormat="{}{0} + {1}">
            <Binding Path="Name" />
            <Binding Path="ID" />
        </MultiBinding>
    </TextBlock.Text>
</TextBlock>

Giving Name a value of Foo and ID a value of 1, your output in the TextBlock would then be Foo + 1.

Note: that this is only supported in .NET 3.5 SP1 and 3.0 SP2 or later.

What port is a given program using?

"netstat -natp" is what I always use.

Multiplying across in a numpy array

You could also use matrix multiplication (aka dot product):

a = [[1,2,3],[4,5,6],[7,8,9]]
b = [0,1,2]
c = numpy.diag(b)

numpy.dot(c,a)

Which is more elegant is probably a matter of taste.

How to detect page zoom level in all modern browsers?

This is for Chrome, in the wake of user800583 answer ...

I spent a few hours on this problem and have not found a better approach, but :

  • There are 16 'zoomLevel' and not 10
  • When Chrome is fullscreen/maximized the ratio is window.outerWidth/window.innerWidth, and when it is not, the ratio seems to be (window.outerWidth-16)/window.innerWidth, however the 1st case can be approached by the 2nd one.

So I came to the following ...

But this approach has limitations : for example if you play the accordion with the application window (rapidly enlarge and reduce the width of the window) then you will get gaps between zoom levels although the zoom has not changed (may be outerWidth and innerWidth are not exactly updated in the same time).

var snap = function (r, snaps)
{
    var i;
    for (i=0; i < 16; i++) { if ( r < snaps[i] ) return i; }
};
var w, l, r;
w = window.outerWidth, l = window.innerWidth;
return snap((w - 16) / l,
            [ 0.29, 0.42, 0.58, 0.71, 0.83, 0.95, 1.05, 1.18, 1.38, 1.63, 1.88, 2.25, 2.75, 3.5, 4.5, 100 ],
);

And if you want the factor :

var snap = function (r, snaps, ratios)
{
    var i;
    for (i=0; i < 16; i++) { if ( r < snaps[i] ) return eval(ratios[i]); }
};
var w, l, r;
w = window.outerWidth, l = window.innerWidth;
return snap((w - 16) / l,
            [ 0.29, 0.42, 0.58, 0.71, 0.83, 0.95, 1.05, 1.18, 1.38, 1.63, 1.88, 2.25, 2.75, 3.5, 4.5, 100 ],
            [ 0.25, '1/3', 0.5, '2/3', 0.75, 0.9, 1, 1.1, 1.25, 1.5, 1.75, 2, 2.5, 3, 4, 5 ]
);

Onclick CSS button effect

Push down the whole button. I suggest this it is looking nice in button.

#button:active {
    position: relative;
    top: 1px;
}

if you only want to push text increase top-padding and decrease bottom padding. You can also use line-height.

@Autowired and static method

You have to workaround this via static application context accessor approach:

@Component
public class StaticContextAccessor {

    private static StaticContextAccessor instance;

    @Autowired
    private ApplicationContext applicationContext;

    @PostConstruct
    public void registerInstance() {
        instance = this;
    }

    public static <T> T getBean(Class<T> clazz) {
        return instance.applicationContext.getBean(clazz);
    }

}

Then you can access bean instances in a static manner.

public class Boo {

    public static void randomMethod() {
         StaticContextAccessor.getBean(Foo.class).doStuff();
    }

}

How to convert "0" and "1" to false and true

If you want the conversion to always succeed, probably the best way to convert the string would be to consider "1" as true and anything else as false (as Kevin does). If you wanted the conversion to fail if anything other than "1" or "0" is returned, then the following would suffice (you could put it in a helper method):

if (returnValue == "1")
{
    return true;
}
else if (returnValue == "0")
{
    return false;
}
else
{
    throw new FormatException("The string is not a recognized as a valid boolean value.");
}

How to check for changes on remote (origin) Git repository

I simply use

git fetch origin

to fetch the remote changes, and then I view both local and pending remote commits (and their associated changes) with the nice gitk tool involving the --all argument like:

gitk --all

How to change JFrame icon

JFrame.setIconImage(Image image) pretty standard.

Replace part of a string with another string

wstring myString = L"Hello $$ this is an example. By $$.";
wstring search = L"$$";
wstring replace = L"Tom";
for (int i = myString.find(search); i >= 0; i = myString.find(search))
    myString.replace(i, search.size(), replace);

Replace missing values with column mean

If DF is your data frame of numeric columns:

library(zoo)
na.aggregate(DF)

ADDED:

Using only the base of R define a function which does it for one column and then lapply to every column:

NA2mean <- function(x) replace(x, is.na(x), mean(x, na.rm = TRUE))
replace(DF, TRUE, lapply(DF, NA2mean))

The last line could be replaced with the following if it's OK to overwrite the input:

DF[] <- lapply(DF, NA2mean)

How to change working directory in Jupyter Notebook?

  1. list all magic command %lsmagic
  2. show current directory %pwd

Tried to Load Angular More Than Once

Had this problem today and figured I would post how I fixed it. In my case I had an index.html page with:

<body ng-app="myApp" ng-controller="mainController"
   <div ng-view></div>
</body>

and in my app.js file I had the following code:

$routeProvider.when('/', {
    controller : 'mainController',
    templateUrl : 'index.html',
    title : 'Home'
  }).when('/other', {
    controller : 'otherController',
    templateUrl : 'views/other.html',
    title : 'other'
  }).otherwise({
    redirectTo : '/'
  });

As a result, when I went to the page (base_url/) it loaded index.html, and inside the ng-view it loaded index.html again, and inside that view it loaded index.html again.. and so on - creating an infinite recursive load of index.html (each time loading angular libraries).

To resolve all I had to do was remove index.html from the routProvider - as follows:

$routeProvider.when('/other', {
    controller : 'otherController',
    templateUrl : 'views/other.html',
    title : 'other'
  }).otherwise({
    redirectTo : '/'
  });

Can I pass variable to select statement as column name in SQL Server

You can't use variable names to bind columns or other system objects, you need dynamic sql

DECLARE @value varchar(10)  
SET @value = 'intStep'  
DECLARE @sqlText nvarchar(1000); 

SET @sqlText = N'SELECT ' + @value + ' FROM dbo.tblBatchDetail'
Exec (@sqlText)

Error in plot.new() : figure margins too large, Scatter plot

Every time you are creating plots you might get this error - "Error in plot.new() : figure margins too large". To avoid such errors you can first check par("mar") output. You should be getting:

[1] 5.1 4.1 4.1 2.1

To change that write:

par(mar=c(1,1,1,1))

This should rectify the error. Or else you can change the values accordingly.

Hope this works for you.

Changing API level Android Studio

In Android studio open build.gradle and edit the following section:

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

here you can change minSdkVersion from 12 to 14

NodeJS: How to decode base64 encoded string back to binary?

As of Node.js v6.0.0 using the constructor method has been deprecated and the following method should instead be used to construct a new buffer from a base64 encoded string:

var b64string = /* whatever */;
var buf = Buffer.from(b64string, 'base64'); // Ta-da

For Node.js v5.11.1 and below

Construct a new Buffer and pass 'base64' as the second argument:

var b64string = /* whatever */;
var buf = new Buffer(b64string, 'base64'); // Ta-da

If you want to be clean, you can check whether from exists :

if (typeof Buffer.from === "function") {
    // Node 5.10+
    buf = Buffer.from(b64string, 'base64'); // Ta-da
} else {
    // older Node versions, now deprecated
    buf = new Buffer(b64string, 'base64'); // Ta-da
}

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

Put fragment name before the activity

Intent mIntent = new Intent(SigninFragment.this.getActivity(),MusicHome.class);

Failed to connect to camera service

Make sure to call the release() method to release the camera when it is no longer needed, or you will not be able to use the camera. Perhaps as a sanity check, see if your regular camera works. If it says it fails, then your previous attempts at runni

How to display a confirmation dialog when clicking an <a> link?

<a href="delete.php?id=22" onclick = "if (! confirm('Continue?')) { return false; }">Confirm OK, then goto URL (uses onclick())</a>

How to do a GitHub pull request

I followed tim peterson's instructions but I created a local branch for my changes. However, after pushing I was not seeing the new branch in GitHub. The solution was to add -u to the push command:

git push -u origin <branch>

How to printf "unsigned long" in C?

The format is %lu.

Please check about the various other datatypes and their usage in printf here

Setting background images in JFrame

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

class BackgroundImageJFrame extends JFrame
{

    JButton b1;
    JLabel l1;

    public BackgroundImageJFrame() {

        setSize(400,400);
        setVisible(true);

        setLayout(new BorderLayout());

        JLabel background=new JLabel(new ImageIcon("C:\\Users\\Computer\\Downloads\\colorful_design.png"));

        add(background);

        background.setLayout(new FlowLayout());

        l1=new JLabel("Here is a button");
        b1=new JButton("I am a button");

        background.add(l1);
        background.add(b1);
    }

    public static void main(String args[]) 
    {
        new BackgroundImageJFrame();
    }
}

check out the below link

http://java-demos.blogspot.in/2012/09/setting-background-image-in-jframe.html

What can I use for good quality code coverage for C#/.NET?

I just tested out NCrunch and have to say I am very impressed. It is a continuous testing tool that will add code coverage to your code in Visual Studio at almost real time. At the time as I write this NCrunch is free. It is a little unclear if it going to be free, cost money or be opened source in the future though.

JavaScript string newline character?

I had the problem of expressing newline with \n or \r\n.
Magically the character \r which is used for carriage return worked for me like a newline.
So in some cases, it is useful to consider \r too.

Including all the jars in a directory within the Java classpath

The only way I know how is to do it individually, for example:

setenv CLASSPATH /User/username/newfolder/jarfile.jar:jarfile2.jar:jarfile3.jar:.

Hope that helps!

Cannot uninstall angular-cli

The following approach worked for me:

npm uninstall -g @angular/cli

and

npm cache verify

How to call webmethod in Asp.net C#

I'm not sure why that isn't working, It works fine on my test. But here is an alternative technique that might help.

Instead of calling the method in the AJAX url, just use the page .aspx url, and add the method as a parameter in the data object. Then when it calls page_load, your data will be in the Request.Form variable.

jQuery

jQuery.ajax({
    url: 'AddToCart.aspx',
    type: "POST",
    data: {
        method: 'AddTo_Cart', quantity: total_qty, itemId: itemId
    },
    dataType: "json",
    beforeSend: function () {
        alert("Start!!! ");
    },
    success: function (data) {
        alert("a");
    },
    failure: function (msg) { alert("Sorry!!! "); }
});

C# Page Load:

if (!Page.IsPostBack)
{
    if (Request.Form["method"] == "AddTo_Cart")
    {
        int q, id;
        int.TryParse(Request.Form["quantity"], out q);
        int.TryParse(Request.Form["itemId"], out id);
        AddTo_Cart(q,id);
    }
}

Difference between document.addEventListener and window.addEventListener?

You'll find that in javascript, there are usually many different ways to do the same thing or find the same information. In your example, you are looking for some element that is guaranteed to always exist. window and document both fit the bill (with just a few differences).

From mozilla dev network:

addEventListener() registers a single event listener on a single target. The event target may be a single element in a document, the document itself, a window, or an XMLHttpRequest.

So as long as you can count on your "target" always being there, the only difference is what events you're listening for, so just use your favorite.

How do you get the currently selected <option> in a <select> via JavaScript?

Using the selectedOptions property:

var yourSelect = document.getElementById("your-select-id");
alert(yourSelect.selectedOptions[0].value);

It works in all browsers except Internet Explorer.

If conditions in a Makefile, inside a target

There are several problems here, so I'll start with my usual high-level advice: Start small and simple, add complexity a little at a time, test at every step, and never add to code that doesn't work. (I really ought to have that hotkeyed.)

You're mixing Make syntax and shell syntax in a way that is just dizzying. You should never have let it get this big without testing. Let's start from the outside and work inward.

UNAME := $(shell uname -m)

all:
    $(info Checking if custom header is needed)
    ifeq ($(UNAME), x86_64)
    ... do some things to build unistd_32.h
    endif

    @make -C $(KDIR) M=$(PWD) modules

So you want unistd_32.h built (maybe) before you invoke the second make, you can make it a prerequisite. And since you want that only in a certain case, you can put it in a conditional:

ifeq ($(UNAME), x86_64)
all: unistd_32.h
endif

all:
    @make -C $(KDIR) M=$(PWD) modules

unistd_32.h:
    ... do some things to build unistd_32.h

Now for building unistd_32.h:

F1_EXISTS=$(shell [ -e /usr/include/asm/unistd_32.h ] && echo 1 || echo 0 )
ifeq ($(F1_EXISTS), 1)
    $(info Copying custom header)
    $(shell sed -e 's/__NR_/__NR32_/g' /usr/include/asm/unistd_32.h > unistd_32.h)
else    
    F2_EXISTS=$(shell [[ -e /usr/include/asm-i386/unistd.h ]] && echo 1 || echo 0 )
    ifeq ($(F2_EXISTS), 1)
        $(info Copying custom header)
        $(shell sed -e 's/__NR_/__NR32_/g' /usr/include/asm-i386/unistd.h > unistd_32.h)
    else
        $(error asm/unistd_32.h and asm-386/unistd.h does not exist)
    endif
endif

You are trying to build unistd.h from unistd_32.h; the only trick is that unistd_32.h could be in either of two places. The simplest way to clean this up is to use a vpath directive:

vpath unistd.h /usr/include/asm /usr/include/asm-i386

unistd_32.h: unistd.h
    sed -e 's/__NR_/__NR32_/g' $< > $@

can't load package: package .: no buildable Go source files

Make sure you are using that command in the Go project source folder (like /Users/7yan00/Golang/src/myProject).

One alternative (similar to this bug) is to use the -d option (see go get command)

go get -d

The -d flag instructs get to stop after downloading the packages; that is, it instructs get not to install the packages.

See if that helps in your case.


But more generally, as described in this thread:

go get is for package(s), not for repositories.

so if you want a specific package, say, go.text/encoding, then use

go get code.google.com/p/go.text/encoding

if you want all packages in that repository, use ... to signify that:

go get code.google.com/p/go.text/...

How to read value of a registry key c#

You need to first add using Microsoft.Win32; to your code page.

Then you can begin to use the Registry classes:

try
{
    using (RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\\Wow6432Node\\MySQL AB\\MySQL Connector\\Net"))
    {
        if (key != null)
        {
            Object o = key.GetValue("Version");
            if (o != null)
            {
                Version version = new Version(o as String);  //"as" because it's REG_SZ...otherwise ToString() might be safe(r)
                //do what you like with version
            }
        }
    }
}
catch (Exception ex)  //just for demonstration...it's always best to handle specific exceptions
{
    //react appropriately
}

BEWARE: unless you have administrator access, you are unlikely to be able to do much in LOCAL_MACHINE. Sometimes even reading values can be a suspect operation without admin rights.

Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2:java (default-cli)

I had a similar problem.

As it turned out, I ran mvn clean package install.

Correct way is mvn clean install

Description Box using "onmouseover"

Although not necessarily a JavaScript solution, there is also a "title" global tag attribute that may be helpful.

<a href="https://stackoverflow.com/questions/3559467/description-box-on-mouseover" title="This is a title.">Mouseover me</a>

Mouseover me

Just disable scroll not hide it?

This is the solution we went with. Simply save the scroll position when the overlay is opened, scroll back to the saved position any time the user attempted to scroll the page, and turn the listener off when the overlay is closed.

It's a bit jumpy on IE, but works like a charm on Firefox/Chrome.

_x000D_
_x000D_
var body = $("body"),_x000D_
  overlay = $("#overlay"),_x000D_
  overlayShown = false,_x000D_
  overlayScrollListener = null,_x000D_
  overlaySavedScrollTop = 0,_x000D_
  overlaySavedScrollLeft = 0;_x000D_
_x000D_
function showOverlay() {_x000D_
  overlayShown = true;_x000D_
_x000D_
  // Show overlay_x000D_
  overlay.addClass("overlay-shown");_x000D_
_x000D_
  // Save scroll position_x000D_
  overlaySavedScrollTop = body.scrollTop();_x000D_
  overlaySavedScrollLeft = body.scrollLeft();_x000D_
_x000D_
  // Listen for scroll event_x000D_
  overlayScrollListener = body.scroll(function() {_x000D_
    // Scroll back to saved position_x000D_
    body.scrollTop(overlaySavedScrollTop);_x000D_
    body.scrollLeft(overlaySavedScrollLeft);_x000D_
  });_x000D_
}_x000D_
_x000D_
function hideOverlay() {_x000D_
  overlayShown = false;_x000D_
_x000D_
  // Hide overlay_x000D_
  overlay.removeClass("overlay-shown");_x000D_
_x000D_
  // Turn scroll listener off_x000D_
  if (overlayScrollListener) {_x000D_
    overlayScrollListener.off();_x000D_
    overlayScrollListener = null;_x000D_
  }_x000D_
}_x000D_
_x000D_
// Click toggles overlay_x000D_
$(window).click(function() {_x000D_
  if (!overlayShown) {_x000D_
    showOverlay();_x000D_
  } else {_x000D_
    hideOverlay();_x000D_
  }_x000D_
});
_x000D_
/* Required */_x000D_
html, body { margin: 0; padding: 0; height: 100%; background: #fff; }_x000D_
html { overflow: hidden; }_x000D_
body { overflow-y: scroll; }_x000D_
_x000D_
/* Just for looks */_x000D_
.spacer { height: 300%; background: orange; background: linear-gradient(#ff0, #f0f); }_x000D_
.overlay { position: fixed; top: 20px; bottom: 20px; left: 20px; right: 20px; z-index: -1; background: #fff; box-shadow: 0 0 5px rgba(0, 0, 0, .3); overflow: auto; }_x000D_
.overlay .spacer { background: linear-gradient(#88f, #0ff); }_x000D_
.overlay-shown { z-index: 1; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<h1>Top of page</h1>_x000D_
<p>Click to toggle overlay. (This is only scrollable when overlay is <em>not</em> open.)</p>_x000D_
<div class="spacer"></div>_x000D_
<h1>Bottom of page</h1>_x000D_
<div id="overlay" class="overlay">_x000D_
  <h1>Top of overlay</h1>_x000D_
  <p>Click to toggle overlay. (Containing page is no longer scrollable, but this is.)</p>_x000D_
  <div class="spacer"></div>_x000D_
  <h1>Bottom of overlay</h1>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Show loading gif after clicking form submit using jQuery

Better and clean example using JS only

Reference: TheDeveloperBlog.com

Step 1 - Create your java script and place it in your HTML page.

<script type="text/javascript">
    function ShowLoading(e) {
        var div = document.createElement('div');
        var img = document.createElement('img');
        img.src = 'loading_bar.GIF';
        div.innerHTML = "Loading...<br />";
        div.style.cssText = 'position: fixed; top: 5%; left: 40%; z-index: 5000; width: 422px; text-align: center; background: #EDDBB0; border: 1px solid #000';
        div.appendChild(img);
        document.body.appendChild(div);
        return true;
        // These 2 lines cancel form submission, so only use if needed.
        //window.event.cancelBubble = true;
        //e.stopPropagation();
    }
</script>

in your form call the java script function on submit event.

<form runat="server"  onsubmit="ShowLoading()">
</form>

Soon after you submit the form, it will show you the loading image.

Listview Scroll to the end of the list after updating the list

The simplest solution is :

    listView.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
    listView.setStackFromBottom(true);

RegEx for Javascript to allow only alphanumeric

/^[a-z0-9]+$/i

^         Start of string
[a-z0-9]  a or b or c or ... z or 0 or 1 or ... 9
+         one or more times (change to * to allow empty string)
$         end of string    
/i        case-insensitive

Update (supporting universal characters)

if you need to this regexp supports universal character you can find list of unicode characters here.

for example: /^([a-zA-Z0-9\u0600-\u06FF\u0660-\u0669\u06F0-\u06F9 _.-]+)$/

this will support persian.

Passing environment-dependent variables in webpack

Since Webpack v4, simply setting mode in your Webpack config will set the NODE_ENV for you (via DefinePlugin). Docs here.

Custom bullet symbol for <li> elements in <ul> that is a regular character, and not an image

You can make use of ::marker pseudo element. This is useful in situations when you need to have different character entities for each list item.

ul li::marker {
  content: " "; /* Your symbol here */
}

_x000D_
_x000D_
ul li:nth-child(1)::marker {
  content: "\26BD   ";
}

ul li:nth-child(2)::marker {
  content: "\26C5   ";
}

ul li:nth-child(3)::marker {
  content: "\26F3   ";
}

ul li::marker {
  font-size: 20px;
}

ul li {
  margin: 15px 0;
  font-family: sans-serif;
  background: #BADA55;
  color: black;
  padding-bottom: 10px;
  padding-left: 10px;
  padding-top: 5px;
}
_x000D_
<ul>
  <li>France Vs Croatia</li>
  <li>Cloudy with sunshine</li>
  <li>Golf session ahead</li>
</ul>
_x000D_
_x000D_
_x000D_

How copy data from Excel to a table using Oracle SQL Developer

Click on "Tables" in "Connections" window, choose "Import data ...", follow the wizard and you will be asked for name for new table.

Create a asmx web service in C# using visual studio 2013

Check your namespaces. I had and issue with that. I found that out by adding another web service to the project to dup it like you did yours and noticed the namespace was different. I had renamed it at the beginning of the project and it looks like its persisted.

MVC 4 Razor adding input type date

 @Html.TextBoxFor(m => m.EntryDate, new{ type = "date" })

 or type = "time"

 it will display a calendar
 it will not work if you give @Html.EditorFor()

Figure out size of UILabel based on String in Swift

I found that the accepted answer worked for a fixed width, but not a fixed height. For a fixed height, it would just increase the width to fit everything on one line, unless there was a line break in the text.

The width function calls the height function multiple times, but it is a quick calculation and I didn't notice performance issues using the function in the rows of a UITable.

extension String {

    public func height(withConstrainedWidth width: CGFloat, font: UIFont) -> CGFloat {
        let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
        let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [.font : font], context: nil)

        return ceil(boundingBox.height)
    }

    public func width(withConstrainedHeight height: CGFloat, font: UIFont, minimumTextWrapWidth:CGFloat) -> CGFloat {

        var textWidth:CGFloat = minimumTextWrapWidth
        let incrementWidth:CGFloat = minimumTextWrapWidth * 0.1
        var textHeight:CGFloat = self.height(withConstrainedWidth: textWidth, font: font)

        //Increase width by 10% of minimumTextWrapWidth until minimum width found that makes the text fit within the specified height
        while textHeight > height {
            textWidth += incrementWidth
            textHeight = self.height(withConstrainedWidth: textWidth, font: font)
        }
        return ceil(textWidth)
    }
}

Get text of the selected option with jQuery

$(document).ready(function() {
    $('select#select_2').change(function() {
        var selectedText = $(this).find('option:selected').text();
        alert(selectedText);
    });
});

Fiddle

How do I call the base class constructor?

There is no super() in C++. You have to call the Base Constructor explicitly by name.

Find the host name and port using PSQL commands

SELECT CURRENT_USER usr, :'HOST' host, inet_server_port() port;

This uses psql's built in HOST variable, documented here

And postgres System Information Functions, documented here

Convert timestamp long to normal date format

java.time

    ZoneId usersTimeZone = ZoneId.of("Asia/Tashkent");
    Locale usersLocale = Locale.forLanguageTag("ga-IE");
    DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM)
            .withLocale(usersLocale);

    long microsSince1970 = 1_512_345_678_901_234L;
    long secondsSince1970 = TimeUnit.MICROSECONDS.toSeconds(microsSince1970);
    long remainingMicros = microsSince1970 - TimeUnit.SECONDS.toMicros(secondsSince1970);
    ZonedDateTime dateTime = Instant.ofEpochSecond(secondsSince1970, 
                    TimeUnit.MICROSECONDS.toNanos(remainingMicros))
            .atZone(usersTimeZone);
    String dateTimeInUsersFormat = dateTime.format(formatter);
    System.out.println(dateTimeInUsersFormat);

The above snippet prints:

4 Noll 2017 05:01:18

“Noll” is Gaelic for December, so this should make your user happy. Except there may be very few Gaelic speaking people living in Tashkent, so please specify the user’s correct time zone and locale yourself.

I am taking seriously that you got microseconds from your database. If second precision is fine, you can do without remainingMicros and just use the one-arg Instant.ofEpochSecond(), which will make the code a couple of lines shorter. Since Instant and ZonedDateTime do support nanosecond precision, I found it most correct to keep the full precision of your timestamp. If your timestamp was in milliseconds rather than microseconds (which they often are), you may just use Instant.ofEpochMilli().

The answers using Date, Calendar and/or SimpleDateFormat were fine when this question was asked 7 years ago. Today those classes are all long outdated, and we have so much better in java.time, the modern Java date and time API.

For most uses I recommend you use the built-in localized formats as I do in the code. You may experiment with passing SHORT, LONG or FULL for format style. Yo may even specify format style for the date and for the time of day separately using an overloaded ofLocalizedDateTime method. If a specific format is required (this was asked in a duplicate question), you can have that:

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss, dd/MM/uuuu");

Using this formatter instead we get

05:01:18, 04/12/2017

Link: Oracle tutorial: Date Time explaining how to use java.time.

What's the difference between lists and tuples?

Lists are mutable and tuples are immutable. Just consider this example.

a = ["1", "2", "ra", "sa"]    #list
b = ("1", "2", "ra", "sa")    #tuple

Now change index values of list and tuple.

a[2] = 1000
print a     #output : ['1', '2', 1000, 'sa']
b[2] = 1000
print b     #output : TypeError: 'tuple' object does not support item assignment.

Hence proved the following code is invalid with tuple, because we attempted to update a tuple, which is not allowed.

How can I create Min stl priority_queue?

Multiply values with -1 and use max heap to get the effect of min heap

Apache HttpClient Android (Gradle)

I resolved problem by adding following to my build.gradle file

android {
useLibrary 'org.apache.http.legacy'}

However this only works if you are using gradle 1.3.0-beta2 or greater, so you will have to add this to buildscript dependencies if you are on a lower version:

classpath 'com.android.tools.build:gradle:1.3.0-beta2'

jQuery UI 1.10: dialog and zIndex option

You may want to try jQuery dialog method:

$( ".selector" ).dialog( "moveToTop" );

reference: http://api.jqueryui.com/dialog/#method-moveToTop

hibernate could not get next sequence value

You need to set your @GeneratedId column with strategy GenerationType.IDENTITY instead of GenerationType.AUTO

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "JUD_ID")
private Long _judId;

Python unicode equal comparison failed

You may use the == operator to compare unicode objects for equality.

>>> s1 = u'Hello'
>>> s2 = unicode("Hello")
>>> type(s1), type(s2)
(<type 'unicode'>, <type 'unicode'>)
>>> s1==s2
True
>>> 
>>> s3='Hello'.decode('utf-8')
>>> type(s3)
<type 'unicode'>
>>> s1==s3
True
>>> 

But, your error message indicates that you aren't comparing unicode objects. You are probably comparing a unicode object to a str object, like so:

>>> u'Hello' == 'Hello'
True
>>> u'Hello' == '\x81\x01'
__main__:1: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
False

See how I have attempted to compare a unicode object against a string which does not represent a valid UTF8 encoding.

Your program, I suppose, is comparing unicode objects with str objects, and the contents of a str object is not a valid UTF8 encoding. This seems likely the result of you (the programmer) not knowing which variable holds unicide, which variable holds UTF8 and which variable holds the bytes read in from a file.

I recommend http://nedbatchelder.com/text/unipain.html, especially the advice to create a "Unicode Sandwich."

Not able to pip install pickle in python 3.6

Pickle is a module installed for both Python 2 and Python 3 by default. See the standard library for 3.6.4 and 2.7.

Also to prove what I am saying is correct try running this script:

import pickle
print(pickle.__doc__)

This will print out the Pickle documentation showing you all the functions (and a bit more) it provides.

Or you can start the integrated Python 3.6 Module Docs and check there.

As a rule of thumb: if you can import the module without an error being produced then it is installed

The reason for the No matching distribution found for pickle is because libraries for included packages are not available via pip because you already have them (I found this out yesterday when I tried to install an integrated package).

If it's running without errors but it doesn't work as expected I would think that you made a mistake somewhere (perhaps quickly check the functions you are using in the docs). Python is very informative with it's errors so we generally know if something is wrong.

How to split a string, but also keep the delimiters?

import java.util.regex.*;
import java.util.LinkedList;

public class Splitter {
    private static final Pattern DEFAULT_PATTERN = Pattern.compile("\\s+");

    private Pattern pattern;
    private boolean keep_delimiters;

    public Splitter(Pattern pattern, boolean keep_delimiters) {
        this.pattern = pattern;
        this.keep_delimiters = keep_delimiters;
    }
    public Splitter(String pattern, boolean keep_delimiters) {
        this(Pattern.compile(pattern==null?"":pattern), keep_delimiters);
    }
    public Splitter(Pattern pattern) { this(pattern, true); }
    public Splitter(String pattern) { this(pattern, true); }
    public Splitter(boolean keep_delimiters) { this(DEFAULT_PATTERN, keep_delimiters); }
    public Splitter() { this(DEFAULT_PATTERN); }

    public String[] split(String text) {
        if (text == null) {
            text = "";
        }

        int last_match = 0;
        LinkedList<String> splitted = new LinkedList<String>();

        Matcher m = this.pattern.matcher(text);

        while (m.find()) {

            splitted.add(text.substring(last_match,m.start()));

            if (this.keep_delimiters) {
                splitted.add(m.group());
            }

            last_match = m.end();
        }

        splitted.add(text.substring(last_match));

        return splitted.toArray(new String[splitted.size()]);
    }

    public static void main(String[] argv) {
        if (argv.length != 2) {
            System.err.println("Syntax: java Splitter <pattern> <text>");
            return;
        }

        Pattern pattern = null;
        try {
            pattern = Pattern.compile(argv[0]);
        }
        catch (PatternSyntaxException e) {
            System.err.println(e);
            return;
        }

        Splitter splitter = new Splitter(pattern);

        String text = argv[1];
        int counter = 1;
        for (String part : splitter.split(text)) {
            System.out.printf("Part %d: \"%s\"\n", counter++, part);
        }
    }
}

/*
    Example:
    > java Splitter "\W+" "Hello World!"
    Part 1: "Hello"
    Part 2: " "
    Part 3: "World"
    Part 4: "!"
    Part 5: ""
*/

I don't really like the other way, where you get an empty element in front and back. A delimiter is usually not at the beginning or at the end of the string, thus you most often end up wasting two good array slots.

Edit: Fixed limit cases. Commented source with test cases can be found here: http://snippets.dzone.com/posts/show/6453

Python map object is not subscriptable

In Python 3, map returns an iterable object of type map, and not a subscriptible list, which would allow you to write map[i]. To force a list result, write

payIntList = list(map(int,payList))

However, in many cases, you can write out your code way nicer by not using indices. For example, with list comprehensions:

payIntList = [pi + 1000 for pi in payList]
for pi in payIntList:
    print(pi)

JavaScript window resize event

The following blog post may be useful to you: Fixing the window resize event in IE

It provides this code:

Sys.Application.add_load(function(sender, args) {
    $addHandler(window, 'resize', window_resize);
});

var resizeTimeoutId;

function window_resize(e) {
     window.clearTimeout(resizeTimeoutId);
     resizeTimeoutId = window.setTimeout('doResizeCode();', 10);
}

Logical operator in a handlebars.js {{#if}} conditional

I can understand why you would want to create a helper for situations where you have a large number of varied comparisons to perform within your template, but for a relatively small number of comparisons (or even one, which was what brought me to this page in the first place), it would probably just be easier to define a new handlebars variable in your view-rendering function call, like:

Pass to handlebars on render:

var context= {
    'section1' : section1,
    'section2' : section2,
    'section1or2' : (section1)||(section2)
};

and then within your handlebars template:

{{#if section1or2}}
    .. content
{{/if}}

I mention this for simplicity's sake, and also because it's an answer that may be quick and helpful while still complying with the logicless nature of Handlebars.

How to ftp with a batch file?

Using the Windows FTP client you would want to use the -s:filename option to specify a script for the FTP client to run. The documentation specifically points out that you should not try to pipe input into the FTP client with a < character.

Execution of the script will start immediately, so it does work for username/password.

However, the security of this setup is questionable since you now have a username and password for the FTP server visible to anyone who decides to look at your batch file.

Either way, you can generate the script file on the fly from the batch file and then pass it to the FTP client like so:

@echo off

REM Generate the script. Will overwrite any existing temp.txt
echo open servername> temp.txt
echo username>> temp.txt
echo password>> temp.txt
echo get %1>> temp.txt
echo quit>> temp.txt

REM Launch FTP and pass it the script
ftp -s:temp.txt

REM Clean up.
del temp.txt

Replace servername, username, and password with your details and the batch file will generate the script as temp.txt launch ftp with the script and then delete the script.

If you are always getting the same file you can replace the %1 with the file name. If not you just launch the batchfile and provide the name of the file to get as an argument.

Read Numeric Data from a Text File in C++

Repeat >> reads in loop.

#include <iostream>
#include <fstream>
int main(int argc, char * argv[])
{
    std::fstream myfile("D:\\data.txt", std::ios_base::in);

    float a;
    while (myfile >> a)
    {
        printf("%f ", a);
    }

    getchar();

    return 0;
}

Result:

45.779999 67.900002 87.000000 34.889999 346.000000 0.980000

If you know exactly, how many elements there are in a file, you can chain >> operator:

int main(int argc, char * argv[])
{
    std::fstream myfile("D:\\data.txt", std::ios_base::in);

    float a, b, c, d, e, f;

    myfile >> a >> b >> c >> d >> e >> f;

    printf("%f\t%f\t%f\t%f\t%f\t%f\n", a, b, c, d, e, f);

    getchar();

    return 0;
}

Edit: In response to your comments in main question.

You have two options.

  • You can run previous code in a loop (or two loops) and throw away a defined number of values - for example, if you need the value at point (97, 60), you have to skip 5996 (= 60 * 100 + 96) values and use the last one. This will work if you're interested only in specified value.
  • You can load the data into an array - as Jerry Coffin sugested. He already gave you quite nice class, which will solve the problem. Alternatively, you can use simple array to store the data.

Edit: How to skip values in file

To choose the 1234th value, use the following code:

int skipped = 1233;
for (int i = 0; i < skipped; i++)
{
    float tmp;
    myfile >> tmp;
}
myfile >> value;

How to capture Curl output to a file?

A tad bit late, but I think the OP was looking for something like:

curl -K myfile.txt --trace-asci output.txt

Where is the user's Subversion config file stored on the major operating systems?

Not sure about Win but n *nix (OS X, Linux, etc.) its in ~/.subversion

Is HTML considered a programming language?

Well, L is for language, but it doesn't imply programming language. After all, English or French are (natural) languages too! ;-)

As said above, put them under a subsidiary section, Technology seems to be a good term.

(Looking at my own resume, not updated in a while) I have made a section just called "Languages", so I can't get wrong... :-D
I have put "(X)HTML and CSS, XML/DTD/Schema and SVG" at the end of the section, clearly separated.

In French, I have a section "Langages" (programming and markup) and another "Langues" (French/English). In the English version, I titled both at "Languages", which is clumsy now that I think of it, although context clarify this. I should find a better formulation.

Android Overriding onBackPressed()

Best and most generic way to control the music is to create a mother Activity in which you override startActivity(Intent intent) - in it you put shouldPlay=true, and onBackPressed() - in it you put shouldPlay = true. onStop - in it you put a conditional mediaPlayer.stop with shouldPlay as condition

Then, just extend the mother activity to all other activities, and no code duplicating is needed.

How to select bottom most rows?

It would seem that any of the answers which implement an ORDER BY clause in the solution is missing the point, or does not actually understand what TOP returns to you.

TOP returns an unordered query result set which limits the record set to the first N records returned. (From an Oracle perspective, it is akin to adding a where ROWNUM < (N+1).

Any solution which uses an order, may return rows which also are returned by the TOP clause (since that data set was unordered in the first place), depending on what criteria was used in the order by

The usefulness of TOP is that once the dataset reaches a certain size N, it stops fetching rows. You can get a feel for what the data looks like without having to fetch all of it.

To implement BOTTOM accurately, it would need to fetch the entire dataset unordered and then restrict the dataset to the final N records. That will not be particularly effective if you are dealing with huge tables. Nor will it necessarily give you what you think you are asking for. The end of the data set may not necessarily be "the last rows inserted" (and probably won't be for most DML intensive applications).

Similarly, the solutions which implement an ORDER BY are, unfortunately, potentially disastrous when dealing with large data sets. If I have, say, 10 Billion records and want the last 10, it is quite foolish to order 10 Billion records and select the last 10.

The problem here, is that BOTTOM does not have the meaning that we think of when comparing it to TOP.

When records are inserted, deleted, inserted, deleted over and over and over again, some gaps will appear in the storage and later, rows will be slotted in, if possible. But what we often see, when we select TOP, appears to be sorted data, because it may have been inserted early on in the table's existence. If the table does not experience many deletions, it may appear to be ordered. (e.g. creation dates may be as far back in time as the table creation itself). But the reality is, if this is a delete-heavy table, the TOP N rows may not look like that at all.

So -- the bottom line here(pun intended) is that someone who is asking for the BOTTOM N records doesn't actually know what they're asking for. Or, at least, what they're asking for and what BOTTOM actually means are not the same thing.

So -- the solution may meet the actual business need of the requestor...but does not meet the criteria for being the BOTTOM.

VS 2017 Git Local Commit DB.lock error on every commit

Step 1:
Add .vs/ to your .gitignore file (as said in other answers).

Step 2:
It is important to understand, that step 1 WILL NOT remove files within .vs/ from your current branch index, if they have already been added to it. So clear your active branch by issuing:

git rm --cached -r .vs/*

Step 3:
Best to immediately repeat steps 1 and 2 for all other active branches of your project as well.
Otherwise you will easily face the same problems again when switching to an uncleaned branch.

Pro tip:
Instead of step 1 you may want to to use this official .gitingore template for VisualStudio that covers much more than just the .vs path:
https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
(But still don't forget steps 2 and 3.)

mysqldump Error 1045 Access denied despite correct passwords etc

In my case, I could access correctly with mysql.exe but not with mysqldump.exe.

The problem was the port for my connection was not the default one (3306) and I had to put the mysqldump port work with (-P3307)

mysqldump -u root -p -P3307 my_database > /path/backup_database

Increment a database field by 1

You didn't say what you're trying to do, but you hinted at it well enough in the comments to the other answer. I think you're probably looking for an auto increment column

create table logins (userid int auto_increment primary key, 
  username varchar(30), password varchar(30));

then no special code is needed on insert. Just

insert into logins (username, password) values ('user','pass');

The MySQL API has functions to tell you what userid was created when you execute this statement in client code.

Is there a regular expression to detect a valid regular expression?

Though it is perfectly possible to use a recursive regex as MizardX has posted, for this kind of things it is much more useful a parser. Regexes were originally intended to be used with regular languages, being recursive or having balancing groups is just a patch.

The language that defines valid regexes is actually a context free grammar, and you should use an appropriate parser for handling it. Here is an example for a university project for parsing simple regexes (without most constructs). It uses JavaCC. And yes, comments are in Spanish, though method names are pretty self-explanatory.

SKIP :
{
    " "
|   "\r"
|   "\t"
|   "\n"
}
TOKEN : 
{
    < DIGITO: ["0" - "9"] >
|   < MAYUSCULA: ["A" - "Z"] >
|   < MINUSCULA: ["a" - "z"] >
|   < LAMBDA: "LAMBDA" >
|   < VACIO: "VACIO" >
}

IRegularExpression Expression() :
{
    IRegularExpression r; 
}
{
    r=Alternation() { return r; }
}

// Matchea disyunciones: ER | ER
IRegularExpression Alternation() :
{
    IRegularExpression r1 = null, r2 = null; 
}
{
    r1=Concatenation() ( "|" r2=Alternation() )?
    { 
        if (r2 == null) {
            return r1;
        } else {
            return createAlternation(r1,r2);
        } 
    }
}

// Matchea concatenaciones: ER.ER
IRegularExpression Concatenation() :
{
    IRegularExpression r1 = null, r2 = null; 
}
{
    r1=Repetition() ( "." r2=Repetition() { r1 = createConcatenation(r1,r2); } )*
    { return r1; }
}

// Matchea repeticiones: ER*
IRegularExpression Repetition() :
{
    IRegularExpression r; 
}
{
    r=Atom() ( "*" { r = createRepetition(r); } )*
    { return r; }
}

// Matchea regex atomicas: (ER), Terminal, Vacio, Lambda
IRegularExpression Atom() :
{
    String t;
    IRegularExpression r;
}
{
    ( "(" r=Expression() ")" {return r;}) 
    | t=Terminal() { return createTerminal(t); }
    | <LAMBDA> { return createLambda(); }
    | <VACIO> { return createEmpty(); }
}

// Matchea un terminal (digito o minuscula) y devuelve su valor
String Terminal() :
{
    Token t;
}
{
    ( t=<DIGITO> | t=<MINUSCULA> ) { return t.image; }
}

Generate an integer sequence in MySQL

How big is m?

You could do something like:

create table two select null foo union all select null;
create temporary table seq ( foo int primary key auto_increment ) auto_increment=9 select a.foo from two a, two b, two c, two d;
select * from seq where foo <= 23;

where the auto_increment is set to n and the where clause compares to m and the number of times the two table is repeated is at least ceil(log(m-n+1)/log(2)).

(The non-temporary two table could be omitted by replacing two with (select null foo union all select null) in the create temporary table seq.)

How to find longest string in the table column data

If column datatype is text you should use DataLength function like:

select top 1 CR, DataLength(CR)
from tbl
order by DataLength(CR) desc

How to round a numpy array?

Numpy provides two identical methods to do this. Either use

np.round(data, 2)

or

np.around(data, 2)

as they are equivalent.

See the documentation for more information.


Examples:

>>> import numpy as np
>>> a = np.array([0.015, 0.235, 0.112])
>>> np.round(a, 2)
array([0.02, 0.24, 0.11])
>>> np.around(a, 2)
array([0.02, 0.24, 0.11])
>>> np.round(a, 1)
array([0. , 0.2, 0.1])

Adding timestamp to a filename with mv in BASH

You can write your scripts in notepad but just make sure you convert them using this -> $ sed -i 's/\r$//' yourscripthere

I use it all they time when I'm working in cygwin and it works. Hope this helps

What is the difference between Left, Right, Outer and Inner Joins?

There are only 4 kinds:

  1. Inner join: The most common type. An output row is produced for every pair of input rows that match on the join conditions.
  2. Left outer join: The same as an inner join, except that if there is any row for which no matching row in the table on the right can be found, a row is output containing the values from the table on the left, with NULL for each value in the table on the right. This means that every row from the table on the left will appear at least once in the output.
  3. Right outer join: The same as a left outer join, except with the roles of the tables reversed.
  4. Full outer join: A combination of left and right outer joins. Every row from both tables will appear in the output at least once.

A "cross join" or "cartesian join" is simply an inner join for which no join conditions have been specified, resulting in all pairs of rows being output.

Thanks to RusselH for pointing out FULL joins, which I'd omitted.

How to get Java Decompiler / JD / JD-Eclipse running in Eclipse Helios

  1. Download the JD-Eclipse Update Site(github.com/java-decompiler/jd-eclipse)
  2. Launch Eclipse,

  3. Click on "Help > Install New Software...",

  4. Click on button "Add..." to add an new repository,

  5. Enter "JD-Eclipse Update Site" and select the local site directory,

  6. Check "Java Decompiler Eclipse Plug-in",

  7. Next, next, next... and restart Eclipse.

How to use *ngIf else?

In Angular 4.0 if..else syntax is quite similar to conditional operators in Java.

In Java you use to "condition?stmnt1:stmnt2".

In Angular 4.0 you use *ngIf="condition;then stmnt1 else stmnt2".

Assign one struct to another in C

Yes, you can assign one instance of a struct to another using a simple assignment statement.

  • In the case of non-pointer or non pointer containing struct members, assignment means copy.

  • In the case of pointer struct members, assignment means pointer will point to the same address of the other pointer.

Let us see this first hand:

#include <stdio.h>

struct Test{
    int foo;
    char *bar;
};

int main(){
    struct Test t1;
    struct Test t2;
    t1.foo = 1;
    t1.bar = malloc(100 * sizeof(char));
    strcpy(t1.bar, "t1 bar value");
    t2.foo = 2;
    t2.bar = malloc(100 * sizeof(char));
    strcpy(t2.bar, "t2 bar value");
    printf("t2 foo and bar before copy: %d %s\n", t2.foo, t2.bar);
    t2 = t1;// <---- ASSIGNMENT
    printf("t2 foo and bar after copy: %d %s\n", t2.foo, t2.bar);
    //The following 3 lines of code demonstrate that foo is deep copied and bar is shallow copied
    strcpy(t1.bar, "t1 bar value changed");
    t1.foo = 3;
    printf("t2 foo and bar after t1 is altered: %d %s\n", t2.foo, t2.bar);
    return 0;
}

Page scroll when soft keyboard popped up

In your Manifest define windowSoftInputMode property:

<activity android:name=".MyActivity"
          android:windowSoftInputMode="adjustNothing">

Efficiency of Java "Double Brace Initialization"?

I second Nat's answer, except I would use a loop instead of creating and immediately tossing the implicit List from asList(elements):

static public Set<T> setOf(T ... elements) {
    Set set=new HashSet<T>(elements.size());
    for(T elm: elements) { set.add(elm); }
    return set;
    }

How to iterate through XML in Powershell?

PowerShell has built-in XML and XPath functions. You can use the Select-Xml cmdlet with an XPath query to select nodes from XML object and then .Node.'#text' to access node value.

[xml]$xml = Get-Content $serviceStatePath
$nodes = Select-Xml "//Object[Property/@Name='ServiceState' and Property='Running']/Property[@Name='DisplayName']" $xml
$nodes | ForEach-Object {$_.Node.'#text'}

Or shorter

[xml]$xml = Get-Content $serviceStatePath
Select-Xml "//Object[Property/@Name='ServiceState' and Property='Running']/Property[@Name='DisplayName']" $xml |
  % {$_.Node.'#text'}

How to get query string parameter from MVC Razor markup?

For Asp.net Core 2

ViewContext.ModelState["id"].AttemptedValue

An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll

There are some problems with your code. First I advise to use parametrized queries so you avoid SQL Injection attacks and also parameter types are discovered by framework:

var cmd = new SqlCommand("SELECT EmpName FROM Employee WHERE EmpID = @id", con);
cmd.Parameters.AddWithValue("@id", id.Text);

Second, as you are interested only in one value getting returned from the query, it is better to use ExecuteScalar:

var name = cmd.ExecuteScalar();

if (name != null)
{
   position = name.ToString();
   Response.Write("User Registration successful");
}
else
{
    Console.WriteLine("No Employee found.");
}

The last thing is to wrap SqlConnection and SqlCommand into using so any resources used by those will be disposed of:

string position;

using (SqlConnection con = new SqlConnection("server=free-pc\\FATMAH; Integrated Security=True; database=Workflow; "))
{
  con.Open();

  using (var cmd = new SqlCommand("SELECT EmpName FROM Employee WHERE EmpID = @id", con))
  {
    cmd.Parameters.AddWithValue("@id", id.Text);
  
    var name = cmd.ExecuteScalar();
  
    if (name != null)
    {
       position = name.ToString();
       Response.Write("User Registration successful");
    }
    else
    {
        Console.WriteLine("No Employee found.");
    }
  }
}

What is simplest way to read a file into String?

Using Apache Commons IO.

import org.apache.commons.io.FileUtils;

//...

String contents = FileUtils.readFileToString(new File("/path/to/the/file"), "UTF-8")

You can see de javadoc for the method for details.

Can't push to the heroku

Read this doc which will explain to you what to do.
https://devcenter.heroku.com/articles/buildpacks

Setting a buildpack on an application

You can change the buildpack used by an application by setting the buildpack value.
When the application is next pushed, the new buildpack will be used.

$ heroku buildpacks:set heroku/php

Buildpack set. Next release on random-app-1234 will use heroku/php.
Run git push heroku master to create a new release using this buildpack.

This is whay its not working for you since you did not set it up.

... When the application is next pushed, the new buildpack will be used.

You may also specify a buildpack during app creation:

$ heroku create myapp --buildpack heroku/python

How to import a bak file into SQL Server Express

I had the same error. What worked for me is when you go for the SMSS GUI option, look at General, Files in Options settings. After I did that (replace DB, set location) all went well.

How to read input from console in a batch file?

The code snippet in the linked proposed duplicate reads user input.

ECHO A current build of Test Harness exists.
set /p delBuild=Delete preexisting build [y/n]?: 

The user can type as many letters as they want, and it will go into the delBuild variable.

file_get_contents(): SSL operation failed with code 1, Failed to enable crypto

You shouldn't just turn off verification. Rather you should download a certificate bundle, perhaps the curl bundle will do?

Then you just need to put it on your web server, giving the user that runs php permission to read the file. Then this code should work for you:

$arrContextOptions= [
    'ssl' => [
        'cafile' => '/path/to/bundle/cacert.pem',
        'verify_peer'=> true,
        'verify_peer_name'=> true,
    ],
];

$response = file_get_contents(
    'https://maps.co.weber.ut.us/arcgis/rest/services/SDE_composite_locator/GeocodeServer/findAddressCandidates?Street=&SingleLine=3042+N+1050+W&outFields=*&outSR=102100&searchExtent=&f=json',
    false,
    stream_context_create($arrContextOptions)
);

Hopefully, the root certificate of the site you are trying to access is in the curl bundle. If it isn't, this still won't work until you get the root certificate of the site and put it into your certificate file.

Set active tab style with AngularJS

Simplest solution here:

How to set bootstrap navbar active class with Angular JS?

Which is:

Use ng-controller to run a single controller outside of the ng-view:

<div class="collapse navbar-collapse" ng-controller="HeaderController">
    <ul class="nav navbar-nav">
        <li ng-class="{ active: isActive('/')}"><a href="/">Home</a></li>
        <li ng-class="{ active: isActive('/dogs')}"><a href="/dogs">Dogs</a></li>
        <li ng-class="{ active: isActive('/cats')}"><a href="/cats">Cats</a></li>
    </ul>
</div>
<div ng-view></div>

and include in controllers.js:

function HeaderController($scope, $location) 
{ 
    $scope.isActive = function (viewLocation) { 
        return viewLocation === $location.path();
    };
}

npm install errors with Error: ENOENT, chmod

The same error during global install (npm install -g mymodule) for package with a non-existing script.

In package.json:

    ...
    "bin": {
      "module": "./bin/module"
    },
    ...

But the ./bin/module did not exist, as it was named modulejs.

Uncaught TypeError: Object #<Object> has no method 'movingBoxes'

It's also a good idea to make sure you're using the correct version of jQuery. I had recently acquired a project using jQuery 1.6.2 that wasn't working with the hoverIntent plugin. Upgrading it to the most recent version fixed that for me.

How do you select the entire excel sheet with Range using VBA?

Refering to the very first question, I am looking into the same. The result I get, recording a macro, is, starting by selecting cell A76:

Sub find_last_row()
    Range("A76").Select
    Range(Selection, Selection.End(xlDown)).Select
End Sub

Detect if a jQuery UI dialog box is open

Actually, you have to explicitly compare it to true. If the dialog doesn't exist yet, it will not return false (as you would expect), it will return a DOM object.

if ($('#mydialog').dialog('isOpen') === true) {
    // true
} else {
    // false
}

jQuery validation: change default error message

The newest version has some nice in-line stuff you can do.

If it's a simple input field you can add the attribute data-validation-error-msg like this --

data-validation-error-msg="Invalid Regex"

If you need something a little heavier you can fully customize things using a variable with all the values which is passed into the validate function. Reference this link for full details -- https://github.com/victorjonsson/jQuery-Form-Validator#fully-customizable

How to add ASP.NET 4.0 as Application Pool on IIS 7, Windows 7

In the top level of the IIS Manager (above Sites), you should see the Application Pools tree node. Right click on "Application Pools", choose "Add Application Pool".

Give it a name, choose .NET Framework 4.0 and either Integrated or Classic mode.

When you add or edit a web site, your new application pools will now show up in the list.

How to find when a web page was last updated

This is a Pythonic way to do it:

import httplib
import yaml
c = httplib.HTTPConnection(address)
c.request('GET', url_path)
r = c.getresponse()
# get the date into a datetime object
lmd = r.getheader('last-modified')
if lmd != None:
   cur_data = { url: datetime.strptime(lmd, '%a, %d %b %Y %H:%M:%S %Z') }
else:
   print "Hmmm, no last-modified data was returned from the URL."
   print "Returned header:"
   print yaml.dump(dict(r.getheaders()), default_flow_style=False)

The rest of the script includes an example of archiving a page and checking for changes against the new version, and alerting someone by email.

What is a callback?

In computer programming, a callback is executable code that is passed as an argument to other code.

Wikipedia: Callback (computer science)

C# has delegates for that purpose. They are heavily used with events, as an event can automatically invoke a number of attached delegates (event handlers).

C# list.Orderby descending

Sure:

var newList = list.OrderByDescending(x => x.Product.Name).ToList();

Doc: OrderByDescending(IEnumerable, Func).

In response to your comment:

var newList = list.OrderByDescending(x => x.Product.Name)
                  .ThenBy(x => x.Product.Price)
                  .ToList();

SQL Server stored procedure Nullable parameter

It looks like you're passing in Null for every argument except for PropertyValueID and DropDownOptionID, right? I don't think any of your IF statements will fire if only these two values are not-null. In short, I think you have a logic error.

Other than that, I would suggest two things...

First, instead of testing for NULL, use this kind syntax on your if statements (it's safer)...

    ELSE IF ISNULL(@UnitValue, 0) != 0 AND ISNULL(@UnitOfMeasureID, 0) = 0

Second, add a meaningful PRINT statement before each UPDATE. That way, when you run the sproc in MSSQL, you can look at the messages and see how far it's actually getting.

Android button with different background colors

As your error states, you have to define drawable attibute for the items (for some reason it is required when it comes to background definitions), so:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@color/red"/> <!-- pressed -->
    <item android:state_focused="true" android:drawable="@color/blue"/> <!-- focused -->
    <item android:drawable="@color/black"/> <!-- default -->
</selector>

Also note that drawable attribute doesn't accept raw color values, so you have to define the colors as resources. Create colors.xml file at res/values folder:

<?xml version="1.0" encoding="utf-8"?>
<resources>
     <color name="black">#000</color>
     <color name="blue">#00f</color>
     <color name="red">#f00</color>
</resources>

How can I select records ONLY from yesterday?

If you want the timestamp for yesterday try something like:

(CURRENT_TIMESTAMP - INTERVAL '1' DAY)

Simple way to create matrix of random numbers

use np.random.randint() as np.random.random_integers() is deprecated

random_matrix = np.random.randint(min_val,max_val,(<num_rows>,<num_cols>))

Git stash pop- needs merge, unable to refresh index

I have found that the best solution is to branch off your stash and do a resolution afterwards.

git stash branch <branch-name>

if you drop of clear your stash, you may lose your changes and you will have to recur to the reflog.

IE11 prevents ActiveX from running

Here's how I got it working:

  1. Include your URL in IE Trusted Sites

  2. run gpedit.msc (as Admin) and enable the following setting:

gpedit->Local->Computer->Windows Comp->ActiveX Installer->ActiveX installation policy for sites in Trusted Zones

Enabled + Silently,Silently,Prompt

  1. Run gpupdate

  2. Relaunch your Browser

NOTES: Windows 10 EDGE don't have trusted sites, so you have to use IE 11. Lots of folk moaning about that!

Static method in a generic class?

Since static variables are shared by all instances of the class. For example if you are having following code

class Class<T> {
  static void doIt(T object) {
    // using T here 
  }
}

T is available only after an instance is created. But static methods can be used even before instances are available. So, Generic type parameters cannot be referenced inside static methods and variables

How to get thread id from a thread pool?

The accepted answer answers the question about getting a thread id, but it doesn't let you do "Thread X of Y" messages. Thread ids are unique across threads but don't necessarily start from 0 or 1.

Here is an example matching the question:

import java.util.concurrent.*;
class ThreadIdTest {

  public static void main(String[] args) {

    final int numThreads = 5;
    ExecutorService exec = Executors.newFixedThreadPool(numThreads);

    for (int i=0; i<10; i++) {
      exec.execute(new Runnable() {
        public void run() {
          long threadId = Thread.currentThread().getId();
          System.out.println("I am thread " + threadId + " of " + numThreads);
        }
      });
    }

    exec.shutdown();
  }
}

and the output:

burhan@orion:/dev/shm$ javac ThreadIdTest.java && java ThreadIdTest
I am thread 8 of 5
I am thread 9 of 5
I am thread 10 of 5
I am thread 8 of 5
I am thread 9 of 5
I am thread 11 of 5
I am thread 8 of 5
I am thread 9 of 5
I am thread 10 of 5
I am thread 12 of 5

A slight tweak using modulo arithmetic will allow you to do "thread X of Y" correctly:

// modulo gives zero-based results hence the +1
long threadId = Thread.currentThread().getId()%numThreads +1;

New results:

burhan@orion:/dev/shm$ javac ThreadIdTest.java && java ThreadIdTest  
I am thread 2 of 5 
I am thread 3 of 5 
I am thread 3 of 5 
I am thread 3 of 5 
I am thread 5 of 5 
I am thread 1 of 5 
I am thread 4 of 5 
I am thread 1 of 5 
I am thread 2 of 5 
I am thread 3 of 5 

How to override trait function and call it from the overridden function?

An alternative approach if interested - with an extra intermediate class to use the normal OOO way. This simplifies the usage with parent::methodname

trait A {
    function calc($v) {
        return $v+1;
    }
}

// an intermediate class that just uses the trait
class IntClass {
    use A;
}

// an extended class from IntClass
class MyClass extends IntClass {
    function calc($v) {
        $v++;
        return parent::calc($v);
    }
}

return error message with actionResult

One approach would be to just use the ModelState:

ModelState.AddModelError("", "Error in cloud - GetPLUInfo" + ex.Message);

and then on the view do something like this:

@Html.ValidationSummary()

where you want the errors to display. If there are no errors, it won't display, but if there are you'll get a section that lists all the errors.

Binding to static property

Look at my project CalcBinding, which provides to you writing complex expressions in Path property value, including static properties, source properties, Math and other. So, you can write this:

<TextBox Text="{c:Binding local:VersionManager.FilterString}"/>

Goodluck!

Cause of a process being a deadlock victim

Although @Remus Rusanu's is already an excelent answer, in case one is looking forward a better insight on SQL Server's Deadlock causes and trace strategies, I would suggest you to read Brad McGehee's How to Track Down Deadlocks Using SQL Server 2005 Profiler

How to make HTML input tag only accept numerical values?

Please see my project of the cross-browser filter of value of the text input element on your web page using JavaScript language: Input Key Filter . You can filter the value as an integer number, a float number, or write a custom filter, such as a phone number filter. See an example of code of input an integer number:

_x000D_
_x000D_
<!doctype html>_x000D_
<html xmlns="http://www.w3.org/1999/xhtml" >_x000D_
<head>_x000D_
    <title>Input Key Filter Test</title>_x000D_
 <meta name="author" content="Andrej Hristoliubov [email protected]">_x000D_
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>_x000D_
 _x000D_
 <!-- For compatibility of IE browser with audio element in the beep() function._x000D_
 https://www.modern.ie/en-us/performance/how-to-use-x-ua-compatible -->_x000D_
 <meta http-equiv="X-UA-Compatible" content="IE=9"/>_x000D_
 _x000D_
 <link rel="stylesheet" href="https://rawgit.com/anhr/InputKeyFilter/master/InputKeyFilter.css" type="text/css">  _x000D_
 <script type="text/javascript" src="https://rawgit.com/anhr/InputKeyFilter/master/Common.js"></script>_x000D_
 <script type="text/javascript" src="https://rawgit.com/anhr/InputKeyFilter/master/InputKeyFilter.js"></script>_x000D_
 _x000D_
</head>_x000D_
<body>_x000D_
 <h1>Integer field</h1>_x000D_
<input id="Integer">_x000D_
<script>_x000D_
 CreateIntFilter("Integer", function(event){//onChange event_x000D_
   inputKeyFilter.RemoveMyTooltip();_x000D_
   var elementNewInteger = document.getElementById("NewInteger");_x000D_
   var integer = parseInt(this.value);_x000D_
   if(inputKeyFilter.isNaN(integer, this)){_x000D_
    elementNewInteger.innerHTML = "";_x000D_
    return;_x000D_
   }_x000D_
   //elementNewInteger.innerText = integer;//Uncompatible with FireFox_x000D_
   elementNewInteger.innerHTML = integer;_x000D_
  }_x000D_
  _x000D_
  //onblur event. Use this function if you want set focus to the input element again if input value is NaN. (empty or invalid)_x000D_
  , function(event){ inputKeyFilter.isNaN(parseInt(this.value), this); }_x000D_
 );_x000D_
</script>_x000D_
 New integer: <span id="NewInteger"></span>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Also see my page "Integer field:" of the example of the input key filter

Set the location in iPhone Simulator

Pre iOS 5 you could do it in code:

I use this snippet just before the @implementation of the class where I need my fake heading and location data.

#if (TARGET_IPHONE_SIMULATOR)
@interface MyHeading : CLHeading
    -(CLLocationDirection) magneticHeading;
    -(CLLocationDirection) trueHeading;
@end

@implementation MyHeading
    -(CLLocationDirection) magneticHeading { return 90; }
    -(CLLocationDirection) trueHeading { return 91; }
@end

@implementation CLLocationManager (TemporaryLocationFix)
- (void)locationFix {
    CLLocation *location = [[CLLocation alloc] initWithLatitude:55.932 longitude:12.321];
    [[self delegate] locationManager:self didUpdateToLocation:location fromLocation:nil];

    id heading  = [[MyHeading alloc] init];
    [[self delegate] locationManager:self didUpdateHeading: heading];
}

-(void)startUpdatingHeading {
    [self performSelector:@selector(locationFix) withObject:nil afterDelay:0.1];
}

- (void)startUpdatingLocation {
    [self performSelector:@selector(locationFix) withObject:nil afterDelay:0.1];
}
@end
#endif

After iOS 5 simply include a GPX file in your project like this to have the location updated continuously Hillerød.gpx:

<?xml version="1.0"?>
<gpx version="1.1" creator="Xcode"> 
    <wpt lat="55.93619760" lon="12.29131930"></wpt>
    <wpt lat="55.93625770" lon="12.29108330"></wpt>
    <wpt lat="55.93631780" lon="12.29078290"></wpt>
    <wpt lat="55.93642600" lon="12.29041810"></wpt>
    <wpt lat="55.93653420" lon="12.28998890"></wpt>
    <wpt lat="55.93660630" lon="12.28966710"></wpt>
    <wpt lat="55.93670240" lon="12.28936670"></wpt>
    <wpt lat="55.93677450" lon="12.28921650"></wpt>
    <wpt lat="55.93709900" lon="12.28945250"></wpt>
    <wpt lat="55.93747160" lon="12.28949540"></wpt>
    <wpt lat="55.93770000" lon="12.28966710"></wpt>
    <wpt lat="55.93785620" lon="12.28977440"></wpt>
    <wpt lat="55.93809660" lon="12.28988170"></wpt>
    <wpt lat="55.93832490" lon="12.28994600"></wpt>
    <wpt lat="55.93845710" lon="12.28996750"></wpt>
    <wpt lat="55.93856530" lon="12.29007480"></wpt>
    <wpt lat="55.93872150" lon="12.29013910"></wpt>
    <wpt lat="55.93886570" lon="12.28975290"></wpt>
    <wpt lat="55.93898590" lon="12.28955980"></wpt>
    <wpt lat="55.93910610" lon="12.28919500"></wpt>
    <wpt lat="55.93861330" lon="12.28883020"></wpt>
    <wpt lat="55.93845710" lon="12.28868000"></wpt>
    <wpt lat="55.93827680" lon="12.28850840"></wpt>
    <wpt lat="55.93809660" lon="12.28842250"></wpt>
    <wpt lat="55.93796440" lon="12.28831520"></wpt>
    <wpt lat="55.93780810" lon="12.28810070"></wpt>
    <wpt lat="55.93755570" lon="12.28790760"></wpt>
    <wpt lat="55.93739950" lon="12.28775730"></wpt>
    <wpt lat="55.93726730" lon="12.28767150"></wpt>
    <wpt lat="55.93707500" lon="12.28760710"></wpt>
    <wpt lat="55.93690670" lon="12.28734970"></wpt>
    <wpt lat="55.93675050" lon="12.28726380"></wpt>
    <wpt lat="55.93649810" lon="12.28713510"></wpt>
    <wpt lat="55.93625770" lon="12.28687760"></wpt>
    <wpt lat="55.93596930" lon="12.28679180"></wpt>
    <wpt lat="55.93587310" lon="12.28719940"></wpt>
    <wpt lat="55.93575290" lon="12.28752130"></wpt>
    <wpt lat="55.93564480" lon="12.28797190"></wpt>
    <wpt lat="55.93554860" lon="12.28833670"></wpt>
    <wpt lat="55.93550050" lon="12.28868000"></wpt>
    <wpt lat="55.93535630" lon="12.28900190"></wpt>
    <wpt lat="55.93515200" lon="12.28936670"></wpt>
    <wpt lat="55.93505580" lon="12.28958120"></wpt>
    <wpt lat="55.93481550" lon="12.29001040"></wpt>
    <wpt lat="55.93468320" lon="12.29033230"></wpt>
    <wpt lat="55.93452700" lon="12.29063270"></wpt>
    <wpt lat="55.93438280" lon="12.29095450"></wpt>
    <wpt lat="55.93425050" lon="12.29121200"></wpt>
    <wpt lat="55.93413040" lon="12.29140520"></wpt>
    <wpt lat="55.93401020" lon="12.29168410"></wpt>
    <wpt lat="55.93389000" lon="12.29189870"></wpt>
    <wpt lat="55.93372170" lon="12.29239220"></wpt>
    <wpt lat="55.93385390" lon="12.29258530"></wpt>
    <wpt lat="55.93409430" lon="12.29295010"></wpt>
    <wpt lat="55.93421450" lon="12.29320760"></wpt>
    <wpt lat="55.93433470" lon="12.29333630"></wpt>
    <wpt lat="55.93445490" lon="12.29350800"></wpt>
    <wpt lat="55.93463520" lon="12.29374400"></wpt>
    <wpt lat="55.93479140" lon="12.29410880"></wpt>
    <wpt lat="55.93491160" lon="12.29419460"></wpt>
    <wpt lat="55.93515200" lon="12.29458090"></wpt>
    <wpt lat="55.93545250" lon="12.29494570"></wpt>
    <wpt lat="55.93571690" lon="12.29505300"></wpt>
    <wpt lat="55.93593320" lon="12.29513880"></wpt>
    <wpt lat="55.93617360" lon="12.29522460"></wpt>
    <wpt lat="55.93622170" lon="12.29537480"></wpt>
    <wpt lat="55.93713510" lon="12.29505300"></wpt>
    <wpt lat="55.93776000" lon="12.29378700"></wpt>
    <wpt lat="55.93904600" lon="12.29531040"></wpt>
    <wpt lat="55.94004350" lon="12.29552500"></wpt>
    <wpt lat="55.94023570" lon="12.29561090"></wpt>
    <wpt lat="55.94019970" lon="12.29591130"></wpt>
    <wpt lat="55.94017560" lon="12.29629750"></wpt>
    <wpt lat="55.94017560" lon="12.29670520"></wpt>
    <wpt lat="55.94017560" lon="12.29713430"></wpt>
    <wpt lat="55.94019970" lon="12.29754200"></wpt>
    <wpt lat="55.94024780" lon="12.29816430"></wpt>
    <wpt lat="55.94051210" lon="12.29842180"></wpt>
    <wpt lat="55.94084860" lon="12.29820720"></wpt>
    <wpt lat="55.94105290" lon="12.29799270"></wpt>
    <wpt lat="55.94123320" lon="12.29777810"></wpt>
    <wpt lat="55.94140140" lon="12.29749910"></wpt>
    <wpt lat="55.94142550" lon="12.29726310"></wpt>
    <wpt lat="55.94147350" lon="12.29687690"></wpt>
    <wpt lat="55.94155760" lon="12.29619020"></wpt>
    <wpt lat="55.94161770" lon="12.29576110"></wpt>
    <wpt lat="55.94148550" lon="12.29531040"></wpt>
    <wpt lat="55.94093270" lon="12.29522460"></wpt>
    <wpt lat="55.94041600" lon="12.29518170"></wpt>
    <wpt lat="55.94056020" lon="12.29398010"></wpt>
    <wpt lat="55.94024780" lon="12.29352950"></wpt>
    <wpt lat="55.94001940" lon="12.29335780"></wpt>
    <wpt lat="55.93992330" lon="12.29325050"></wpt>
    <wpt lat="55.93969490" lon="12.29299300"></wpt>
    <wpt lat="55.93952670" lon="12.29277840"></wpt>
    <wpt lat="55.93928630" lon="12.29260680"></wpt>
    <wpt lat="55.93915410" lon="12.29232780"></wpt>
    <wpt lat="55.93928630" lon="12.29202740"></wpt>
    <wpt lat="55.93933440" lon="12.29174850"></wpt>
    <wpt lat="55.93947860" lon="12.29116910"></wpt>
    <wpt lat="55.93965890" lon="12.29095450"></wpt>
    <wpt lat="55.94001940" lon="12.29061120"></wpt>
    <wpt lat="55.94041600" lon="12.29084730"></wpt>
    <wpt lat="55.94076450" lon="12.29101890"></wpt>
    <wpt lat="55.94080060" lon="12.29065410"></wpt>
    <wpt lat="55.94086060" lon="12.29031080"></wpt>
    <wpt lat="55.94092070" lon="12.28990310"></wpt>
    <wpt lat="55.94099280" lon="12.28975290"></wpt>
    <wpt lat="55.94119710" lon="12.28986020"></wpt>
    <wpt lat="55.94134130" lon="12.28998890"></wpt>
    <wpt lat="55.94147350" lon="12.29007480"></wpt>
    <wpt lat="55.94166580" lon="12.29003190"></wpt>
    <wpt lat="55.94176190" lon="12.28938810"></wpt>
    <wpt lat="55.94183400" lon="12.28893750"></wpt>
    <wpt lat="55.94194220" lon="12.28850840"></wpt>
    <wpt lat="55.94199030" lon="12.28835820"></wpt>
    <wpt lat="55.94215850" lon="12.28859420"></wpt>
    <wpt lat="55.94250700" lon="12.28883020"></wpt>
    <wpt lat="55.94267520" lon="12.28893750"></wpt>
    <wpt lat="55.94284350" lon="12.28902330"></wpt>
    <wpt lat="55.94304770" lon="12.28915210"></wpt>
    <wpt lat="55.94325200" lon="12.28925940"></wpt>
    <wpt lat="55.94348030" lon="12.28953830"></wpt>
    <wpt lat="55.94366060" lon="12.28966710"></wpt>
    <wpt lat="55.94388890" lon="12.28975290"></wpt>
    <wpt lat="55.94399700" lon="12.28994600"></wpt>
    <wpt lat="55.94379280" lon="12.29065410"></wpt>
    <wpt lat="55.94364860" lon="12.29095450"></wpt>
    <wpt lat="55.94350440" lon="12.29127640"></wpt>
    <wpt lat="55.94340820" lon="12.29155540"></wpt>
    <wpt lat="55.94331210" lon="12.29198450"></wpt>
    <wpt lat="55.94315590" lon="12.29269260"></wpt>
    <wpt lat="55.94310780" lon="12.29318610"></wpt>
    <wpt lat="55.94301170" lon="12.29361530"></wpt>
    <wpt lat="55.94292760" lon="12.29408740"></wpt>
    <wpt lat="55.94290350" lon="12.29436630"></wpt>
    <wpt lat="55.94287950" lon="12.29453800"></wpt>
    <wpt lat="55.94283140" lon="12.29533190"></wpt>
    <wpt lat="55.94274730" lon="12.29606150"></wpt>
    <wpt lat="55.94278340" lon="12.29621170"></wpt>
    <wpt lat="55.94280740" lon="12.29649060"></wpt>
    <wpt lat="55.94284350" lon="12.29679100"></wpt>
    <wpt lat="55.94284350" lon="12.29734890"></wpt>
    <wpt lat="55.94308380" lon="12.29837890"></wpt>
    <wpt lat="55.94315590" lon="12.29852910"></wpt>
    <wpt lat="55.94263920" lon="12.29906550"></wpt>
    <wpt lat="55.94237480" lon="12.29910850"></wpt>
    <wpt lat="55.94220660" lon="12.29915140"></wpt>
    <wpt lat="55.94208640" lon="12.29902260"></wpt>
    <wpt lat="55.94196620" lon="12.29887240"></wpt>
    <wpt lat="55.94176190" lon="12.29794970"></wpt>
    <wpt lat="55.94156970" lon="12.29760640"></wpt>
</gpx>

I use GPSies.com to create the base file for the gpx data. A bit of cleanup is required though.

Activate by running the simulator and choosing your file


(source: castleandersen.dk)

Android ListView in fragment example

Your Fragment can subclass ListFragment.
And onCreateView() from ListFragment will return a ListView you can then populate.

Why is my locally-created script not allowed to run under the RemoteSigned execution policy?

This is an IDE issue. Change the setting in the PowerShell GUI. Go to the Tools tab and select Options, and then Debugging options. Then check the box Turn off requirement for scripts to be signed. Done.

How can I enable auto complete support in Notepad++?

Autocomplete in Notepad++ is as simple as hitting Ctrl + Enter or Ctrl + Space in the interface.

Ctrl + Enter - as simple as that!

This, for many people, will be better than autocompleting on everything.

Frequency table for a single variable

The answer provided by @DSM is simple and straightforward, but I thought I'd add my own input to this question. If you look at the code for pandas.value_counts, you'll see that there is a lot going on.

If you need to calculate the frequency of many series, this could take a while. A faster implementation would be to use numpy.unique with return_counts = True

Here is an example:

import pandas as pd
import numpy as np

my_series = pd.Series([1,2,2,3,3,3])

print(my_series.value_counts())
3    3
2    2
1    1
dtype: int64

Notice here that the item returned is a pandas.Series

In comparison, numpy.unique returns a tuple with two items, the unique values and the counts.

vals, counts = np.unique(my_series, return_counts=True)
print(vals, counts)
[1 2 3] [1 2 3]

You can then combine these into a dictionary:

results = dict(zip(vals, counts))
print(results)
{1: 1, 2: 2, 3: 3}

And then into a pandas.Series

print(pd.Series(results))
1    1
2    2
3    3
dtype: int64

Android Transparent TextView?

To set programmatically:

setBackgroundColor(Color.TRANSPARENT);

For me, I also had to set it to Color.TRANSPARENT on the parent layout.

How to modify memory contents using GDB?

The easiest is setting a program variable (see GDB: assignment):

(gdb) l
6       {
7           int i;
8           struct file *f, *ftmp;
9
(gdb) set variable i = 10
(gdb) p i
$1 = 10

Or you can just update arbitrary (writable) location by address:

(gdb) set {int}0x83040 = 4

There's more. Read the manual.

Java and SQLite

sqlitejdbc code can be downloaded using git from https://github.com/crawshaw/sqlitejdbc.

# git clone https://github.com/crawshaw/sqlitejdbc.git sqlitejdbc
...
# cd sqlitejdbc
# make

Note: Makefile requires curl binary to download sqlite libraries/deps.

Alter table to modify default value of column

Your belief about what will happen is not correct. Setting a default value for a column will not affect the existing data in the table.

I create a table with a column col2 that has no default value

SQL> create table foo(
  2    col1 number primary key,
  3    col2 varchar2(10)
  4  );

Table created.

SQL> insert into foo( col1 ) values (1);

1 row created.

SQL> insert into foo( col1 ) values (2);

1 row created.

SQL> insert into foo( col1 ) values (3);

1 row created.

SQL> select * from foo;

      COL1 COL2
---------- ----------
         1
         2
         3

If I then alter the table to set a default value, nothing about the existing rows will change

SQL> alter table foo
  2    modify( col2 varchar2(10) default 'foo' );

Table altered.

SQL> select * from foo;

      COL1 COL2
---------- ----------
         1
         2
         3

SQL> insert into foo( col1 ) values (4);

1 row created.

SQL> select * from foo;

      COL1 COL2
---------- ----------
         1
         2
         3
         4 foo

Even if I subsequently change the default again, there will still be no change to the existing rows

SQL> alter table foo
  2    modify( col2 varchar2(10) default 'bar' );

Table altered.

SQL> select * from foo;

      COL1 COL2
---------- ----------
         1
         2
         3
         4 foo

SQL> insert into foo( col1 ) values (5);

1 row created.

SQL> select * from foo;

      COL1 COL2
---------- ----------
         1
         2
         3
         4 foo
         5 bar

Windows Explorer "Command Prompt Here"

Use the following in command prompt to open your current location in windows explorer:

C:\your-directory> explorer .

How do I create a URL shortener?

Implementation in Scala:

class Encoder(alphabet: String) extends (Long => String) {

  val Base = alphabet.size

  override def apply(number: Long) = {
    def encode(current: Long): List[Int] = {
      if (current == 0) Nil
      else (current % Base).toInt :: encode(current / Base)
    }
    encode(number).reverse
      .map(current => alphabet.charAt(current)).mkString
  }
}

class Decoder(alphabet: String) extends (String => Long) {

  val Base = alphabet.size

  override def apply(string: String) = {
    def decode(current: Long, encodedPart: String): Long = {
      if (encodedPart.size == 0) current
      else decode(current * Base + alphabet.indexOf(encodedPart.head),encodedPart.tail)
    }
    decode(0,string)
  }
}

Test example with Scala test:

import org.scalatest.{FlatSpec, Matchers}

class DecoderAndEncoderTest extends FlatSpec with Matchers {

  val Alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"

  "A number with base 10" should "be correctly encoded into base 62 string" in {
    val encoder = new Encoder(Alphabet)
    encoder(127) should be ("cd")
    encoder(543513414) should be ("KWGPy")
  }

  "A base 62 string" should "be correctly decoded into a number with base 10" in {
    val decoder = new Decoder(Alphabet)
    decoder("cd") should be (127)
    decoder("KWGPy") should be (543513414)
  }

}

How to convert Windows end of line in Unix end of line (CR/LF to LF)

Go back to Windows, tell Eclipse to change the encoding to UTF-8, then back to Unix and run d2u on the files.

How to tell bash that the line continues on the next line

The character is a backslash \

From the bash manual:

The backslash character ‘\’ may be used to remove any special meaning for the next character read and for line continuation.

Creating an object: with or without `new`

Both do different things.

The first creates an object with automatic storage duration. It is created, used, and then goes out of scope when the current block ({ ... }) ends. It's the simplest way to create an object, and is just the same as when you write int x = 0;

The second creates an object with dynamic storage duration and allows two things:

  • Fine control over the lifetime of the object, since it does not go out of scope automatically; you must destroy it explicitly using the keyword delete;

  • Creating arrays with a size known only at runtime, since the object creation occurs at runtime. (I won't go into the specifics of allocating dynamic arrays here.)

Neither is preferred; it depends on what you're doing as to which is most appropriate.

Use the former unless you need to use the latter.

Your C++ book should cover this pretty well. If you don't have one, go no further until you have bought and read, several times, one of these.

Good luck.


Your original code is broken, as it deletes a char array that it did not new. In fact, nothing newd the C-style string; it came from a string literal. deleteing that is an error (albeit one that will not generate a compilation error, but instead unpredictable behaviour at runtime).

Usually an object should not have the responsibility of deleteing anything that it didn't itself new. This behaviour should be well-documented. In this case, the rule is being completely broken.

Adding 30 minutes to time formatted as H:i in PHP

Your current solution does not work because $time is a string - it needs to be a Unix timestamp. You can do this instead:

$unix_time = strtotime('January 1 2010 '.$time); // create a unix timestamp
$startTime date( "H:i", strtotime('-30 minutes', $unix_time) );
$endTime date( "H:i", strtotime('+30 minutes', $unix_time) );

What is the most efficient way to store tags in a database?

Actually I believe de-normalising the tags table might be a better way forward, depending on scale.

This way, the tags table simply has tagid, itemid, tagname.

You'll get duplicate tagnames, but it makes adding/removing/editing tags for specific items MUCH more simple. You don't have to create a new tag, remove the allocation of the old one and re-allocate a new one, you just edit the tagname.

For displaying a list of tags, you simply use DISTINCT or GROUP BY, and of course you can count how many times a tag is used easily, too.

Python NameError: name is not defined

Note that sometimes you will want to use the class type name inside its own definition, for example when using Python Typing module, e.g.

class Tree:
    def __init__(self, left: Tree, right: Tree):
        self.left = left
        self.right = right

This will also result in

NameError: name 'Tree' is not defined

That's because the class has not been defined yet at this point. The workaround is using so called Forward Reference, i.e. wrapping a class name in a string, i.e.

class Tree:
    def __init__(self, left: 'Tree', right: 'Tree'):
        self.left = left
        self.right = right

Git Pull vs Git Rebase

In a nutshell :

-> Git Merge: It will simply merge your local changes and remote changes, and that will create another commit history record

-> Git Rebase: It will put your changes above all new remote changes, and rewrite commit history, so your commit history will be much cleaner than git merge. Rebase is a destructive operation. That means, if you do not apply it correctly, you could lose committed work and/or break the consistency of other developer's repositories.

Compare dates with javascript

if( (new Date(first).getTime() > new Date(second).getTime()))
{
    ----------------------------------
}

:last-child not working as expected?

I encounter similar situation. I would like to have background of the last .item to be yellow in the elements that look like...

<div class="container">
  <div class="item">item 1</div>
  <div class="item">item 2</div>
  <div class="item">item 3</div>
  ...
  <div class="item">item x</div>
  <div class="other">I'm here for some reasons</div>
</div>

I use nth-last-child(2) to achieve it.

.item:nth-last-child(2) {
  background-color: yellow;
}

It strange to me because nth-last-child of item suppose to be the second of the last item but it works and I got the result as I expect. I found this helpful trick from CSS Trick

What is secret key for JWT based authentication and how to generate it?

The algorithm (HS256) used to sign the JWT means that the secret is a symmetric key that is known by both the sender and the receiver. It is negotiated and distributed out of band. Hence, if you're the intended recipient of the token, the sender should have provided you with the secret out of band.

If you're the sender, you can use an arbitrary string of bytes as the secret, it can be generated or purposely chosen. You have to make sure that you provide the secret to the intended recipient out of band.

For the record, the 3 elements in the JWT are not base64-encoded but base64url-encoded, which is a variant of base64 encoding that results in a URL-safe value.

jquery/javascript convert date string to date

If you're running with jQuery you can use the datepicker UI library's parseDate function to convert your string to a date:

var d = $.datepicker.parseDate("DD, MM dd, yy",  "Sunday, February 28, 2010");

and then follow it up with the formatDate method to get it to the string format you want

var datestrInNewFormat = $.datepicker.formatDate( "mm/dd/yy", d);

If you're not running with jQuery of course its probably not the best plan given you'd need jQuery core as well as the datepicker UI module... best to go with the suggestion from Segfault above to use date.js.

HTH

Is there an online application that automatically draws tree structures for phrases/sentences?

There are lots of options out there. Many of which are available as downloadable software as well as public websites. I do not think many of them expect to be used as API's unless they explicitly state that.

The one that I found effective was Enju which did not have the character limit that the Marc's Carnagie Mellon link had. Marc also mentioned a VISL scanner in comments, but that requires java in the browser, which is a non-starter for me.

Note that recently, Google has offered a new NLP Machine Learning API that providers amoung other features, a automatic sentence parser. I will likely not update this answer again, especially since the question is closed, but I suspect that the other big ML cloud stacks will soon support the same.

See full command of running/stopped container in Docker

TL-DR

docker ps --no-trunc and docker inspect CONTAINER provide the entrypoint executed to start the container, along the command passed to, but that may miss some parts such as ${ANY_VAR} because container environment variables are not printed as resolved.

To overcome that, docker inspect CONTAINER has an advantage because it also allow to retrieve separately env variables and their values defined in the container from the Config.Env property.

docker ps and docker inspect provide information about the executed entrypoint and its command. Often, that is a wrapper entrypoint script (.sh) and not the "real" program started by the container. To get information on that, requesting process information with ps or /proc/1/cmdline help.


1) docker ps --no-trunc

It prints the entrypoint and the command executed for all running containers. While it prints the command passed to the entrypoint (if we pass that), it doesn't show value of docker env variables (such as $FOO or ${FOO}).
If our containers use env variables, it may be not enough.

For example, run an alpine container :

docker run --name alpine-example -e MY_VAR=/var alpine:latest sh -c 'ls $MY_VAR'

When use docker -ps such as :

docker ps -a --filter name=alpine-example --no-trunc

It prints :

CONTAINER ID           IMAGE               COMMAND                CREATED             STATUS                     PORTS               NAMES
5b064a6de6d8417...   alpine:latest       "sh -c 'ls $MY_VAR'"   2 minutes ago       Exited (0) 2 minutes ago                       alpine-example

We see the command passed to the entrypoint : sh -c 'ls $MY_VAR' but $MY_VAR is indeed not resolved.

2) docker inspect CONTAINER

When we inspect the alpine-example container :

docker inspect alpine-example | grep -4 Cmd

The command is also there but we don't still see the env variable value :

        "Cmd": [
            "sh",
            "-c",
            "ls $MY_VAR"
        ],

In fact, we could not see interpolated variables with these docker commands.
While as a trade-off, we could display separately both command and env variables for a container with docker inspect :

docker inspect  alpine-example  | grep -4 -E "Cmd|Env"

That prints :

        "Env": [
            "MY_VAR=/var",
            "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
        ],
        "Cmd": [
            "sh",
            "-c",
            "ls $MY_VAR"
        ]

A more docker way would be to use the --format flag of docker inspect that allows to specify JSON attributes to render :

docker inspect --format '{{.Name}} {{.Config.Cmd}}  {{ (.Config.Env) }}'  alpine-example

That outputs :

/alpine-example [sh -c ls $MY_VAR]  [MY_VAR=/var PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin]

3) Retrieve the started process from the container itself for running containers

The entrypoint and command executed by docker may be helpful but in some cases, it is not enough because that is "only" a wrapper entrypoint script (.sh) that is responsible to start the real/core process.
For example when I run a Nexus container, the command executed and shown to run the container is "sh -c ${SONATYPE_DIR}/start-nexus-repository-manager.sh".
For PostgreSQL that is "docker-entrypoint.sh postgres".

To get more information, we could execute on a running container docker exec CONTAINER ps aux.
It may print other processes that may not interest us.
To narrow to the initial process launched by the entrypoint, we could do :

docker exec CONTAINER ps -1

I specify 1 because the process executed by the entrypoint is generally the one with the 1 id.

Without ps, we could still find the information in /proc/1/cmdline (in most of Linux distros but not all). For example :

docker exec CONTAINER cat /proc/1/cmdline | sed -e "s/\x00/ /g"; echo    

If we have access to the docker host that started the container, another alternative to get the full command of the process executed by the entrypoint is : : execute ps -PID where PID is the local process created by the Docker daemon to run the container such as :

ps -$(docker container inspect --format '{{.State.Pid}}'  CONTAINER)

User-friendly formatting with docker ps

docker ps --no-trunc is not always easy to read.
Specifying columns to print and in a tabular format may make it better :

docker ps   --no-trunc  --format "table{{.Names}}\t{{.CreatedAt}}\t{{.Command}}"

Create an alias may help :

alias dps='docker ps   --no-trunc  --format "table{{.Names}}\t{{.CreatedAt}}\t{{.Command}}"'

How can I generate an HTML report for Junit results?

I found the above answers quite useful but not really general purpose, they all need some other major build system like Ant or Maven.

I wanted to generate a report in a simple one-shot command that I could call from anything (from a build, test or just myself) so I have created junit2html which can be found here: https://github.com/inorton/junit2html

You can install it by doing:

pip install junit2html

What does if [ $? -eq 0 ] mean for shell scripts?

It is an extremely overused way to check for the success/failure of a command. Typically, the code snippet you give would be refactored as:

if grep -e ERROR ${LOG_DIR_PATH}/${LOG_NAME} > /dev/null; then
   ...
fi

(Although you can use 'grep -q' in some instances instead of redirecting to /dev/null, doing so is not portable. Many implementations of grep do not support the -q option, so your script may fail if you use it.)

How can I exclude directories from grep -R?

Frequently use this:

grep can be used in conjunction with -r (recursive), i (ignore case) and -o (prints only matching part of lines). To exclude files use --exclude and to exclude directories use --exclude-dir.

Putting it together you end up with something like:

grep -rio --exclude={filenames comma separated} \
--exclude-dir={directory names comma separated} <search term> <location>

Describing it makes it sound far more complicated than it actually is. Easier to illustrate with a simple example.

Example:

Suppose I am searching for current project for all places where I explicitly set the string value debugger during a debugging session, and now wish to review / remove.

I write a script called findDebugger.sh and use grep to find all occurrences. However:

For file exclusions - I wish to ensure that .eslintrc is ignored (this actually has a linting rule about debugger so should be excluded). Likewise, I don't want my own script to be referenced in any results.

For directory exclusions - I wish to exclude node_modules as it contains lots of libraries that do reference debugger and I am not interested in those results. Also I just wish to omit .idea and .git hidden directories because I don't care about those search locations either, and wish to keep the search performant.

So here is the result - I create a script called findDebugger.sh with:

#!/usr/bin/env bash
grep -rio --exclude={.eslintrc,findDebugger.sh} \
--exclude-dir={node_modules,.idea,.git} debugger .

Laravel Query Builder where max id

No need to use sub query, just Try this,Its working fine:

  DB::table('orders')->orderBy('id', 'desc')->first();

Swift error : signal SIGABRT how to solve it

In my case, I was using RxSwift for performing search.

I had extensively kept using a shared instance of a particular class inside the onNext method, which probably made it inaccessible (Mutex).

Make sure that such instances are handled carefully only when absolutely necessary.

In my case, I made use of a couple of variables beforehand to safely (and sequentially) store the return values of the shared instance's methods, and reused them inside onNext block.

How to determine the current iPhone/device model?

Simplest way to get model name (marketing name)

Use private API -[UIDevice _deviceInfoForKey:] carefully, you won't be rejected by Apple,

// works on both simulators and real devices, iOS 8 to iOS 12
NSString *deviceModelName(void) {
    // For Simulator
    NSString *modelName = NSProcessInfo.processInfo.environment[@"SIMULATOR_DEVICE_NAME"];
    if (modelName.length > 0) {
        return modelName;
    }

    // For real devices and simulators, except simulators running on iOS 8.x
    UIDevice *device = [UIDevice currentDevice];
    NSString *selName = [NSString stringWithFormat:@"_%@ForKey:", @"deviceInfo"];
    SEL selector = NSSelectorFromString(selName);
    if ([device respondsToSelector:selector]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
        modelName = [device performSelector:selector withObject:@"marketing-name"];
#pragma clang diagnostic pop
    }
    return modelName;
}

How did I get the key "marketing-name"?

Running on a simulator, NSProcessInfo.processInfo.environment contains a key named "SIMULATOR_CAPABILITIES", the value of which is a plist file. Then you open the plist file, you will get the model name's key "marketing-name".

What is the best way to check for Internet connectivity using .NET?

public static bool HasConnection()
{
    try
    {
        System.Net.IPHostEntry i = System.Net.Dns.GetHostEntry("www.google.com");
        return true;
    }
    catch
    {
        return false;
    }
}

That works

How to add a button programmatically in VBA next to some sheet cell data?

Suppose your function enters data in columns A and B and you want to a custom Userform to appear if the user selects a cell in column C. One way to do this is to use the SelectionChange event:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim clickRng As Range
    Dim lastRow As Long

    lastRow = Range("A1").End(xlDown).Row
    Set clickRng = Range("C1:C" & lastRow) //Dynamically set cells that can be clicked based on data in column A

    If Not Intersect(Target, clickRng) Is Nothing Then
        MyUserForm.Show //Launch custom userform
    End If

End Sub

Note that the userform will appear when a user selects any cell in Column C and you might want to populate each cell in Column C with something like "select cell to launch form" to make it obvious that the user needs to perform an action (having a button naturally suggests that it should be clicked)

Spring MVC How take the parameter value of a GET HTTP Request in my controller method?

You could also use a URI template. If you structured your request into a restful URL Spring could parse the provided value from the url.

HTML

<li>
    <a id="byParameter" 
       class="textLink" href="<c:url value="/mapping/parameter/bar />">By path, method,and
           presence of parameter</a>
</li>

Controller

@RequestMapping(value="/mapping/parameter/{foo}", method=RequestMethod.GET)
public @ResponseBody String byParameter(@PathVariable String foo) {
    //Perform logic with foo
    return "Mapped by path + method + presence of query parameter! (MappingController)";
}

Spring URI Template Documentation

Disable/turn off inherited CSS3 transitions

If you want to disable a single transition property, you can do:

transition: color 0s;

(since a zero second transition is the same as no transition.)

Create a Dropdown List for MVC3 using Entity Framework (.edmx Model) & Razor Views && Insert A Database Record to Multiple Tables

Well, actually I'll have to say David is right with his solution, but there are some topics disturbing me:

  1. You should never send your model to the view => This is correct
  2. If you create a ViewModel, and include the Model as member in the ViewModel, then you effectively sent your model to the View => this is BAD
  3. Using dictionaries to send the options to the view => this not good style

So how can you create a better coupling?

I would use a tool like AutoMapper or ValueInjecter to map between ViewModel and Model. AutoMapper does seem to have the better syntax and feel to it, but the current version lacks a very severe topic: It is not able to perform the mapping from ViewModel to Model (under certain circumstances like flattening, etc., but this is off topic) So at present I prefer to use ValueInjecter.

So you create a ViewModel with the fields you need in the view. You add the SelectList items you need as lookups. And you add them as SelectLists already. So you can query from a LINQ enabled sourc, select the ID and text field and store it as a selectlist: You gain that you do not have to create a new type (dictionary) as lookup and you just move the new SelectList from the view to the controller.

  // StaffTypes is an IEnumerable<StaffType> from dbContext
  // viewModel is the viewModel initialized to copy content of Model Employee  
  // viewModel.StaffTypes is of type SelectList

  viewModel.StaffTypes =
    new SelectList(
        StaffTypes.OrderBy( item => item.Name )
        "StaffTypeID",
        "Type",
        viewModel.StaffTypeID
    );

In the view you just have to call

@Html.DropDownListFor( model => mode.StaffTypeID, model.StaffTypes )

Back in the post element of your method in the controller you have to take a parameter of the type of your ViewModel. You then check for validation. If the validation fails, you have to remember to re-populate the viewModel.StaffTypes SelectList, because this item will be null on entering the post function. So I tend to have those population things separated into a function. You just call back return new View(viewModel) if anything is wrong. Validation errors found by MVC3 will automatically be shown in the view.

If you have your own validation code you can add validation errors by specifying which field they belong to. Check documentation on ModelState to get info on that.

If the viewModel is valid you have to perform the next step:

If it is a create of a new item, you have to populate a model from the viewModel (best suited is ValueInjecter). Then you can add it to the EF collection of that type and commit changes.

If you have an update, you get the current db item first into a model. Then you can copy the values from the viewModel back to the model (again using ValueInjecter gets you do that very quick). After that you can SaveChanges and are done.

Feel free to ask if anything is unclear.

Is there a function to make a copy of a PHP array to another?

In PHP arrays are assigned by copy, while objects are assigned by reference. This means that:

$a = array();
$b = $a;
$b['foo'] = 42;
var_dump($a);

Will yield:

array(0) {
}

Whereas:

$a = new StdClass();
$b = $a;
$b->foo = 42;
var_dump($a);

Yields:

object(stdClass)#1 (1) {
  ["foo"]=>
  int(42)
}

You could get confused by intricacies such as ArrayObject, which is an object that acts exactly like an array. Being an object however, it has reference semantics.

Edit: @AndrewLarsson raises a point in the comments below. PHP has a special feature called "references". They are somewhat similar to pointers in languages like C/C++, but not quite the same. If your array contains references, then while the array itself is passed by copy, the references will still resolve to the original target. That's of course usually the desired behaviour, but I thought it was worth mentioning.

Running Command Line in Java

To avoid the called process to be blocked if it outputs a lot of data on the standard output and/or error, you have to use the solution provided by Craigo. Note also that ProcessBuilder is better than Runtime.getRuntime().exec(). This is for a couple of reasons: it tokenizes better the arguments, and it also takes care of the error standard output (check also here).

ProcessBuilder builder = new ProcessBuilder("cmd", "arg1", ...);
builder.redirectErrorStream(true);
final Process process = builder.start();

// Watch the process
watch(process);

I use a new function "watch" to gather this data in a new thread. This thread will finish in the calling process when the called process ends.

private static void watch(final Process process) {
    new Thread() {
        public void run() {
            BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = null; 
            try {
                while ((line = input.readLine()) != null) {
                    System.out.println(line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }.start();
}

How to ping an IP address

I think this code will help you:

public class PingExample {
    public static void main(String[] args){
        try{
            InetAddress address = InetAddress.getByName("192.168.1.103");
            boolean reachable = address.isReachable(10000);

            System.out.println("Is host reachable? " + reachable);
        } catch (Exception e){
            e.printStackTrace();
        }
    }
}

receiver type *** for instance message is a forward declaration

FWIW, I got this error when I was implementing core data in to an existing project. It turned out I forgot to link CoreData.h to my project. I had already added the CoreData framework to my project but solved the issue by linking to the framework in my pre-compiled header just like Apple's templates do:

#import <Availability.h>

#ifndef __IPHONE_5_0
#warning "This project uses features only available in iOS SDK 5.0 and later."
#endif

#ifdef __OBJC__
    #import <UIKit/UIKit.h>
    #import <Foundation/Foundation.h>
    #import <CoreData/CoreData.h>
#endif

What are the advantages of Sublime Text over Notepad++ and vice-versa?

Main advantage for me is that Sublime Text 2 is almost the same, and has the same features on Windows, Linux and OS X. Can you claim that about Notepad++? It makes me move from one OS to another seamlessly.

Then there is speed. Sublime Text 2, which people claim is buggy and unstable ( 3 is more stable ), is still amazingly fast. If you use it, you will realize how fast it is.

Sublime Text 2 has some neat features like multi cursor input, multiple selections etc that will make you immensely productive.

Good number of plugins and themes, and also support for those of Textmate means you can do anything with Sublime Text 2. I have moved from Notepad++ to Sublime Text 2 on Windows and haven't looked back. The real question for me has been - Sublime Text 2 or vim?

What's good on Notepad++ side - it loads much faster on Windows for me. Maybe it will be good enough for you for quick editing. But, again, Sublime Text 3 is supposed to be faster on this front too. Sublime text 2 is not really good when it comes to handling huge files, and I had found that Notepad++ was pretty good till certain size of files. And, of course, Notepad++ is free. Sublime Text 2 has unlimited trial.

The easiest way to replace white spaces with (underscores) _ in bash

You can do it using only the shell, no need for tr or sed

$ str="This is just a test"
$ echo ${str// /_}
This_is_just_a_test

How to get the week day name from a date?

SQL> SELECT TO_CHAR(date '1982-03-09', 'DAY') day FROM dual;

DAY
---------
TUESDAY

SQL> SELECT TO_CHAR(date '1982-03-09', 'DY') day FROM dual;

DAY
---
TUE

SQL> SELECT TO_CHAR(date '1982-03-09', 'Dy') day FROM dual;

DAY
---
Tue

(Note that the queries use ANSI date literals, which follow the ISO-8601 date standard and avoid date format ambiguity.)

.NET Core vs Mono

This is no more .NET Core vs. Mono. It's unified.

Update as of November 2020 - .NET 5 released that unifies .NET Framework and .NET Core

.NET and Mono will be unified under .NET 6 that would be released in November 2021

  • .NET 6.0 will add net6.0-ios and net6.0-android.
  • The OS-specific names can include OS version numbers, like net6.0-ios14.

Check below articles:

Is it better to use NOT or <> when comparing values?

The second example would be the one to go with, not just for readability, but because of the fact that in the first example, If NOT value1 would return a boolean value to be compared against value2. IOW, you need to rewrite that example as

If NOT (value1 = value2)

which just makes the use of the NOT keyword pointless.

How do I trim whitespace from a string?

I wanted to remove the too-much spaces in a string (also in between the string, not only in the beginning or end). I made this, because I don't know how to do it otherwise:

string = "Name : David         Account: 1234             Another thing: something  " 

ready = False
while ready == False:
    pos = string.find("  ")
    if pos != -1:
       string = string.replace("  "," ")
    else:
       ready = True
print(string)

This replaces double spaces in one space until you have no double spaces any more

Link a photo with the cell in excel

There is a much simpler way. Put your picture in a comment box within the description cell. That way you only have one column and when you sort the picture will always stay with the description. Okay... Right click the cell containing the description... Insert comment...right click the outer border... Format comment...colours and lines tab... Colour drop down...Fill effects...Picture tab...select picture...browse for your picture (it might be best to keep all pictures in one folder for ease of placement)...ok... you will probably need to go to the size tab and frig around with the height and width. Done... You now only need to mouse over the red in the top right corner of the cell and the picture will appear...like magic.

This method means that the row height can be kept to a minimum and the pictures can be as big as you like.

React this.setState is not a function

Now ES6 have arrow function it really helpful if you really confuse with bind(this) expression you can try arrow function

This is how I do.

componentWillMount() {
        ListApi.getList()
            .then(JsonList => this.setState({ List: JsonList }));
    }

 //Above method equalent to this...
     componentWillMount() {
         ListApi.getList()
             .then(function (JsonList) {
                 this.setState({ List: JsonList });
             }.bind(this));
 }

how to make a full screen div, and prevent size to be changed by content?

<html>
<div style="width:100%; height:100%; position:fixed; left:0;top:0;overflow:hidden;">

</div>
</html>

How to change node.js's console font color?

Emoji

You can use colors for text as others mentioned in their answers.

But you can use emojis instead! for example, you can use?? for warning messages and for error messages.

Or simply use these notebooks as a color:

: error message
: warning message
: ok status message
: action message
: canceled status message
: Or anything you like and want to recognize immediately by color

Bonus:

This method also helps you to quickly scan and find logs directly in the source code.

But Linux default emoji font is not colorful by default and you may want to make them colorful, first.

Get Wordpress Category from Single Post

<div class="post_category">
        <?php $category = get_the_category();
             $allcategory = get_the_category(); 
        foreach ($allcategory as $category) {
        ?>
           <a class="btn"><?php echo $category->cat_name;; ?></a>
        <?php 
        }
        ?>
 </div>

How to trim a string to N chars in Javascript?

Why not just use substring... string.substring(0, 7); The first argument (0) is the starting point. The second argument (7) is the ending point (exclusive). More info here.

var string = "this is a string";
var length = 7;
var trimmedString = string.substring(0, length);

Show Error on the tip of the Edit Text Android

Using Kotlin Language,

EXAMPLE CODE

 login_ID.setOnClickListener {
            if(email_address_Id.text.isEmpty()){
                email_address_Id.error = "Please Enter Email Address"
            }
            if(Password_ID.text.isEmpty()){
                Password_ID.error = "Please Enter Password"
            }
        }

Adjust icon size of Floating action button (fab)

If you are using androidx 1.0.0 and are using a custom fab size, you will have to specify the custom size using

app:fabCustomSize="your custom size in dp"

By deafult the size is 56dp and there is another variation that is the small sized fab which is 40dp, if you are using anything you will have to specify it for the padding to be calculated correctly

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

Are you sure you are not using a wrong path in the url field? - I was facing the same error, and the problem was solved after I checked the path, found it wrong and replaced it with the right one.

Make sure that the URL you are specifying is correct for the AJAX request and that the file exists.