Programs & Examples On #Openejb

Apache OpenEJB is an embeddable and lightweight EJB 3.0 implementation that can be used as a standalone server or embedded into Tomcat, JUnit, TestNG, Eclipse, IntelliJ, Maven, Ant, and any IDE or application. OpenEJB is included in Apache Geronimo, IBM WebSphere Application Server CE, Apache TomEE and Apple's WebObjects.

Can't stop rails server

1. Simply Delete the pid file from rails app directory

Rails_app -> tmp -> pids -> pid file

Delete the file and run

rails start

2. For Rails 5.0 and above, you can use this command

rails restart

"You tried to execute a query that does not include the specified aggregate function"

GROUP BY can be selected from Total row in query design view in MS Access.
If Total row not shown in design view (as in my case). You can go to SQL View and add GROUP By fname etc. Then Total row will automatically show in design view.
You have to select as Expression in this row for calculated fields.

How to set Oracle's Java as the default Java in Ubuntu?

to set Oracle's Java SE Development Kit as the system default Java just download the latest Java SE Development Kit from here then create a directory somewhere you like in your file system for example /usr/java now extract the files you just downloaded in that directory:

$ sudo tar xvzf jdk-8u5-linux-i586.tar.gz -C /usr/java

now to set your JAVA_HOME environment variable:

$ JAVA_HOME=/usr/java/jdk1.8.0_05/
$ sudo update-alternatives --install /usr/bin/java java ${JAVA_HOME%*/}/bin/java 20000
$ sudo update-alternatives --install /usr/bin/javac javac ${JAVA_HOME%*/}/bin/javac 20000

make sure the Oracle's java is set as default java by:

$ update-alternatives --config java

you get something like this:

There are 2 choices for the alternative java (providing /usr/bin/java).

  Selection    Path                                           Priority   Status
* 0            /opt/java/jdk1.8.0_05/bin/java                  20000     auto mode
  1            /opt/java/jdk1.8.0_05/bin/java                  20000     manual mode
  2            /usr/lib/jvm/java-6-openjdk-i386/jre/bin/java   1061      manual mode

Press enter to keep the current choice[*], or type selection number:

pay attention to the asterisk before the numbers on the left and if the correct one is not set choose the correct one by typing the number of it and pressing enter. now test your java:

$ java -version

if you get something like the following, you are good to go:

java version "1.8.0_05"
Java(TM) SE Runtime Environment (build 1.8.0_05-b13)
Java HotSpot(TM) Server VM (build 25.5-b02, mixed mode)

also note that you might need root permission or be in sudoers group to be able to do this. I've tested this solution on both ubuntu 12.04 and Debian wheezy and it works in both of them.

org.apache.catalina.core.StandardContext startInternal SEVERE: Error listenerStart

SEVERE: Error listenerStart

This boils down to that a ServletContextListener which is registered by either @WebListener annotation on the class, or by a <listener> declaration in web.xml, has thrown an unhandled exception inside the contextInitialized() method. This is usually caused by a developer's mistake (a bug) and needs to be fixed. For example, a NullPointerException.

The full exception should be visible in webapp-specific startup log as well as the IDE console, before the particular line which you've copypasted. If there is none and you still can't figure the cause of the exception by just looking at the code, put the entire contextInitialized() code in a try-catch wherein you log the exception to a reliable output and then interpret and fix it accordingly.

MD5 hashing in Android

i have used below method to give me md5 by passing string for which you want to get md5

public static String getMd5Key(String password) {

//        String password = "12131123984335";

        try {
            MessageDigest md = MessageDigest.getInstance("MD5");

            byte byteData[] = md.digest();

            //convert the byte to hex format method 1
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < byteData.length; i++) {
                sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));

            System.out.println("Digest(in hex format):: " + sb.toString());

            //convert the byte to hex format method 2
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < byteData.length; i++) {
                String hex = Integer.toHexString(0xff & byteData[i]);
                if (hex.length() == 1) hexString.append('0');
            System.out.println("Digest(in hex format):: " + hexString.toString());

            return hexString.toString();

        } catch (Exception e) {
            // TODO: handle exception

        return "";

php multidimensional array get values

For people who searched for php multidimensional array get values and actually want to solve problem comes from getting one column value from a 2 dimensinal array (like me!), here's a much elegant way than using foreach, which is array_column

For example, if I only want to get hotel_name from the below array, and form to another array:

$hotels = [
        'hotel_name' => 'Hotel A',
        'info' => 'Hotel A Info',
        'hotel_name' => 'Hotel B',
        'info' => 'Hotel B Info',

I can do this using array_column:

$hotel_name = array_column($hotels, 'hotel_name');

print_r($hotel_name); // Which will give me ['Hotel A', 'Hotel B']

For the actual answer for this question, it can also be beautified by array_column and call_user_func_array('array_merge', $twoDimensionalArray);

Let's make the data in PHP:

$hotels = [
        'hotel_name' => 'Hotel A',
        'info' => 'Hotel A Info',
        'rooms' => [
                'room_name' => 'Luxury Room',
                'bed' => 2,
                'boards' => [
                    'board_id' => 1,
                    'price' => 200
                'room_name' => 'Non Luxy Room',
                'bed' => 4,
                'boards' => [
                    'board_id' => 2,
                    'price' => 150
        'hotel_name' => 'Hotel B',
        'info' => 'Hotel B Info',
        'rooms' => [
                'room_name' => 'Luxury Room',
                'bed' => 2,
                'boards' => [
                    'board_id' => 3,
                    'price' => 900
                'room_name' => 'Non Luxy Room',
                'bed' => 4,
                'boards' => [
                    'board_id' => 4,
                    'price' => 300

And here's the calculation:

$rooms = array_column($hotels, 'rooms');
$rooms = call_user_func_array('array_merge', $rooms);
$boards = array_column($rooms, 'boards');

foreach($boards as $board){
    $board_id = $board['board_id'];
    $price = $board['price'];
    echo "Board ID is: ".$board_id." and price is: ".$price . "<br/>";

Which will give you the following result:

Board ID is: 1 and price is: 200
Board ID is: 2 and price is: 150
Board ID is: 3 and price is: 900
Board ID is: 4 and price is: 300

Check if Cell value exists in Column, and then get the value of the NEXT Cell

After t.thielemans' answer, I worked that just


works fine and does what I wanted, except that it returns #N/A for non-matches; so it is suitable for the case where it is known that the value definitely exists in the look-up column.

Edit (based on t.thielemans' comment):

To avoid #N/A for non-matches, do:

=IFERROR(VLOOKUP(A1, B:C, 2, FALSE), "No Match")

Syntax error on print with Python 3

Because in Python 3, print statement has been replaced with a print() function, with keyword arguments to replace most of the special syntax of the old print statement. So you have to write it as

print("Hello World")

But if you write this in a program and someone using Python 2.x tries to run it, they will get an error. To avoid this, it is a good practice to import print function:

from __future__ import print_function

Now your code works on both 2.x & 3.x.

Check out below examples also to get familiar with print() function.

Old: print "The answer is", 2*2
New: print("The answer is", 2*2)

Old: print x,           # Trailing comma suppresses newline
New: print(x, end=" ")  # Appends a space instead of a newline

Old: print              # Prints a newline
New: print()            # You must call the function!

Old: print >>sys.stderr, "fatal error"
New: print("fatal error", file=sys.stderr)

Old: print (x, y)       # prints repr((x, y))
New: print((x, y))      # Not the same as print(x, y)!

Source: What’s New In Python 3.0?

JPA Criteria API - How to add JOIN clause (as general sentence as possible)

Warning! There's a numbers of errors on the Sun JPA 2 example and the resulting pasted content in Pascal's answer. Please consult this post.

This post and the Sun Java EE 6 JPA 2 example really held back my comprehension of JPA 2. After plowing through the Hibernate and OpenJPA manuals and thinking that I had a good understanding of JPA 2, I still got confused afterwards when returning to this post.

ESLint Parsing error: Unexpected token

If you have got a pre-commit task with husky running eslint, please continue reading. I tried most of the answers about parserOptions and parser values where my actual issue was about the node version I was using.

My current node version was 12.0.0, but husky was using my nvm default version somehow (even though I didn't have nvm in my system). This seems to be an issue with husky itself. So:

  1. I deleted $HOME/.nvm folder which was not deleted when I removed nvm earlier.
  2. Verified node is the latest and did proper parser options.
  3. It started working!

Convert date to datetime in Python

You can use the date.timetuple() method and unpack operator *.

args = d.timetuple()[:6]

Is it possible to decompile an Android .apk file?

Sometimes you get broken code, when using dex2jar/apktool, most notably in loops. To avoid this, use jadx, which decompiles dalvik bytecode into java source code, without creating a .jar/.class file first as dex2jar does (apktool uses dex2jar I think). It is also open-source and in active development. It even has a GUI, for GUI-fanatics. Try it!

Multiple radio button groups in MVC 4 Razor

Ok here's how I fixed this

My model is a list of categories. Each category contains a list of its subcategories.
with this in mind, every time in the foreach loop, each RadioButton will have its category's ID (which is unique) as its name attribue.
And I also used Html.RadioButton instead of Html.RadioButtonFor.

Here's the final 'working' pseudo-code:

@foreach (var cat in Model.Categories)
  //A piece of code & html here
  @foreach (var item in cat.SubCategories)
     @Html.RadioButton(item.CategoryID.ToString(), item.ID)

The result is:

<input name="127" type="radio" value="110">

Please note that I HAVE NOT put all these radio button groups inside a form. And I don't know if this solution will still work properly in a form.

Thanks to all of the people who helped me solve this ;)

#1273 - Unknown collation: 'utf8mb4_unicode_ci' cPanel

i use this in linux :

sed -i 's/utf8mb4/utf8/g' your_file.sql
sed -i 's/utf8_unicode_ci/utf8_general_ci/g' your_file.sql
sed -i 's/utf8_unicode_520_ci/utf8_general_ci/g' your_file.sql

then restore your_file.sql

mysql -u yourdBUser -p yourdBPasswd yourdB < your_file.sql

How to post JSON to PHP with curl

I believe you are getting an empty array because PHP is expecting the posted data to be in a Querystring format (key=value&key1=value1).

Try changing your curl request to:

curl -i -X POST -d 'json={"screencast":{"subject":"tools"}}'  \

and see if that helps any.

LINQ with groupby and count

Assuming userInfoList is a List<UserInfo>:

        var groups = userInfoList
            .GroupBy(n => n.metric)
            .Select(n => new
                MetricName = n.Key,
                MetricCount = n.Count()
            .OrderBy(n => n.MetricName);

The lambda function for GroupBy(), n => n.metric means that it will get field metric from every UserInfo object encountered. The type of n is depending on the context, in the first occurrence it's of type UserInfo, because the list contains UserInfo objects. In the second occurrence n is of type Grouping, because now it's a list of Grouping objects.

Groupings have extension methods like .Count(), .Key() and pretty much anything else you would expect. Just as you would check .Lenght on a string, you can check .Count() on a group.

jQuery's .click - pass parameters to user function

Yes, this is an old post. Regardless, someone may find it useful. Here is another way to send parameters to event handlers.

//click handler
function add_event(event, paramA, paramB)
    //do something with your parameters
    alert(paramA ? 'paramA:' + paramA : '' + paramB ? '  paramB:' + paramB : '');

//bind handler to click event
//once you've processed some data and know your parameters, trigger a click event.
//In this case, we will send 'myfirst' and 'mysecond' as parameters
$('.leadtoscore').trigger('click', {'myfirst', 'mysecond'});

//or use variables
var a = 'first',
    b = 'second';

$('.leadtoscore').trigger('click', {a, b});
$('.leadtoscore').trigger('click', {a});

How do I select and store columns greater than a number in pandas?

Sample DF:

In [79]: df = pd.DataFrame(np.random.randint(5, 15, (10, 3)), columns=list('abc'))

In [80]: df
    a   b   c
0   6  11  11
1  14   7   8
2  13   5  11
3  13   7  11
4  13   5   9
5   5  11   9
6   9   8   6
7   5  11  10
8   8  10  14
9   7  14  13

present only those rows where b > 10

In [81]: df[df.b > 10]
   a   b   c
0  6  11  11
5  5  11   9
7  5  11  10
9  7  14  13

Minimums (for all columns) for the rows satisfying b > 10 condition

In [82]: df[df.b > 10].min()
a     5
b    11
c     9
dtype: int32

Minimum (for the b column) for the rows satisfying b > 10 condition

In [84]: df.loc[df.b > 10, 'b'].min()
Out[84]: 11

UPDATE: starting from Pandas 0.20.1 the .ix indexer is deprecated, in favor of the more strict .iloc and .loc indexers.


I know its been a while since the original post but I like using CTE's and this worked for me:

WITH cte_table_a
    SELECT [id] [id]
    , MAX([value]) [value]
    FROM table_a
    GROUP BY [id]
UPDATE table_b
SET table_b.code = CASE WHEN cte_table_a.[value] IS NOT NULL THEN cte_table_a.[value] ELSE 124 END
FROM table_b
LEFT OUTER JOIN  cte_table_a
ON =

Check if ADODB connection is open

This is an old topic, but in case anyone else is still looking...

I was having trouble after an undock event. An open db connection saved in a global object would error, even after reconnecting to the network. This was due to the TCP connection being forcibly terminated by remote host. (Error -2147467259: TCP Provider: An existing connection was forcibly closed by the remote host.)

However, the error would only show up after the first transaction was attempted. Up to that point, neither Connection.State nor Connection.Version (per solutions above) would reveal any error.

So I wrote the small sub below to force the error - hope it's useful.

Performance testing on my setup (Access 2016, SQL Svr 2008R2) was approx 0.5ms per call.

Function adoIsConnected(adoCn As ADODB.Connection) As Boolean

    '#PURPOSE: Checks whether the supplied db connection is alive and
    '          hasn't had it's TCP connection forcibly closed by remote
    '          host, for example, as happens during an undock event
    '#RETURNS: True if the supplied db is connected and error-free, 
    '          False otherwise
    '#AUTHOR:  Belladonna

    Dim i As Long
    Dim cmd As New ADODB.Command

    'Set up SQL command to return 1
    cmd.CommandText = "SELECT 1"
    cmd.ActiveConnection = adoCn

    'Run a simple query, to test the connection
    On Error Resume Next
    i = cmd.Execute.Fields(0)
    On Error GoTo 0

    'Tidy up
    Set cmd = Nothing

    'If i is 1, connection is open
    If i = 1 Then
        adoIsConnected = True
        adoIsConnected = False
    End If

End Function

Git for beginners: The definitive practical guide

Checking Out Code

First go to an empty dir, use "git init" to make it a repository, then clone the remote repo into your own.

git clone [email protected]:/dir/to/repo

Wherever you initially clone from is where "git pull" will pull from by default.

Reading and writing to serial port in C on Linux

Some receivers expect EOL sequence, which is typically two characters \r\n, so try in your code replace the line

unsigned char cmd[] = {'I', 'N', 'I', 'T', ' ', '\r', '\0'};


unsigned char cmd[] = "INIT\r\n";

BTW, the above way is probably more efficient. There is no need to quote every character.

Python AttributeError: 'module' object has no attribute 'Serial'

You have installed the incorrect package named 'serial'.

  • Run pip uninstall serial for python 2.x or pip3 uninstall serial for python 3.x
  • Then install pyserial if not already installed by running pip install pyserial for python 2.x orpip3 install pyserial for python 3.x.

html "data-" attribute as javascript parameter


<div data-uid="aaa" data-name="bbb", data-value="ccc" onclick="fun(this)">


function fun(obj) {
    var uid= $(obj).attr('data-uid');
    var name= $(obj).attr('data-name');
    var value= $(obj).attr('data-value');

but I'm using jQuery.

How can I see the raw SQL queries Django is running?

Django-extensions have a command shell_plus with a parameter print-sql

./ shell_plus --print-sql

In django-shell all executed queries will be printed


SELECT "auth_user"."id",
FROM "auth_user"
WHERE "auth_user"."id" = 1

Execution time: 0.002466s [Database: default]

<User: username>

How do I compile a .cpp file on Linux?

You'll need to compile it using:

g++ inputfile.cpp -o outputbinary

The file you are referring has a missing #include <cstdlib> directive, if you also include that in your file, everything shall compile fine.

Is there a way I can capture my iPhone screen as a video?

Short of using a video camera, no.

Many youtube videos for demonstrating iPhone applications are made with a screen grabber application (such as iShowU, ScreenFlow, or Snapz Pro) and the simulator. Be aware that the speed of response in the simulator can be dramatically different than a device - so it's possible to get effects (and miss) with the simulator you'll never see on a device. In particular, default animations can flash by in the simulator, where they just look quick on a device.

TypeError: 'float' object is not subscriptable

You are not selecting multiple indexes with PriceList[0][1][2][3][4][5][6] , instead each [] is going into a sub index.

Try this

PizzaChange=float(input("What would you like the new price for all standard pizzas to be? "))      

using wildcards in LDAP search filters/queries

A filter argument with a trailing * can be evaluated almost instantaneously via an index lookup. A leading * implies a sequential search through the index, so it is O(N). It will take ages.

I suggest you reconsider the requirement.

How can I align text directly beneath an image?

I am not an expert in HTML but here is what worked for me:

<div class="img-with-text-below">
    <img src="your-image.jpg" alt="alt-text" />
    <p><center>Your text</center></p>

Is there an upper bound to BigInteger?

The number is held in an int[] - the maximum size of an array is Integer.MAX_VALUE. So the maximum BigInteger probably is (2 ^ 32) ^ Integer.MAX_VALUE.

Admittedly, this is implementation dependent, not part of the specification.

In Java 8, some information was added to the BigInteger javadoc, giving a minimum supported range and the actual limit of the current implementation:

BigInteger must support values in the range -2Integer.MAX_VALUE (exclusive) to +2Integer.MAX_VALUE (exclusive) and may support values outside of that range.

Implementation note: BigInteger constructors and operations throw ArithmeticException when the result is out of the supported range of -2Integer.MAX_VALUE (exclusive) to +2Integer.MAX_VALUE (exclusive).

Android WSDL/SOAP service client

private static  final  String NAMESPACE = "";
private static  final String URL = "";
private static  final  String SOAP_ACTION = "";
private static  final String METHOD_NAME = "Login";

//calling web services method

String loginresult=callService(username,password,usertype);

//calling webservices
String callService(String a1,String b1,Integer c1) throws Exception {

            Boolean flag=true;

                SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

                PropertyInfo pa1 = new PropertyInfo();

                PropertyInfo pb1 = new PropertyInfo();

                PropertyInfo pc1 = new PropertyInfo();
                System.out.println(c1+"this is integer****s");


                SoapSerializationEnvelope envelope = new    SoapSerializationEnvelope(SoapEnvelope.VER11);
                envelope.dotNet = true;
                HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
                androidHttpTransport.setXmlVersionTag("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
      , envelope);
                catch(Exception e)

                    System.out.println(e+"   this is exception");
                SoapObject response = (SoapObject)envelope.bodyIn;

                result = response.getProperty(0).toString(); 

                }catch (Exception e) {
                // TODO: handle exception
            return result;


Installing MySQL-python

this worked for me on python 3

pip install mysqlclient

use "netsh wlan set hostednetwork ..." to create a wifi hotspot and the authentication can't work correctly

For me, running the ad-hoc network on Windows 8.1, it was two things:

  • I had to set a static IP on my Android (under Advanced Options under where you type the Wifi password)
  • I had to use a password 8 characters long

Any IP will allow you to connect, but if you want internet access the static IP should match the subnet from the shared internet connection.

I'm not sure why I couldn't get a longer password to work, but it's worth a try. Maybe a more knowledgeable person could fill us in.

How can I clear the NuGet package cache using the command line?

dotnet nuget locals all --clear

If you're using .NET Core.

How can I get a specific field of a csv file?

Finaly I got it!!!

import csv

def select_index(index):
    csv_file = open('oscar_age_female.csv', 'r')
    csv_reader = csv.DictReader(csv_file)

    for line in csv_reader:
        l = line['Index']
        if l == index:
            print(line[' "Name"'])


"Bette Davis"

Confusing "duplicate identifier" Typescript error message

Problem was solved by simply:

  1. Deleting the node_modules folder
  2. Running npm install to get all packages with correct versions

In my case, the problem occurred after changing Git branches, where a new branch was using a different set of node modules. The old branch was using TypeScript v1.8, the new one v2.0

What is a software framework?

A simple explanation is: A framework is a scaffold that you can you build applications around.

A framework generally provides some base functionality which you can use and extend to make more complex applications from, there are frameworks for all sorts of things. Microsofts MVC framework is a good example of this. It provides everything you need to get off the ground building website using the MVC pattern, it handles web requests, routes and the like. All you have to do is implement "Controllers" and provide "Views" which are two constructs defined by the MVC framework. The MVC framework then handles calling your controllers and rendering your views.

Perhaps not the best wording but I hope it helps

How can I shuffle the lines of a text file on the Unix command line or in a shell script?

This is a python script that I saved as in my home folder:


import sys
import random

if __name__ == '__main__':
  with open(sys.argv[1], 'r') as f:
    flist = f.readlines()

    for line in flist:
      print line.strip()

On Mac OSX sort -R and shuf are not available so you can alias this in your bash_profile as:

alias shuf='python'

accessing a file using [NSBundle mainBundle] pathForResource: ofType:inDirectory:

Select Project / Specific Folder --> Right Click --> Add Files to Project -- > Select the File you want to add.

This worked for me.

How to validate an email address in JavaScript

There are some complex RegEx written here, that also works.

I tested this one and it works too:


Please test this here :

Hope this helps.

Android Studio suddenly cannot resolve symbols

Be aware that the name of files and specially folders can result in this error. For instance, if you have a folder "Helpers" and the package for files in this folder is "com.whatever.helpers" it won't result in any compilation error but will cause the Android studio fail to load the symbols in that folder. One typical reason for that is when you name a folder with first capital letter, commit it on Git and later change the folder name to all lower case. The Git system won't recognize the change resulting in a discrepancy between the local and remote repositories that only the new repository clones will be affect by.

jQuery checkbox checked state changed event

Is very simple, this is the way I use:


$(document).on('change', '[name="nameOfCheckboxes[]"]', function() {
    var checkbox = $(this), // Selected or current checkbox
        value = checkbox.val(); // Value of checkbox

    if (':checked'))
        console.log('not checked');


How to open in default browser in C#

After researching a lot I feel most of the given answer will not work with dotnet core. 1.System.Diagnostics.Process.Start(""); -- Will not work with dotnet core

2.It will work but it will block the new window opening in case default browser is chrome

 myProcess.StartInfo.UseShellExecute = true; 
    myProcess.StartInfo.FileName = "http://some.domain.tld/bla";

Below is the simplest and will work in all the scenarios.

Process.Start("explorer", url);

regular expression for Indian mobile numbers

Here you go :)


Split a String into an array in Swift?

This is for String and CSV file for swift 4.2 at 20181206 1610

var dataArray : [[String]] = []
 let path = Bundle.main.path(forResource: "csvfilename", ofType: "csv")
        let url = URL(fileURLWithPath: path!)
        do {
            let data = try Data(contentsOf: url) 
            let content = String(data: data, encoding: .utf8)
            let parsedCSV = content?.components(separatedBy: "\r\n").map{ $0.components(separatedBy: ";") }
           for line in parsedCSV!
        catch let jsonErr {
            print("\n   Error read CSV file: \n ", jsonErr)

            print("\n MohNada 20181206 1610 - The final result is \(dataArray)  \n ")

(XML) The markup in the document following the root element must be well-formed. Start location: 6:2

After insuring that the string "strOutput" has a correct XML structure, you can do this:

Matcher junkMatcher = (Pattern.compile("^([\\W]+)<")).matcher(strOutput);
strOutput = junkMatcher.replaceFirst("<");

What is the T-SQL To grant read and write access to tables in a database in SQL Server?

In SQL Server 2012, 2014:

USE mydb


In SQL Server 2008:

use mydb

exec sp_addrolemember db_datareader, MYUSER 
exec sp_addrolemember db_datawriter, MYUSER 

To also assign the ability to execute all Stored Procedures for a Database:


To assign the ability to execute specific stored procedures:

GRANT EXECUTE ON dbo.sp_mystoredprocedure TO MYUSER;

How to stop a setTimeout loop?

I know this is an old question, I'd like to post my approach anyway. This way you don't have to handle the 0 trick that T. J. Crowder expained.

var keepGoing = true;

function myLoop() {
    // ... Do something ...

    if(keepGoing) {
        setTimeout(myLoop, 1000);

function startLoop() {
    keepGoing = true;

function stopLoop() {
    keepGoing = false;

Get month name from Date

The easiest and simplest way I figured.

         var now = new Date();_x000D_
//basically converting whole date to string = "Fri Apr 2020'_x000D_
//then splitting by ' ' a space = ['Fri' 'Apr' '2020']_x000D_
//then selecting second element of array = _x000D_
//['Fri' 'Apr' '2020'].[1]_x000D_
var currentMonth = now.toDateString().split(' ')[1];_x000D_

Visual Studio : short cut Key : Duplicate Line

In Visual Studio 2010 you copy the entire line the cursor is on with CTRL + INSERT then you can use Ctrl + V or SHIFT + INSERT to paste it.

What's the best way to cancel event propagation between nested ng-click calls?

Use $event.stopPropagation():

<div ng-controller="OverlayCtrl" class="overlay" ng-click="hideOverlay()">
    <img src="http://some_src" ng-click="nextImage(); $event.stopPropagation()" />

Here's a demo:

Regular expression to match balanced parentheses

The answer depends on whether you need to match matching sets of brackets, or merely the first open to the last close in the input text.

If you need to match matching nested brackets, then you need something more than regular expressions. - see @dehmann

If it's just first open to last close see @Zach

Decide what you want to happen with:

abc ( 123 ( foobar ) def ) xyz ) ghij

You need to decide what your code needs to match in this case.

How to insert multiple rows from a single query using eloquent/fluent

It is really easy to do a bulk insert in Laravel using Eloquent or the query builder.

You can use the following approach.

$data = [
    ['user_id'=>'Coder 1', 'subject_id'=> 4096],
    ['user_id'=>'Coder 2', 'subject_id'=> 2048],

Model::insert($data); // Eloquent approach
DB::table('table')->insert($data); // Query Builder approach

In your case you already have the data within the $query variable.

Swift 3 URLSession.shared() Ambiguous reference to member 'dataTask(with:completionHandler:) error (bug)

Xcode 10.1 Swift 4

This worked for me:

let task: URLSessionDataTask = session.dataTask(with: request as URLRequest) { (data, response, error) -> Void in

The key was adding in the URLSessionDataTask type declaration.

iOS 7 status bar overlapping UI

If you're using Cordova with Sencha Touch and you're using the normal Sencha Touch navigation/title bars, you can just stretch the navbar and reposition the content within the navbar so it looks at home on iOS 7. Just add this into app.js (after your last Ext.Viewport.add line) :

// Adjust toolbar height when running in iOS to fit with new iOS 7 style
if ( && Ext.os.version.major >= 7) {".x-toolbar").applyStyles("height: 62px; padding-top: 15px;");


This is a bit hacky, I know, but it saves dealing with it at the Objective-C level. It won't be much good for those not using Sencha Touch with Cordova, though.

How to cut a string after a specific character in unix

This should do the trick:

$ echo "$var" | awk -F':' '{print $NF}'

Conditional HTML Attributes using Razor MVC3

Note you can do something like this(at least in MVC3):

<td align="left" @(isOddRow ? "class=TopBorder" : "style=border:0px") >

What I believed was razor adding quotes was actually the browser. As Rism pointed out when testing with MVC 4(I haven't tested with MVC 3 but I assume behavior hasn't changed), this actually produces class=TopBorder but browsers are able to parse this fine. The HTML parsers are somewhat forgiving on missing attribute quotes, but this can break if you have spaces or certain characters.

<td align="left" class="TopBorder" >


<td align="left" style="border:0px" >

What goes wrong with providing your own quotes

If you try to use some of the usual C# conventions for nested quotes, you'll end up with more quotes than you bargained for because Razor is trying to safely escape them. For example:

<button type="button" @(true ? "style=\"border:0px\"" : string.Empty)>

This should evaluate to <button type="button" style="border:0px"> but Razor escapes all output from C# and thus produces:


You will only see this if you view the response over the network. If you use an HTML inspector, often you are actually seeing the DOM, not the raw HTML. Browsers parse HTML into the DOM, and the after-parsing DOM representation already has some niceties applied. In this case the Browser sees there aren't quotes around the attribute value, adds them:


But in the DOM inspector HTML character codes display properly so you actually see:


In Chrome, if you right-click and select Edit HTML, it switch back so you can see those nasty HTML character codes, making it clear you have real outer quotes, and HTML encoded inner quotes.

So the problem with trying to do the quoting yourself is Razor escapes these.

If you want complete control of quotes

Use Html.Raw to prevent quote escaping:

<td @Html.Raw( someBoolean ? "rel='tooltip' data-container='.drillDown a'" : "" )>

Renders as:

<td rel='tooltip' title='Drilldown' data-container='.drillDown a'>

The above is perfectly safe because I'm not outputting any HTML from a variable. The only variable involved is the ternary condition. However, beware that this last technique might expose you to certain security problems if building strings from user supplied data. E.g. if you built an attribute from data fields that originated from user supplied data, use of Html.Raw means that string could contain a premature ending of the attribute and tag, then begin a script tag that does something on behalf of the currently logged in user(possibly different than the logged in user). Maybe you have a page with a list of all users pictures and you are setting a tooltip to be the username of each person, and one users named himself '/><script>$.post('changepassword.php?password=123')</script> and now any other user who views this page has their password instantly changed to a password that the malicious user knows.

Elasticsearch query to return all records

size param increases the hits displayed from from the default(10) to 500.


Change the from step by step to get all the data.


Angular 5 Reactive Forms - Radio Button Group

I tried your code, you didn't assign/bind a value to your formControlName.

In HTML file:

<form [formGroup]="form">
     <input type="radio" value="Male" formControlName="gender">
     <input type="radio" value="Female" formControlName="gender">

In the TS file:

  form: FormGroup;
  constructor(fb: FormBuilder) { = 'Angular2'
    this.form ={
      gender: ['', Validators.required]

Make sure you use Reactive form properly: [formGroup]="form" and you don't need the name attribute.

In my sample. words male and female in span tags are the values display along the radio button and Male and Female values are bind to formControlName

See the screenshot: enter image description here

To make it shorter:

<form [formGroup]="form">
  <input type="radio" value='Male' formControlName="gender" >Male
  <input type="radio" value='Female' formControlName="gender">Female

enter image description here

Hope it helps:)

How do I dynamically set HTML5 data- attributes using react?

Note - if you want to pass a data attribute to a React Component, you need to handle them a little differently than other props.

2 options

Don't use camel case

<Option data-img-src='value' ... />

And then in the component, because of the dashes, you need to refer to the prop in quotes.

// @flow
class Option extends React.Component {

  props: {
    'data-img-src': string

And when you refer to it later, you don't use the dot syntax

  render () {
    return (
      <option data-img-src={this.props['data-img-src']} >...</option>

Or use camel case

<Option dataImgSrc='value' ... />

And then in the component, you need to convert.

// @flow
class Option extends React.Component {

  props: {
    dataImgSrc: string

And when you refer to it later, you don't use the dot syntax

  render () {
    return (
      <option data-img-src={this.props.dataImgSrc} >...</option>

Mainly just realize data- attributes and aria- attributes are treated specially. You are allowed to use hyphens in the attribute name in those two cases.



  FROM user_payment
 WHERE user_id=1 
ORDER BY paym_date = (select MAX(paym_date) from user_payment and user_id=1);


  SELECT MEMBSHIP_ID, row_number() over (order by paym_date desc) rn
      FROM user_payment
     WHERE user_id=1 )
WHERE rn = 1

Set select option 'selected', by value

Just put in this code:


Declare and Initialize String Array in VBA


Dim myarray As Variant

works but

Dim myarray As String

doesn't so I sitck to Variant

How do I prompt a user for confirmation in bash script?

This what I found elsewhere, is there a better possible version?

read -p "Are you sure you wish to continue?"
if [ "$REPLY" != "yes" ]; then

How do I get the row count of a Pandas DataFrame?

An alternative method to finding out the amount of rows in a dataframe which I think is the most readable variant is pandas.Index.size.

Do note that, as I commented on the accepted answer,

Suspected pandas.Index.size would actually be faster than len(df.index) but timeit on my computer tells me otherwise (~150 ns slower per loop).

Insert json file into mongodb

the following two ways work well:

C:\>mongodb\bin\mongoimport --jsonArray -d test -c docs --file example2.json
C:\>mongodb\bin\mongoimport --jsonArray -d test -c docs < example2.json

if the collections are under a specific user, you can use -u -p --authenticationDatabase

Uploading file using POST request in Node.js

Leonid Beschastny's answer works but I also had to convert ArrayBuffer to Buffer that is used in the Node's request module. After uploading file to the server I had it in the same format that comes from the HTML5 FileAPI (I'm using Meteor). Full code below - maybe it will be helpful for others.

function toBuffer(ab) {
  var buffer = new Buffer(ab.byteLength);
  var view = new Uint8Array(ab);
  for (var i = 0; i < buffer.length; ++i) {
    buffer[i] = view[i];
  return buffer;

var req =, function (err, resp, body) {
  if (err) {
  } else {
    console.log('URL: ' + body);
var form = req.form();
form.append('file', toBuffer(, {
  contentType: file.type

How do I get the path of the assembly the code is in?

I find my solution adequate for the retrieval of the location.

var executingAssembly = new FileInfo((Assembly.GetExecutingAssembly().Location)).Directory.FullName;

Display Images Inline via CSS

The code you have posted here and code on your site both are different. There is a break <br> after second image, so the third image into new line, remove this <br> and it will display correctly.

How do you change library location in R?

I'm late to the party but I encountered the same thing when I tried to get fancy and move my library and then had files being saved to a folder that was outdated:

.libloc <<- "C:/Program Files/rest_of_your_Library_FileName"

One other point to mention is that for Windows Computers, if you copy the address from Windows Explorer, you have to manually change the '\' to a '/' for the directory to be recognized.

How to run 'sudo' command in windows

To just run a command as admin in a non-elevated Powershell, you can use Start-Process directly, with the right options, particularly -Verb runas.

It's a lot more convoluted than sudo, particularly because you can't just re-use the previous command with an additional option. You need to specify the arguments to your command separately.

Here is an example, using the route command to change the gateway :

This fails because we are not in an elevated PS:

> route change mask
The requested operation requires elevation.

This works after accepting the UAC:

> Start-Process route -ArgumentList "change mask" -Verb runas

Or for a command that requires cmd.exe:

> Start-Process cmd -ArgumentList "/c other_command arguments ..." -Verb runas

Convert string to ASCII value python

def stringToNumbers(ord(message)):
    return stringToNumbers
    stringToNumbers.append = (ord[0])
    stringToNumbers = ("morocco")

How to split a string after specific character in SQL Server and update this value to specific column

Maybe something like this:

First some test data:

DECLARE @tbl TABLE(Column1 VARCHAR(100))

SELECT '1/2'

Then like this:

    @tbl AS tbl

Simplest way to throw an error/exception with a custom message in Swift 2?

Swift 4:

As per:

if you don't want to define a custom exception, you could use a standard NSError object as follows:

import Foundation

do {
  throw NSError(domain: "my error domain", code: 42, userInfo: ["ui1":12, "ui2":"val2"] ) 
catch let error as NSError {
  print("Caught NSError: \(error.localizedDescription), \(error.domain), \(error.code)")
  let uis = error.userInfo 
  print("\tUser info:")
  for (key,value) in uis {
    print("\t\tkey=\(key), value=\(value)")


Caught NSError: The operation could not be completed, my error domain, 42
    User info:
        key=ui1, value=12
        key=ui2, value=val2

This allows you to provide a custom string (the error domain), plus a numeric code and a dictionary with all the additional data you need, of any type.

N.B.: this was tested on OS=Linux (Ubuntu 16.04 LTS).

Pull new updates from original GitHub repository into forked GitHub repository

To automatically sync your forked repository with the parent repository, you could use the Pull App on GitHub.

Refer to the Readme for more details.

For advanced setup where you want to preserve your changes done to the forked repository, refer to my answer on a similar question here.

What is the purpose of the return statement?

Just to add to @Nathan Hughes's excellent answer:

The return statement can be used as a kind of control flow. By putting one (or more) return statements in the middle of a function, we can say: "stop executing this function. We've either got what we wanted or something's gone wrong!"

Here's an example:

>>> def make_3_characters_long(some_string):
...     if len(some_string) == 3:
...         return False
...     if str(some_string) != some_string:
...         return "Not a string!"
...     if len(some_string) < 3:
...         return ''.join(some_string,'x')[:,3]
...     return some_string[:,3]
>>> threechars = make_3_characters_long('xyz')    
>>> if threechars:
...     print threechars
... else:
...     print "threechars is already 3 characters long!"
threechars is already 3 characters long!

See the Code Style section of the Python Guide for more advice on this way of using return.

Why is char[] preferred over String for passwords?

To quote an official document, the Java Cryptography Architecture guide says this about char[] vs. String passwords (about password-based encryption, but this is more generally about passwords of course):

It would seem logical to collect and store the password in an object of type java.lang.String. However, here's the caveat: Objects of type String are immutable, i.e., there are no methods defined that allow you to change (overwrite) or zero out the contents of a String after usage. This feature makes String objects unsuitable for storing security sensitive information such as user passwords. You should always collect and store security sensitive information in a char array instead.

Guideline 2-2 of the Secure Coding Guidelines for the Java Programming Language, Version 4.0 also says something similar (although it is originally in the context of logging):

Guideline 2-2: Do not log highly sensitive information

Some information, such as Social Security numbers (SSNs) and passwords, is highly sensitive. This information should not be kept for longer than necessary nor where it may be seen, even by administrators. For instance, it should not be sent to log files and its presence should not be detectable through searches. Some transient data may be kept in mutable data structures, such as char arrays, and cleared immediately after use. Clearing data structures has reduced effectiveness on typical Java runtime systems as objects are moved in memory transparently to the programmer.

This guideline also has implications for implementation and use of lower-level libraries that do not have semantic knowledge of the data they are dealing with. As an example, a low-level string parsing library may log the text it works on. An application may parse an SSN with the library. This creates a situation where the SSNs are available to administrators with access to the log files.

C++ error : terminate called after throwing an instance of 'std::bad_alloc'

Something throws an exception of type std::bad_alloc, indicating that you ran out of memory. This exception is propagated through until main, where it "falls off" your program and causes the error message you see.

Since nobody here knows what "RectInvoice", "rectInvoiceVector", "vect", "im" and so on are, we cannot tell you what exactly causes the out-of-memory condition. You didn't even post your real code, because w h looks like a syntax error.

Does Android support near real time push notification?

Google recently(18May2016) announced that Firebase is now it's unified platform for mobile developers including near real time push notifications.It is also multi-platform :

The company now offers all Firebase users free and unlimited notifications with support for iOS, Android and the Web.


automatically execute an Excel macro on a cell change

Your code looks pretty good.

Be careful, however, for your call to Range("H5") is a shortcut command to Application.Range("H5"), which is equivalent to Application.ActiveSheet.Range("H5"). This could be fine, if the only changes are user-changes -- which is the most typical -- but it is possible for the worksheet's cell values to change when it is not the active sheet via programmatic changes, e.g. VBA.

With this in mind, I would utilize Target.Worksheet.Range("H5"):

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Target.Worksheet.Range("H5")) Is Nothing Then Macro
End Sub

Or you can use Me.Range("H5"), if the event handler is on the code page for the worksheet in question (it usually is):

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Me.Range("H5")) Is Nothing Then Macro
End Sub

Hope this helps...

How to recover the deleted files using "rm -R" command in linux server?

Not possible with standard unix commands. You might have luck with a file recovery utility. Also, be aware, using rm changes the table of contents to mark those blocks as available to be overwritten, so simply using your computer right now risks those blocks being overwritten permanently. If it's critical data, you should turn off the computer before the file sectors gets overwritten. Good luck!

Some restore utility:

Forum where this was previously answered:

Converting pfx to pem using openssl

Another perspective for doing it on Linux... here is how to do it so that the resulting single file contains the decrypted private key so that something like HAProxy can use it without prompting you for passphrase.

openssl pkcs12 -in file.pfx -out file.pem -nodes

Then you can configure HAProxy to use the file.pem file.

This is an EDIT from previous version where I had these multiple steps until I realized the -nodes option just simply bypasses the private key encryption. But I'm leaving it here as it may just help with teaching.

openssl pkcs12 -in file.pfx -out file.nokey.pem -nokeys
openssl pkcs12 -in file.pfx -out file.withkey.pem
openssl rsa -in file.withkey.pem -out file.key
cat file.nokey.pem file.key > file.combo.pem
  1. The 1st step prompts you for the password to open the PFX.
  2. The 2nd step prompts you for that plus also to make up a passphrase for the key.
  3. The 3rd step prompts you to enter the passphrase you just made up to store decrypted.
  4. The 4th puts it all together into 1 file.

Then you can configure HAProxy to use the file.combo.pem file.

The reason why you need 2 separate steps where you indicate a file with the key and another without the key, is because if you have a file which has both the encrypted and decrypted key, something like HAProxy still prompts you to type in the passphrase when it uses it.

Jenkins CI Pipeline Scripts not permitted to use method groovy.lang.GroovyObject

To get around sandboxing of SCM stored Groovy scripts, I recommend to run the script as Groovy Command (instead of Groovy Script file):

import hudson.FilePath
final GROOVY_SCRIPT = "workspace/relative/path/to/the/checked/out/groovy/script.groovy"

evaluate(new FilePath(build.workspace, GROOVY_SCRIPT).read().text)

in such case, the groovy script is transferred from the workspace to the Jenkins Master where it can be executed as a system Groovy Script. The sandboxing is suppressed as long as the Use Groovy Sandbox is not checked.

SyntaxError: multiple statements found while compiling a single statement

In the shell, you can't execute more than one statement at a time:

>>> x = 5
y = 6
SyntaxError: multiple statements found while compiling a single statement

You need to execute them one by one:

>>> x = 5
>>> y = 6

When you see multiple statements are being declared, that means you're seeing a script, which will be executed later. But in the interactive interpreter, you can't do more than one statement at a time.

Git in Visual Studio - add existing project?

To add a project within a solution, just open the Team Explorer window and go to Changes. Then, under Untracked Files, click on View options and select Switch to Tree View (unless it is already in tree view), right click on the project root folder, and select Add.

Enter image description here

How do I check how many options there are in a dropdown menu?

$('#idofdropdown option').length;

That should do it.

Solving "adb server version doesn't match this client" error

I had same problem since updated platfrom-tool to version 24 and not sure for root cause...(current adb version is 1.0.36)

Also try adb kill-server and adb start-server but problem still happened

but when I downgrade adb version to 1.0.32 everything work will

Disabling Minimize & Maximize On WinForm?

you can simply disable maximize inside form constructor.

 public Form1(){
     MaximizeBox = false;

to minimize when closing.

private void Form1_FormClosing(Object sender, FormClosingEventArgs e) {
    e.Cancel = true;
    WindowState = FormWindowState.Minimized;

Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

TensorFlow 2.3.0 works fine with CUDA 11. But you have to install tf-nightly-gpu (after you installed tensorflow and CUDA 11):


pip install tf-nightly-gpu

Afterwards you'll get the message in your console:

I tensorflow/stream_executor/platform/default/] Successfully opened dynamic library cudart64_110.dll

Java: how to represent graphs?

If you need weighted edges and multigraphs, you might want to add another class Edge.

I would also recommend using generics to allow specifying which sub-class of Vertex and Edge are currently used. For example:

public class Graph<V extends Vertex> {
List<V> vertices;

When it comes to implementing graph algorithms, you could also define interfaces for your graph classes on which the algorithms can operate, so that you can play around with different implementations of the actual graph representation. For example, simple graphs that are well-connected might be better implemented by an adjacency matrix, sparser graphs might be represented by adjacency lists - it all depends...

BTW Building such structures efficiently can be quite challenging, so maybe you could give us some more details on what kind of job you would want to use them for? For more complex tasks I would suggest you have a look at the various Java graph libraries, to get some inspiration.

Sum across multiple columns with dplyr

Using reduce() from purrr is slightly faster than rowSums and definately faster than apply, since you avoid iterating over all the rows and just take advantage of the vectorized operations:

iris %>% mutate(Petal = reduce(select(., starts_with("Petal")), `+`))

See this for timings

PHP create key => value pairs within a foreach

In PHP >= 5.3 it can be done like this:

$offerArray = array_map(function($value) {
    return $value[4];
}, $offer);

How can I check if the array of objects have duplicate property values?

You can use map to return just the name, and then use this forEach trick to check if it exists at least twice:

var areAnyDuplicates = false; {
}).forEach(function (element, index, arr) {
    if (arr.indexOf(element) !== index) {
        areAnyDuplicates = true;


Convert integer to binary in C#

This was a interesting read i was looking for a quick copy paste. I knew i had done this before long ago with bitmath differently.

Here was my take on it.

// i had this as a extension method in a static class (this int inValue);

public static string ToBinaryString(int inValue)
    string result = "";
    for (int bitIndexToTest = 0; bitIndexToTest < 32; bitIndexToTest++)
        result += ((inValue & (1 << (bitIndexToTest))) > 0) ? '1' : '0';
    return result;

You could stick spacing in there with a bit of modulos in the loop.

        // little bit of spacing
        if (((bitIndexToTest + 1) % spaceEvery) == 0)
            result += ' ';

You could probably use or pass in a stringbuilder and append or index directly to avoid deallocations and also get around the use of += this way;

How do C++ class members get initialized if I don't do it explicitly?

Uninitialized non-static members will contain random data. Actually, they will just have the value of the memory location they are assigned to.

Of course for object parameters (like string) the object's constructor could do a default initialization.

In your example:

int *ptr; // will point to a random memory location
string name; // empty string (due to string's default costructor)
string *pname; // will point to a random memory location
string &rname; // it would't compile
const string &crname; // it would't compile
int age; // random value

How to download HTTP directory with all files and sub-directories as they appear on the online files/folders list?

I was able to get this to work thanks to this post utilizing VisualWGet. It worked great for me. The important part seems to be to check the -recursive flag (see image).

Also found that the -no-parent flag is important, othewise it will try to download everything.

enter image description here enter image description here

Best implementation for Key Value Pair Data Structure?

There is a KeyValuePair built-in type. As a matter of fact, this is what the IDictionary is giving you access to when you iterate in it.

Also, this structure is hardly a tree, finding a more representative name might be a good exercise.

MySQL GROUP BY two columns

Using Concat on the group by will work

SELECT,,, SUM ( portfolios.portfolio + ) AS total
FROM clients, portfolios
WHERE = portfolios.client_id

gpg: no valid OpenPGP data found

This problem might occur if you are behind corporate proxy and corporation uses its own certificate. Just add "--no-check-certificate" in the command. e.g. wget --no-check-certificate -qO - | sudo apt-key add -

It works. If you want to see what is going on, you can use verbose command instead of quiet before adding "--no-check-certificate" option. e.g. wget -vO - | sudo apt-key add - This will tell you to use "--no-check-certificate" if you are behind proxy.

What's the best way to get the current URL in Spring MVC?

Well there are two methods to access this data easier, but the interface doesn't offer the possibility to get the whole URL with one call. You have to build it manually:

public static String makeUrl(HttpServletRequest request)
    return request.getRequestURL().toString() + "?" + request.getQueryString();

I don't know about a way to do this with any Spring MVC facilities.

If you want to access the current Request without passing it everywhere you will have to add a listener in the web.xml:


And then use this to get the request bound to the current Thread:

((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest()

Console.WriteLine and generic List

Do this:

list.ForEach(i => Console.Write("{0}\t", i));

EDIT: To others that have responded - he wants them all on the same line, with tabs between them. :)

How do I undo the most recent local commits in Git?

Get last commit ID by using this command (in the log one on the top it is the latest one):

git log

Get the commit id (GUID) and run this command:

git revert <commit_id>

AngularJS toggle class using ng-class

As alternate solution, based on javascript logic operator '&&' which returns the last evaluation, you can also do this like so:

<i ng-class="autoScroll && 'icon-autoscroll' || !autoScroll && 'icon-autoscroll-disabled'"></i>

It's only slightly shorter syntax, but for me easier to read.

Remove trailing comma from comma-separated string




a, b, c
, ,a, b, c, 
,a, b, c   ,
,,a, b, c, ,,,
, a, b, c,    ,
    a, b, c     
     a, b, c ,,
, a, b, c, 
, ,a, b, c, ,
 , a, b, c , 
,,, a, b, c,,, 
,,, ,,,a, b, c,,, ,,,
,,, ,,, a, b, c,,, ,,,
 ,,,a, b, c ,,,
 ,,,a, b, c,,, 
   a, b, c   


a, b, c
a, b, c
a, b, c
a, b, c
a, b, c
a, b, c
a, b, c
a, b, c
a, b, c
a, b, c
a, b, c
a, b, c
a, b, c
a, b, c
a, b, c
a, b, c

AngularJS ui router passing data between states without URL

We can use params, new feature of the UI-Router:

API Reference / ui.router.state / $stateProvider

params A map which optionally configures parameters declared in the url, or defines additional non-url parameters. For each parameter being configured, add a configuration object keyed to the name of the parameter.

See the part: "...or defines additional non-url parameters..."

So the state def would be:

  .state('home', {
    url: "/home",
    templateUrl: 'tpl.html',
    params: { hiddenOne: null, }

Few examples form the doc mentioned above:

// define a parameter's default value
params: {
  param1: { value: "defaultValue" }
// shorthand default values
params: {
  param1: "defaultValue",
  param2: "param2Default"

// param will be array []
params: {
  param1: { array: true }

// handling the default value in url:
params: {
  param1: {
    value: "defaultId",
    squash: true
} }
// squash "defaultValue" to "~"
params: {
  param1: {
    value: "defaultValue",
    squash: "~"
  } }

EXTEND - working example:

Here is an example of a state definition:

  .state('home', {
      url: "/home",
      params : { veryLongParamHome: null, },
  .state('parent', {
      url: "/parent",
      params : { veryLongParamParent: null, },
  .state('parent.child', { 
      url: "/child",
      params : { veryLongParamChild: null, },

This could be a call using ui-sref:

<a ui-sref="home({veryLongParamHome:'Home--f8d218ae-d998-4aa4-94ee-f27144a21238'

<a ui-sref="parent({ 

<a ui-sref="parent.child({

Check the example here

What languages are Windows, Mac OS X and Linux written in?

I have read or heard that Mac OS X is written mostly in Objective-C with some of the lower level parts, such as the kernel, and hardware device drivers written in C. I believe that Apple "eat(s) its own dog food", meaning that they write Mac OS X using their own Xcode Developer Tools. The GCC(GNU Compiler Collection) compiler-linker is the unix command line tool that xCode used for most of its compiling and/or linking of executables. Among other possible languages, I know GCC compiles source code from the C, Objective-C, C++ and Objective-C++ languages.

How to add RSA key to authorized_keys file?

I know I am replying too late but for anyone else who needs this, run following command from your local machine

cat ~/.ssh/ | ssh [email protected] "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys"

this has worked perfectly fine. All you need to do is just to replace

[email protected]

with your own user for that particular host

form_for with nested resources

Travis R is correct. (I wish I could upvote ya.) I just got this working myself. With these routes:

resources :articles do
  resources :comments

You get paths like:


routed to controllers at


just as it says at, with no special namespaces.

But partials and forms become tricky. Note the square brackets:

<%= form_for [@article, @comment] do |f| %>

Most important, if you want a URI, you may need something like this:

article_comment_path(@article, @comment)


[@article, @comment]

as described at

For example, inside a collections partial with comment_item supplied for iteration,

<%= link_to "delete", article_comment_path(@article, comment_item),
      :method => :delete, :confirm => "Really?" %>

What jamuraa says may work in the context of Article, but it did not work for me in various other ways.

There is a lot of discussion related to nested resources, e.g.

Interestingly, I just learned that most people's unit-tests are not actually testing all paths. When people follow jamisbuck's suggestion, they end up with two ways to get at nested resources. Their unit-tests will generally get/post to the simplest:

# POST /comments
post :create, :comment => {:article_id=>42, ...}

In order to test the route that they may prefer, they need to do it this way:

# POST /articles/42/comments
post :create, :article_id => 42, :comment => {...}

I learned this because my unit-tests started failing when I switched from this:

resources :comments
resources :articles do
  resources :comments

to this:

resources :comments, :only => [:destroy, :show, :edit, :update]
resources :articles do
  resources :comments, :only => [:create, :index, :new]

I guess it's ok to have duplicate routes, and to miss a few unit-tests. (Why test? Because even if the user never sees the duplicates, your forms may refer to them, either implicitly or via named routes.) Still, to minimize needless duplication, I recommend this:

resources :comments
resources :articles do
  resources :comments, :only => [:create, :index, :new]

Sorry for the long answer. Not many people are aware of the subtleties, I think.

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

I've faced this issue and I tried all the answers on Stackoverflow but not worked for me, finally I found solution for this issue:

  • First of all you have to uninstall nodejs and remove all the files related him
  • Go to "Register Editor" and search for all "nodejs", "node.js" and delete them
  • Restart your computer
  • And reinstall nodejs then install angular.

It's worked for me

Script for rebuilding and reindexing the fragmented index?

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

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

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


use yourdbname

-- Ensure a USE  statement has been executed first.


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

    DECLARE @page_count_minimum SMALLINT
    SET @page_count_minimum = 50

    DECLARE @fragmentation_minimum FLOAT
    SET @fragmentation_minimum = 30.0

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

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

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

-- Open the cursor.
    OPEN partitions;

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

            IF @@FETCH_STATUS < 0

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

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

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

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

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

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

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

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

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


C# error: "An object reference is required for the non-static field, method, or property"

It looks like you want:

public static string GetRandomBits()

Without static, you would need an object before you can call the GetRandomBits() method. However, since the implementation of GetRandomBits() does not depend on the state of any Program object, it's best to declare it static.

URL to load resources from the classpath in Java

I try to avoid the URL class and instead rely on URI. Thus for things that need URL where I would like to do Spring Resource like lookup with out Spring I do the following:

public static URL toURL(URI u, ClassLoader loader) throws MalformedURLException {
    if ("classpath".equals(u.getScheme())) {
        String path = u.getPath();
        if (path.startsWith("/")){
            path = path.substring("/".length());
        return loader.getResource(path);
    else if (u.getScheme() == null && u.getPath() != null) {
        //Assume that its a file.
        return new File(u.getPath()).toURI().toURL();
    else {
        return u.toURL();

To create a URI you can use URI.create(..). This way is also better because you control the ClassLoader that will do the resource lookup.

I noticed some other answers trying to parse the URL as a String to detect the scheme. I think its better to pass around URI and use it to parse instead.

I have actually filed an issue a while ago with Spring Source begging them to separate out their Resource code from core so that you don't need all the other Spring stuff.

OS specific instructions in CMAKE: How to?

Try that:


target_link_libraries(${PROJECT_NAME} bioutils ${ADDITIONAL_LIBRARIES})

You can find other useful variables here.

jQuery loop over JSON result from AJAX Success?

Try function, works pretty well with maps.

var mapArray = {_x000D_
  "lastName": "Last Name cannot be null!",_x000D_
  "email": "Email cannot be null!",_x000D_
  "firstName": "First Name cannot be null!"_x000D_
$.map(mapArray, function(val, key) {_x000D_
  alert("Value is :" + val);_x000D_
  alert("key is :" + key);_x000D_
<script src=""></script>

Check if an element has event listener on it. No jQuery

There is no JavaScript function to achieve this. However, you could set a boolean value to true when you add the listener, and false when you remove it. Then check against this boolean before potentially adding a duplicate event listener.

Possible duplicate: How to check whether dynamically attached event listener exists or not?

How to validate a date?

function isValidDate(year, month, day) {
        var d = new Date(year, month - 1, day, 0, 0, 0, 0);
        return (!isNaN(d) && (d.getDate() == day && d.getMonth() + 1 == month && d.getYear() == year));

How to check the input is an integer or not in Java?

If the user input is a String then you can try to parse it as an integer using parseInt method, which throws NumberFormatException when the input is not a valid number string:

try {

    int intValue = Integer.parseInt(stringUserInput));
}(NumberFormatException e) {
    System.out.println("Input is not a valid integer");

fitting data with numpy

Note that you can use the Polynomial class directly to do the fitting and return a Polynomial instance.

from numpy.polynomial import Polynomial

p =, y, 4)

p uses scaled and shifted x values for numerical stability. If you need the usual form of the coefficients, you will need to follow with

pnormal = p.convert(domain=(-1, 1))

iFrame src change event detection?

You may want to use the onLoad event, as in the following example:

<iframe src="" onLoad="alert('Test');"></iframe>

The alert will pop-up whenever the location within the iframe changes. It works in all modern browsers, but may not work in some very older browsers like IE5 and early Opera. (Source)

If the iframe is showing a page within the same domain of the parent, you would be able to access the location with contentWindow.location, as in the following example:

<iframe src="/test.html" onLoad="alert(this.contentWindow.location);"></iframe>

Converting an array to a function arguments list

Yes. In current versions of JS you can use:

app[func]( ...args );

Users of ES5 and older will need to use the .apply() method:

app[func].apply( this, args );

Read up on these methods at MDN:

Understanding implicit in Scala

WARNING: contains sarcasm judiciously! YMMV...

Luigi's answer is complete and correct. This one is only to extend it a bit with an example of how you can gloriously overuse implicits, as it happens quite often in Scala projects. Actually so often, you can probably even find it in one of the "Best Practice" guides.

object HelloWorld {
  case class Text(content: String)
  case class Prefix(text: String)

  implicit def String2Text(content: String)(implicit prefix: Prefix) = {
    Text(prefix.text + " " + content)

  def printText(text: Text): Unit = {

  def main(args: Array[String]): Unit = {

  // Best to hide this line somewhere below a pile of completely unrelated code.
  // Better yet, import its package from another distant place.
  implicit val prefixLOL = Prefix("Hello")

How to order citations by appearance using BibTeX?

Just a brief note - I'm using a modified version of plain.bst sitting in the directory with my Latex files; it turns out having sorting by order of appearance is a relatively easy change; just find the piece of code:

ITERATE {presort}


... and comment it - I turned it to:

%% % avoid sort:
%% ITERATE {presort}

... and then, after running bibtex, pdflatex, pdflatex - the citations will be sorted by order of appearance (that is, they will be unsorted :) ).


EDIT: just realized that what I wrote is actually in the comment by @ChrisN: "can you edit it to remove the SORT command" ;)

Setting selected option in laravel form

Another ordinary simple way this is good if there are few options in select box

<select name="job_status">
   <option {{old('job_status',$profile->job_status)=="unemployed"? 'selected':''}}  value="unemployed">Unemployed</option>
   <option {{old('job_status',$profile->job_status)=="employed"? 'selected':''}} value="employed">Employed</option>

HTTPS setup in Amazon EC2

You need to register a domain(on GoDaddy for example) and put a load balancer in front of your ec2 instance - as DigaoParceiro said in his answer.

The issue is that domains generated by amazon on your ec2 instances are ephemeral. Today the domain is belonging to you, tomorrow it may not.

For that reason, let's encrypt throws an error when you try to register a certificate on amazon generated domain that states:

The ACME server refuses to issue a certificate for this domain name, because it is forbidden by policy

More details about this here:

UITextField text change event

Swift 4

func addNotificationObservers() {

    NotificationCenter.default.addObserver(self, selector: #selector(textFieldDidChangeAction(_:)), name: .UITextFieldTextDidChange, object: nil)


@objc func textFieldDidChangeAction(_ notification: NSNotification) {

    let textField = notification.object as! UITextField


how to add or embed CKEditor in php page

<?php require("ckeditor/ckeditor.php"); ?>

 <script type="text/javascript" src="ckeditor/ckeditor.js"></script>
 <script type="text/javascript" src="somedirectory/ckeditor/ckeditor.js"></script>

<textarea class="ckeditor" name="editor1"></textarea>

Why extend the Android Application class?

Not an answer but an observation: keep in mind that the data in the extended application object should not be tied to an instance of an activity, as it is possible that you have two instances of the same activity running at the same time (one in the foreground and one not being visible).

For example, you start your activity normally through the launcher, then "minimize" it. You then start another app (ie Tasker) which starts another instance of your activitiy, for example in order to create a shortcut, because your app supports android.intent.action.CREATE_SHORTCUT. If the shortcut is then created and this shortcut-creating invocation of the activity modified the data the application object, then the activity running in the background will start to use this modified application object once it is brought back to the foreground.

Multiple Inheritance in C#

Multiple inheritance is one of those things that generally causes more problems than it solves. In C++ it fits the pattern of giving you enough rope to hang yourself, but Java and C# have chosen to go the safer route of not giving you the option. The biggest problem is what to do if you inherit multiple classes that have a method with the same signature that the inheritee doesn't implement. Which class's method should it choose? Or should that not compile? There is generally another way to implement most things that doesn't rely on multiple inheritance.

join list of lists in python

This works recursively for infinitely nested elements:

def iterFlatten(root):
    if isinstance(root, (list, tuple)):
        for element in root:
            for e in iterFlatten(element):
                yield e
        yield root


>>> b = [["a", ("b", "c")], "d"]
>>> list(iterFlatten(b))
['a', 'b', 'c', 'd']

How to import XML file into MySQL database table using XML_LOAD(); function

Since ID is auto increment, you can also specify ID=NULL as,

LOAD XML LOCAL INFILE '/pathtofile/file.xml' INTO TABLE my_tablename SET ID=NULL;

AngularJS Error: Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, https

Navigate to C:/user/project/index.html, open it with Visual Studio 2017, File > View in Browser or press Ctrl+Shift+W

CSS: Set Div height to 100% - Pixels

Alternatively, you can just use position:absolute:

    top: 111px;
    bottom: 0px;

However, IE6 doesn't like top and bottom declarations. But web developers don't like IE6.

Install NuGet via PowerShell script

Without having Visual Studio, you can grab Nuget from:

For command-line executions using this, check out:

With respect to Powershell, just copy the nuget.exe to the machine. No installation required, just execute it using commands from the above documentation.

How to remove specific object from ArrayList in Java?

If you are using Java 8:

test.removeIf(t -> t.i == 1);

Java 8 has a removeIf method in the collection interface. For the ArrayList, it has an advanced implementation (order of n).

How to center a label text in WPF?


Label label = new Label();
label.HorizontalContentAlignment = HorizontalAlignment.Center;

"Fatal error: Unable to find local grunt." when running "grunt" command

if you are a exists project, maybe should execute npm install.

guntjs getting started step 2.

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

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

Why use a ReentrantLock if one can use synchronized(this)?

A ReentrantLock is unstructured, unlike synchronized constructs -- i.e. you don't need to use a block structure for locking and can even hold a lock across methods. An example:

private ReentrantLock lock;

public void foo() {

public void bar() {

Such flow is impossible to represent via a single monitor in a synchronized construct.

Aside from that, ReentrantLock supports lock polling and interruptible lock waits that support time-out. ReentrantLock also has support for configurable fairness policy, allowing more flexible thread scheduling.

The constructor for this class accepts an optional fairness parameter. When set true, under contention, locks favor granting access to the longest-waiting thread. Otherwise this lock does not guarantee any particular access order. Programs using fair locks accessed by many threads may display lower overall throughput (i.e., are slower; often much slower) than those using the default setting, but have smaller variances in times to obtain locks and guarantee lack of starvation. Note however, that fairness of locks does not guarantee fairness of thread scheduling. Thus, one of many threads using a fair lock may obtain it multiple times in succession while other active threads are not progressing and not currently holding the lock. Also note that the untimed tryLock method does not honor the fairness setting. It will succeed if the lock is available even if other threads are waiting.

ReentrantLock may also be more scalable, performing much better under higher contention. You can read more about this here.

This claim has been contested, however; see the following comment:

In the reentrant lock test, a new lock is created each time, thus there is no exclusive locking and the resulting data is invalid. Also, the IBM link offers no source code for the underlying benchmark so its impossible to characterize whether the test was even conducted correctly.

When should you use ReentrantLocks? According to that developerWorks article...

The answer is pretty simple -- use it when you actually need something it provides that synchronized doesn't, like timed lock waits, interruptible lock waits, non-block-structured locks, multiple condition variables, or lock polling. ReentrantLock also has scalability benefits, and you should use it if you actually have a situation that exhibits high contention, but remember that the vast majority of synchronized blocks hardly ever exhibit any contention, let alone high contention. I would advise developing with synchronization until synchronization has proven to be inadequate, rather than simply assuming "the performance will be better" if you use ReentrantLock. Remember, these are advanced tools for advanced users. (And truly advanced users tend to prefer the simplest tools they can find until they're convinced the simple tools are inadequate.) As always, make it right first, and then worry about whether or not you have to make it faster.

One final aspect that's gonna become more relevant in the near future has to do with Java 15 and Project Loom. In the (new) world of virtual threads, the underlying scheduler would be able to work much better with ReentrantLock than it's able to do with synchronized, that's true at least in the initial Java 15 release but may be optimized later.

In the current Loom implementation, a virtual thread can be pinned in two situations: when there is a native frame on the stack — when Java code calls into native code (JNI) that then calls back into Java — and when inside a synchronized block or method. In those cases, blocking the virtual thread will block the physical thread that carries it. Once the native call completes or the monitor released (the synchronized block/method is exited) the thread is unpinned.

If you have a common I/O operation guarded by a synchronized, replace the monitor with a ReentrantLock to let your application benefit fully from Loom’s scalability boost even before we fix pinning by monitors (or, better yet, use the higher-performance StampedLock if you can).

Can I write or modify data on an RFID tag?

We have recently started looking into RFID solutions at my work place and we found a cheap solution for testing purposes.

One of the units from here:

Plugs into any windows mobile device with an SD slot and allows reading / writing. There is also a development kit to get you on your way with your own apps.

Hope this helps

Cannot start GlassFish 4.1 from within Netbeans 8.0.1 Service area

you can easily resolve this problem by changing the port number of glassfish.

Go to glassfich configuration File domain.xml which is located under GlassFish_Server\glassfish\domains\domain1\config.

Open this file, then change the following line:

<network-listener port="8080" protocol="http-listener-1" transport="tcp" 
name="http-listener-1" thread-pool="http-thread-pool"></network-listener>  

replace 8080 by 9090 for example, then save file and run glassfish again. it should nicely work.

how to convert string into dictionary in python 3.*?

  1. literal_eval, a somewhat safer version of eval (will only evaluate literals ie strings, lists etc):

    from ast import literal_eval
    python_dict = literal_eval("{'a': 1}")
  2. json.loads but it would require your string to use double quotes:

    import json
    python_dict = json.loads('{"a": 1}')

How to get correct timestamp in C#

For UTC:

string unixTimestamp = Convert.ToString((int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds);

For local system:

string unixTimestamp = Convert.ToString((int)DateTime.Now.Subtract(new DateTime(1970, 1, 1)).TotalSeconds);

What is the difference between public, protected, package-private and private in Java?

                | highest precedence <---------> lowest precedence
 \ xCanBeSeenBy | this          | any class | this subclass | any
  \__________   | class         | in same   | in another    | class
             \  | nonsubbed     | package   | package       |    
Modifier of x \ |               |           |               |       
public          |       ?       |     ?     |       ?       |   ?  
protected       |       ?       |     ?     |       ?       |   ?   
package-private |               |           |               |
(no modifier)   |       ?       |     ?     |       ?       |   ?   
private         |       ?       |     ?     |       ?       |   ?    

run main class of Maven project

Although maven exec does the trick here, I found it pretty poor for a real test. While waiting for maven shell, and hoping this could help others, I finally came out to this repo mvnexec

Clone it, and symlink the script somewhere in your path. I use ~/bin/mvnexec, as I have ~/bin in my path. I think mvnexec is a good name for the script, but is up to you to change the symlink...

Launch it from the root of your project, where you can see src and target dirs.

The script search for classes with main method, offering a select to choose one (Example with mavenized JMeld project)

$ mvnexec 
 1) org.jmeld.ui.JMeldComponent
 2) org.jmeld.ui.text.FileDocument
 3) org.jmeld.JMeld
 4) org.jmeld.util.UIDefaultsPrint
 5) org.jmeld.util.PrintProperties
 6) org.jmeld.util.file.DirectoryDiff
 7) org.jmeld.util.file.VersionControlDiff
17) org.jmeld.Main

If one is selected (typing number), you are prompt for arguments (you can avoid with mvnexec -P)

By default it compiles project every run. but you can avoid that using mvnexec -B

It allows to search only in test classes -M or --no-main, or only in main classes -T or --no-test. also has a filter by name option -f <whatever>

Hope this could save you some time, for me it does.

Subset dataframe by multiple logical conditions of rows to remove

data <- data[-which(data[,1] %in% c("b","d","e")),]

What is the equivalent of "!=" in Excel VBA?

In VBA, the != operator is the Not operator, like this:

If Not strTest = "" Then ...

How to name Dockerfiles

Dockerfile (custom name and folder):



   docker build  -f ./docker/app.Dockerfile .
   docker build  -f ./docker/nginx.Dockerfile .

Best practices for copying files with Maven

In order to copy a file use:



In order to copy folder with sub-folders use next configuration:


What is the convention for word separator in Java package names?

Here's what the official naming conventions document prescribes:


The prefix of a unique package name is always written in all-lowercase ASCII letters and should be one of the top-level domain names, currently com, edu, gov, mil, net, org, or one of the English two-letter codes identifying countries as specified in ISO Standard 3166, 1981.

Subsequent components of the package name vary according to an organization's own internal naming conventions. Such conventions might specify that certain directory name components be division, department, project, machine, or login names.


  • com.sun.eng
  • edu.cmu.cs.bovik.cheese


Note that in particular, anything following the top-level domain prefix isn't specified by the above document. The JLS also agrees with this by giving the following examples:

  • com.sun.sunsoft.DOE
  • gov.whitehouse.socks.mousefinder
  • com.JavaSoft.jag.Oak
  • org.npr.pledge.driver

The following excerpt is also relevant:

In some cases, the internet domain name may not be a valid package name. Here are some suggested conventions for dealing with these situations:

  • If the domain name contains a hyphen, or any other special character not allowed in an identifier, convert it into an underscore.
  • If any of the resulting package name components are keywords then append underscore to them.
  • If any of the resulting package name components start with a digit, or any other character that is not allowed as an initial character of an identifier, have an underscore prefixed to the component.


Fast way to discover the row count of a table in PostgreSQL

Counting rows in big tables is known to be slow in PostgreSQL. To get a precise number it has to do a full count of rows due to the nature of MVCC. There is a way to speed this up dramatically if the count does not have to be exact like it seems to be in your case.

Instead of getting the exact count (slow with big tables):

SELECT count(*) AS exact_count FROM myschema.mytable;

You get a close estimate like this (extremely fast):

SELECT reltuples::bigint AS estimate FROM pg_class where relname='mytable';

How close the estimate is depends on whether you run ANALYZE enough. It is usually very close.
See the PostgreSQL Wiki FAQ.
Or the dedicated wiki page for count(*) performance.

Better yet

The article in the PostgreSQL Wiki is was a bit sloppy. It ignored the possibility that there can be multiple tables of the same name in one database - in different schemas. To account for that:

SELECT c.reltuples::bigint AS estimate
FROM   pg_class c
JOIN   pg_namespace n ON n.oid = c.relnamespace
WHERE  c.relname = 'mytable'
AND    n.nspname = 'myschema'

Or better still

SELECT reltuples::bigint AS estimate
FROM   pg_class
WHERE  oid = 'myschema.mytable'::regclass;

Faster, simpler, safer, more elegant. See the manual on Object Identifier Types.

Use to_regclass('myschema.mytable') in Postgres 9.4+ to avoid exceptions for invalid table names:

TABLESAMPLE SYSTEM (n) in Postgres 9.5+

SELECT 100 * count(*) AS estimate FROM mytable TABLESAMPLE SYSTEM (1);

Like @a_horse commented, the newly added clause for the SELECT command might be useful if statistics in pg_class are not current enough for some reason. For example:

  • No autovacuum running.
  • Immediately after a big INSERT or DELETE.
  • TEMPORARY tables (which are not covered by autovacuum).

This only looks at a random n % (1 in the example) selection of blocks and counts rows in it. A bigger sample increases the cost and reduces the error, your pick. Accuracy depends on more factors:

  • Distribution of row size. If a given block happens to hold wider than usual rows, the count is lower than usual etc.
  • Dead tuples or a FILLFACTOR occupy space per block. If unevenly distributed across the table, the estimate may be off.
  • General rounding errors.

In most cases the estimate from pg_class will be faster and more accurate.

Answer to actual question

First, I need to know the number of rows in that table, if the total count is greater than some predefined constant,

And whether it ...

... is possible at the moment the count pass my constant value, it will stop the counting (and not wait to finish the counting to inform the row count is greater).

Yes. You can use a subquery with LIMIT:

SELECT count(*) FROM (SELECT 1 FROM token LIMIT 500000) t;

Postgres actually stops counting beyond the given limit, you get an exact and current count for up to n rows (500000 in the example), and n otherwise. Not nearly as fast as the estimate in pg_class, though.

while installing vc_redist.x64.exe, getting error "Failed to configure per-machine MSU package."

Posting answer to my own question as I found it here and was hidden in bottom somewhere -

This is because the OS failed to install the required update Windows8.1-KB2999226-x64.msu.

However, you can install it by extracting that update to a folder (e.g. XXXX), and execute following cmdlet. You can find the Windows8.1-KB2999226-x64.msu at below.

C:\ProgramData\Package Cache\469A82B09E217DDCF849181A586DF1C97C0C5C85\packages\Patch\amd64\Windows8.1-KB2999226-x64.msu

copy this file to a folder you like, and

Create a folder XXXX in that and execute following commands from Admin command propmt

wusa.exe Windows8.1-KB2999226-x64.msu /extract:XXXX

DISM.exe /Online /Add-Package /PackagePath:XXXX\

vc_redist.x64.exe /repair

(last command need not be run. Just execute vc_redist.x64.exe once again)

this worked for me.

Node.js Hostname/IP doesn't match certificate's altnames

The other way to fix this in other circumstances is to use NODE_TLS_REJECT_UNAUTHORIZED=0 as an environment variable


WARNING: This is a bad idea security-wise

How to filter by string in JSONPath?

Your query looks fine, and your data and query work for me using this JsonPath parser. Also see the example queries on that page for more predicate examples.

The testing tool that you're using seems faulty. Even the examples from the JsonPath site are returning incorrect results:

e.g., given:

            { "category": "reference",
              "author": "Nigel Rees",
              "title": "Sayings of the Century",
              "price": 8.95
            { "category": "fiction",
              "author": "Evelyn Waugh",
              "title": "Sword of Honour",
              "price": 12.99
            { "category": "fiction",
              "author": "Herman Melville",
              "title": "Moby Dick",
              "isbn": "0-553-21311-3",
              "price": 8.99
            { "category": "fiction",
              "author": "J. R. R. Tolkien",
              "title": "The Lord of the Rings",
              "isbn": "0-395-19395-8",
              "price": 22.99
            "color": "red",
            "price": 19.95

And the expression: $[?(@.length-1)].title, the tool returns a list of all titles.

Working with SQL views in Entity Framework Core

In Entity Framework Core 2.1 we can use Query Types as Yuriy N suggested.

A more detailed article on how to use them can be found here

The most straight forward approach according to the article's examples would be:

1.We have for example the following entity Models to manage publications

public class Magazine
  public int MagazineId { get; set; }
  public string Name { get; set; }
  public string Publisher { get; set; }
  public List<Article> Articles { get; set; }

public class Article
  public int ArticleId { get; set; }
  public string Title { get; set; }
  public int MagazineId { get; set; }
  public DateTime PublishDate { get;  set; }
  public Author Author { get; set; }
  public int AuthorId { get; set; }
public class Author
  public int AuthorId { get; set; }
  public string Name { get; set; }
  public List<Article> Articles { get; set; }

2.We have a view called AuthorArticleCounts, defined to return the name and number of articles an author has written

  Count(r.ArticleId) as ArticleCount
from Authors a
  JOIN Articles r on r.AuthorId = a.AuthorId
GROUP BY a.AuthorName

3.We go and create a model to be used for the View

public class AuthorArticleCount
  public string AuthorName { get; private set; }
  public int ArticleCount { get; private set; }

4.We create after that a DbQuery property in my DbContext to consume the view results inside the Model

public DbQuery<AuthorArticleCount> AuthorArticleCounts{get;set;}

4.1. You might need to override OnModelCreating() and set up the View especially if you have different view name than your Class.

protected override void OnModelCreating(ModelBuilder modelBuilder)

5.Finally we can easily get the results of the View like this.

var results=_context.AuthorArticleCounts.ToList();

UPDATE According to ssougnez's comment

It's worth noting that DbQuery won't be/is not supported anymore in EF Core 3.0. See here

A required class was missing while executing org.apache.maven.plugins:maven-war-plugin:2.1.1:war

Faced the same issue and resolved by upgrading my Maven from 3.0.4 to 3.1.1. Please try with v3.1.1 or any higher version if available

set the iframe height automatically

Try this coding

    <iframe id='iframe2' src="Mypage.aspx" frameborder="0" style="overflow: hidden; height: 100%;
        width: 100%; position: absolute;"></iframe>

How to connect TFS in Visual Studio code

Just as Daniel said "Git and TFVC are the two source control options in TFS". Fortunately both are supported for now in VS Code.

You need to install the Azure Repos Extension for Visual Studio Code. The process of installing is pretty straight forward.

  1. Search for Azure Repos in VS Code and select to install the one by Microsoft
  2. Open File -> Preferences -> Settings
  3. Add the following lines to your user settings

    If you have VS 2015 installed on your machine, your path to Team Foundation tool (tf.exe) may look like this:

        "tfvc.location": "C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\Common7\\IDE\\tf.exe",
        "tfvc.restrictWorkspace": true

    Or for VS 2017:

        "tfvc.location": "C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\Enterprise\\Common7\\IDE\\CommonExtensions\\Microsoft\\TeamFoundation\\Team Explorer\\tf.exe",
        "tfvc.restrictWorkspace": true
  4. Open a local folder (repository), From View -> Command Pallette ..., type team signin

  5. Provide user name --> Enter --> Provide password to connect to TFS.

Please refer to below links for more details:

Note that Server Workspaces are not supported:

"TFVC support is limited to Local workspaces":

on installing Azure extension, visual studio code warns you "It appears you are using a Server workspace. Currently, TFVC support is limited to Local workspaces"

python: sys is not defined

I'm guessing your code failed BEFORE import sys, so it can't find it when you handle the exception.

Also, you should indent the your code whithin the try block.


import sys
# .. other safe imports
    import numpy as np
    # other unsafe imports
except ImportError:
    print "Error: missing one of the libraries (numpy, pyfits, scipy, matplotlib)"

Determine Whether Integer Is Between Two Other Integers?

There are two ways to compare three integers and check whether b is between a and c:

if a < b < c:


if a < b and b < c:

The first one looks like more readable, but the second one runs faster.

Let's compare using dis.dis:

>>> dis.dis('a < b and b < c')
  1           0 LOAD_NAME                0 (a)
              2 LOAD_NAME                1 (b)
              4 COMPARE_OP               0 (<)
              6 JUMP_IF_FALSE_OR_POP    14
              8 LOAD_NAME                1 (b)
             10 LOAD_NAME                2 (c)
             12 COMPARE_OP               0 (<)
        >>   14 RETURN_VALUE
>>> dis.dis('a < b < c')
  1           0 LOAD_NAME                0 (a)
              2 LOAD_NAME                1 (b)
              4 DUP_TOP
              6 ROT_THREE
              8 COMPARE_OP               0 (<)
             10 JUMP_IF_FALSE_OR_POP    18
             12 LOAD_NAME                2 (c)
             14 COMPARE_OP               0 (<)
             16 RETURN_VALUE
        >>   18 ROT_TWO
             20 POP_TOP
             22 RETURN_VALUE

and using timeit:

~$ python3 -m timeit "1 < 2 and 2 < 3"
10000000 loops, best of 3: 0.0366 usec per loop

~$ python3 -m timeit "1 < 2 < 3"
10000000 loops, best of 3: 0.0396 usec per loop

also, you may use range, as suggested before, however it is much more slower.

Select All as default value for Multivalue parameter

This is rather easy to achieve by making a dataset with a text-query like this:

SELECT 'Item1'
SELECT 'Item2'
SELECT 'Item3'
SELECT 'Item4'

The query should return all items that can be selected.

How do I load the contents of a text file into a javascript variable?

When working with jQuery, instead of using jQuery.get, e.g.

jQuery.get("foo.txt", undefined, function(data) {
}, "html").done(function() {
    alert("second success");
}).fail(function(jqXHR, textStatus) {
}).always(function() {

you could use .load which gives you a much more condensed form:


.load gives you also the option to load partial pages which can come in handy, see

Error: 'int' object is not subscriptable - Python

It would be a lot more simple just to do this;

name = input("What's your name? ")
age = int(input("How old are you? "))
print ("Hi,{0} you will be 21 in {1} years.".format(name, 21 - age))`

blur() vs. onblur()



works because your element (the <input>) has an attribute called "onblur" whose value is a function. Thus, you can call it. You're not telling the browser to simulate the actual "blur" event, however; there's no event object created, for example.

Elements do not have a "blur" attribute (or "method" or whatever), so that's why the first thing doesn't work.

How to assign name for a screen?

I am a beginner to screen but I find it immensely useful while restoring lost connections. Your question has already been answered but this information might serve as an add on - I use putty with putty connection manager and name my screens - "tab1", "tab2", etc. - as for me the overall picture of the 8-10 tabs is more important than each individual tab name. I use the 8th tab for connecting to db, the 7th for viewing logs, etc. So when I want to reattach my screens I have written a simple wrapper which says:

screen -d -r tab$1

where first argument is the tab number.

How to access PHP session variables from jQuery function in a .js file?

Strangely importing directly from $_SESSION not working but have to do this to make it work :

$phpVar = $_SESSION['var'];

    var variableValue= '<?php echo $phpVar; ?>';
    var imported = document.createElement('script');
    imported.src = './your/path/to.js';

and in to.js

// rest of js file

How to pass a datetime parameter?

By looking at your code, I assume you do not have a concern about the 'Time' of the DateTime object. If so, you can pass the date, month and the year as integer parameters. Please see the following code. This is a working example from my current project.

The advantage is; this method helps me to avoid DateTime format issues and culture incompatibilities.

    /// <summary>
    /// Get Arrivals Report Seven Day Forecast
    /// </summary>
    /// <param name="day"></param>
    /// <param name="month"></param>
    /// <param name="year"></param>
    /// <returns></returns>
    public async Task<ActionResult<List<ArrivalsReportSevenDayForecastModel>>> GetArrivalsReportSevenDayForecast(int day, int month, int year)
        DateTime selectedDate = new DateTime(year, month, day);
        IList<ArrivalsReportSevenDayForecastModel> arrivingStudents = await _applicationService.Value.GetArrivalsReportSevenDayForecast(selectedDate);
        return Ok(arrivingStudents);

If you are keen to see the front-end as well, feel free to read the code below. Unfortunately, that is written in Angular. This is how I normally pass a DateTime as a query parameter in Angular GET requests.

public getArrivalsReportSevenDayForecast(selectedDate1 : Date): Observable<ArrivalsReportSevenDayForecastModel[]> {
const params = new HttpParams();
const day = selectedDate1.getDate();
const month = selectedDate1.getMonth() + 1
const year = selectedDate1.getFullYear();

const data = this.svcHttp.get<ArrivalsReportSevenDayForecastModel[]>(this.routePrefix +
  `/arrivalreportsevendayforecast/${day}/${month}/${year}`, { params: params }).pipe(
  map<ArrivalsReportSevenDayForecastModel[], ArrivalsReportSevenDayForecastModel[]>(arrivingList => {
    // do mapping here if needed       
    return arrivingList;
  catchError((err) => this.svcError.handleError(err)));

return data;

Bash scripting missing ']'


if [ -s "p1"];  #line 13


if [ -s "p1" ];  #line 13

note the space.

Is there a way to specify which pytest tests to run from a file?

You can use -k option to run test cases with different patterns:

py.test tests_directory/ tests_directory/ -k 'test_001 or test_some_other_test'

This will run test cases with name test_001 and test_some_other_test deselecting the rest of the test cases.

Note: This will select any test case starting with test_001 or test_some_other_test. For example, if you have test case test_0012 it will also be selected.

How do I sort a two-dimensional (rectangular) array in C#?

This is an old question, but here's a class I just built based on the article from Jim Mischel at InformIt linked by Doug L.

class Array2DSort : IComparer<int>
    // maintain a reference to the 2-dimensional array being sorted
    string[,] _sortArray;
    int[] _tagArray;
    int _sortIndex;

    protected string[,] SortArray { get { return _sortArray; } }

    // constructor initializes the sortArray reference
    public Array2DSort(string[,] theArray, int sortIndex)
        _sortArray = theArray;
        _tagArray = new int[_sortArray.GetLength(0)];
        for (int i = 0; i < _sortArray.GetLength(0); ++i) _tagArray[i] = i;
        _sortIndex = sortIndex;

    public string[,] ToSortedArray()
        Array.Sort(_tagArray, this);
        string[,] result = new string[
            _sortArray.GetLength(0), _sortArray.GetLength(1)];
        for (int i = 0; i < _sortArray.GetLength(0); i++)
            for (int j = 0; j < _sortArray.GetLength(1); j++)
                result[i, j] = _sortArray[_tagArray[i], j];
        return result;

    // x and y are integer row numbers into the sortArray
    public virtual int Compare(int x, int y)
        if (_sortIndex < 0) return 0;
        return CompareStrings(x, y, _sortIndex);

    protected int CompareStrings(int x, int y, int col)
        return _sortArray[x, col].CompareTo(_sortArray[y, col]);

Given an unsorted 2D array data of arbitrary size that you want to sort on column 5 you just do this:

        Array2DSort comparer = new Array2DSort(data, 5);
        string[,] sortedData = comparer.ToSortedArray();

Note the virtual Compare method and protected SortArray so you can create specialized subclasses that always sort on a particular column or do specialized sorting on multiple columns or whatever you want to do. That's also why CompareStrings is broken out and protected - any subclasses can use it for simple comparisons instead of typing out the full SortArray[x, col].CompareTo(SortArray[y, col]) syntax.

How to get access to raw resources that I put in res folder?

InputStream raw = context.getAssets().open("filename.ext");

Reader is = new BufferedReader(new InputStreamReader(raw, "UTF8"));

Failed to resolve: in IntelliJ Idea with gradle

this is probably about you don't entered correct dependency version. you can select correct dependency from this:

file>menu>project structure>app>dependencies>+>Library Dependency>select any thing you need > OK

if cannot find your needs you should update your sdk from below way:

tools>android>sdk manager>sdk update>select any thing you need>ok

Wildcards in a Windows hosts file

I could not find a prohibition in writing, but by convention, the Windows hosts file closely follows the UNIX hosts file, and you cannot put wildcard hostname references into that file.

If you read the man page, it says:

     The hosts file contains information regarding the known hosts on the net-
     work.  For each host a single line should be present with the following

           Internet address
           Official host name

Although it does say,

     Host names may contain any printable character other than a field delim-
     iter, newline, or comment character.

that is not true from a practical level.

Basically, the code that looks at the /etc/hosts file does not support a wildcard entry.

The workaround is to create all the entries in advance, maybe use a script to put a couple hundred entries at once.

How to install sshpass on mac?

There are instructions on how to install sshpass here:

For Mac you will need to install xcode and command line tools then use the unofficial Homewbrew command:

brew install

Python extract pattern matches

Maybe that's a bit shorter and easier to understand:

import re
text = '... someline abc... someother line... name my_user_name is valid.. some more lines'
>>>'name (.*) is valid', text).group(1)

Set Background color programmatically

I didn't understand your question ... what do you mean by "when i set every one of my colour"? try this (edit: "#fffff" in original answer changed to "#ffffff"


How to iterate std::set?

One more thing that might be useful for beginners is , since std::set is not allocated with contiguous memory chunks , if someone want to iterate till kth element normal way will not work. example:

std::vector<int > vec{1,2,3,4,5};
int k=3;
for(auto itr=vec.begin();itr<vec.begin()+k;itr++) cout<<*itr<<" ";

std::unordered_set<int > s{1,2,3,4,5};
int k=3;
int index=0;
auto itr=s.begin();
   if(index==k) break;
   cout<<*itr++<<" ";

Check mySQL version on Mac 10.8.5

To check your MySQL version on your mac, navigate to the directory where you installed it (default is usr/local/mysql/bin) and issue this command:

./mysql --version

Alternatively, to avoid needing to navigate to that specific dir to run the command, add its location to your path ($PATH). There's more than one way to add a dir to your $PATH (with explanations on stackoverflow and other places on how to do so), such as adding it to your ./bash_profile.

After adding the mysql bin dir to your $PATH, verify it's there by executing:

echo $PATH

Thereafter you can check your mysql version from anywhere by running (note no "./"):

mysql --version

"static const" vs "#define" vs "enum"

#define var 5 will cause you trouble if you have things like mystruct.var.

For example,

struct mystruct {
    int var;

#define var 5

int main() {
    struct mystruct foo;
    foo.var = 1;
    return 0;

The preprocessor will replace it and the code won't compile. For this reason, traditional coding style suggest all constant #defines uses capital letters to avoid conflict.

How to code a modulo (%) operator in C/C++/Obj-C that handles negative numbers

I would do:

((-1)+8) % 8 

This adds the latter number to the first before doing the modulo giving 7 as desired. This should work for any number down to -8. For -9 add 2*8.

Find oldest/youngest datetime object in a list


oldest = min(datetimes)

Youngest before now:

now =
youngest = max(dt for dt in datetimes if dt < now)

Remove rows with all or some NAs (missing values) in data.frame

Another option if you want greater control over how rows are deemed to be invalid is

final <- final[!($rnor)) | !($cfam)),]

Using the above, this:

             gene hsap mmul mmus rnor cfam
1 ENSG00000208234    0   NA   NA   NA   2
2 ENSG00000199674    0   2    2    2    2
3 ENSG00000221622    0   NA   NA   2   NA
4 ENSG00000207604    0   NA   NA   1    2
5 ENSG00000207431    0   NA   NA   NA   NA
6 ENSG00000221312    0   1    2    3    2


             gene hsap mmul mmus rnor cfam
1 ENSG00000208234    0   NA   NA   NA   2
2 ENSG00000199674    0   2    2    2    2
3 ENSG00000221622    0   NA   NA   2   NA
4 ENSG00000207604    0   NA   NA   1    2
6 ENSG00000221312    0   1    2    3    2

...where only row 5 is removed since it is the only row containing NAs for both rnor AND cfam. The boolean logic can then be changed to fit specific requirements.

Plot multiple columns on the same graph in R

A very simple solution:

df <- read.csv("df.csv",sep=",",head=T)
x <- cbind(df$Xax,df$Xax,df$Xax,df$Xax)
y <- cbind(df$A,df$B,df$C,df$D)

please note it just plots the data and it does not plot any regression line.

nginx: send all requests to a single html page

I think this will do it for you:

location / {
    try_files /base.html =404;

Align printf output in Java

Format specifications for printf and printf-like methods take an optional width parameter.

System.out.printf( "%10d. %25s $%25.2f\n",
                   i + 1, BOOK_TYPE[i], COST[i] );

Adjust widths to desired values.

c++ array - expression must have a constant value

one could also use a fixed lengths vector and access it with indexing

int Lcs(string a, string b) 
    int x = a.size() + 1;
    int y = b.size() + 1;

    vector<vector<int>> L(x, vector<int>(y));

    for (int i = 1; i < x; i++)
        for (int j = 1; j < y; j++)
            L[i][j] = a[i - 1] == b[j - 1] ?
                L[i - 1][j - 1] + 1 :
                max(L[i - 1][j], L[i][j - 1]);

    return L[a.size()][b.size()];

How to auto-scroll to end of div when data is added?

If you don't know when data will be added to #data, you could set an interval to update the element's scrollTop to its scrollHeight every couple of seconds. If you are controlling when data is added, just call the internal of the following function after the data has been added.

window.setInterval(function() {
  var elem = document.getElementById('data');
  elem.scrollTop = elem.scrollHeight;
}, 5000);

How to close jQuery Dialog within the dialog?


Simple, I like to make sure I don't:

  1. hardcode dialog #id values.
  2. Close all dialogs.


Inner Join

The join that displays only the rows that have a match in both the joined tables is known as inner join. This is default join in the query and view Designer.

Syntax for Inner Join

SELECT t1.column_name,t2.column_name
FROM table_name1 t1
INNER JOIN table_name2 t2
ON t1.column_name=t2.column_name

Cross Join

A cross join that produces Cartesian product of the tables that involved in the join. The size of a Cartesian product is the number of the rows in first table multiplied by the number of rows in the second table.

Syntax for Cross Join

SELECT * FROM table_name1
CROSS JOIN table_name2

Or we can write it in another way also

SELECT * FROM table_name1,table_name2

Now check the query below for Cross join


SELECT * FROM UserDetails
CROSS JOIN OrderDetails


SELECT * FROM UserDetails, OrderDetails

how do I create an infinite loop in JavaScript

By omitting all parts of the head, the loop can also become infinite:

for (;;) {}

Why shouldn't I use "Hungarian Notation"?

For years I used Hungarian notation in my programming. Other than some visual clutter and the task of changing the prefix when I changed the data type, no one could convince me otherwise. Until recently--when I had to combine existing C# and VB.NET assemblies in the same solution.

The result: I had to pass a "fltSomeVariable" to a "sngSomeVariable" method parameter. Even as someone who programs in both C# and VB.NET, it caught me off guard and made me pause for a moment. (C# and VB.NET sometimes use different names to represent the same data type--float and single, for example.)

Now consider this: what if you create a COM component that's callable from many languages? The VB.NET and C# "conversion" was easy for a .NET programmer. But what about someone that develops in C++ or Java? Does "dwSomeVariable" mean anything to a .NET developer not familiar with C++?

Open URL in Java to get the content

String url_open ="";

milliseconds to days

public static final long SECOND_IN_MILLIS = 1000;
public static final long MINUTE_IN_MILLIS = SECOND_IN_MILLIS * 60;
public static final long HOUR_IN_MILLIS = MINUTE_IN_MILLIS * 60;
public static final long DAY_IN_MILLIS = HOUR_IN_MILLIS * 24;
public static final long WEEK_IN_MILLIS = DAY_IN_MILLIS * 7;

You could cast int but I would recommend using long.

How do I remove a library from the arduino environment?

The answer is only valid if you have not changed the "Sketchbook Location" field in Preferences. So, first, you need to open the Arduino IDE and go to the menu

"File -> Preferences"

In the dialog, look at the field "Sketchbook Location" and open the corresponding folder. The "libraries" folder in inside.

Android: Color To Int conversion

Paint DOES have set color function.

 * Set the paint's color. Note that the color is an int containing alpha
 * as well as r,g,b. This 32bit value is not premultiplied, meaning that
 * its alpha can be any value, regardless of the values of r,g,b.
 * See the Color class for more details.
 * @param color The new color (including alpha) to set in the paint.
public native void setColor(@ColorInt int color);

As an Android developer, I set paint color like this...


I define the color value on color.xml something like...

<color name="xxx">#008fd2</color>

By the way if you want to the hex RGB value of specific color value, then you can check website like this:

I hope this helps ! Enjoy coding!

How to preSelect an html dropdown list with php?

This answer is not relevant for particular recepient, but maybe useful for others. I had similiar issue with 'selecting' right 'option' by value returned from database. I solved it by adding additional tag with applied display:none.

$status =  "NOT_ON_LIST";

$text = "<html>
<select id=\"statuses\">
   <option value=\"status\" selected=\"selected\" style=\"display:none\">$status</option>
   <option value=\"status\">OK</option>
   <option value=\"status\">DOWN</option>
   <option value=\"status\">UNKNOWN</option>

print $text;

How to configure Spring Security to allow Swagger URL to be accessed without authentication

For those who using a newer swagger 3 version org.springdoc:springdoc-openapi-ui

public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/v3/api-docs/**", "/swagger-ui.html", "/swagger-ui/**");

Specified cast is not valid.. how to resolve this

Use Convert.ToDouble(value) rather than (double)value. It takes an object and supports all of the types you asked for! :)

Also, your method is always returning a string in the code above; I'd recommend having the method indicate so, and give it a more obvious name (public string FormatLargeNumber(object value))