Programs & Examples On #Hclust

R function from {stats} package - hierarchical cluster analysis on a set of dissimilarities and methods for analyzing it.

Python - abs vs fabs

math.fabs() always returns float, while abs() may return integer.

Why catch and rethrow an exception in C#?

It depends what you are doing in the catch block, and if you are wanting to pass the error on to the calling code or not.

You might say Catch io.FileNotFoundExeption ex and then use an alternative file path or some such, but still throw the error on.

Also doing Throw instead of Throw Ex allows you to keep the full stack trace. Throw ex restarts the stack trace from the throw statement (I hope that makes sense).

How to specify font attributes for all elements on an html web page?

you can set them in the body tag

body
{
    font-size:xxx;
    font-family:yyyy;
}

Using moment.js to convert date to string "MM/dd/yyyy"

Try this:

var momentObj = $("#start_ts").datepicker("getDate");

var yourDate = momentObj.format('L');

NullPointerException in Java with no StackTrace

toString() only returns the exception name and the optional message. I would suggest calling

exception.printStackTrace()

to dump the message, or if you need the gory details:

 StackTraceElement[] trace = exception.getStackTrace()

Find out if string ends with another string in C++

Let a be a string and b the string you look for. Use a.substr to get the last n characters of a and compare them to b (where n is the length of b)

Or use std::equal (include <algorithm>)

Ex:

bool EndsWith(const string& a, const string& b) {
    if (b.size() > a.size()) return false;
    return std::equal(a.begin() + a.size() - b.size(), a.end(), b.begin());
}

Find all files with a filename beginning with a specified string?

ls | grep "^abc"  

will give you all files beginning (which is what the OP specifically required) with the substringabc.
It operates only on the current directory whereas find operates recursively into sub folders.

To use find for only files starting with your string try

find . -name 'abc'*

Kendo grid date column not formatting

I found this piece of information and got it to work correctly. The data given to me was in string format so I needed to parse the string using kendo.parseDate before formatting it with kendo.toString.

columns: [
    {
        field: "FirstName",
        title: "FIRST NAME"
    },
    {
        field: "LastName",
        title: "LAST NAME"
    },
    {
        field: "DateOfBirth",
        title: "DATE OF BIRTH",
        template: "#= kendo.toString(kendo.parseDate(DateOfBirth, 'yyyy-MM-dd'), 'MM/dd/yyyy') #"
    },
...


References:

  1. format-date-in-grid
  2. jsfiddle
  3. kendo ui date formatting

VB.Net .Clear() or txtbox.Text = "" textbox clear methods

Public Sub EmptyTxt(ByVal Frm As Form)
    Dim Ctl As Control
    For Each Ctl In Frm.Controls
        If TypeOf Ctl Is TextBox Then Ctl.Text = ""
        If TypeOf Ctl Is GroupBox Then
            Dim Ctl1 As Control
            For Each Ctl1 In Ctl.Controls
                If TypeOf Ctl1 Is TextBox Then
                    Ctl1.Text = ""
                End If
            Next
        End If
    Next
End Sub

add this code in form and call this function

EmptyTxt(Me)

Finish an activity from another activity

I know this is an old question, a few of these methods didn't work for me so for anyone looking in the future or having my troubles this worked for me

I overrode onPause and called finish() inside that method.

Getting the WordPress Post ID of current post

In some cases, such as when you're outside The Loop, you may need to use get_queried_object_id() instead of get_the_ID().

$postID = get_queried_object_id();

Is it possible to modify a registry entry via a .bat/.cmd script?

Yes. You can use reg.exe which comes with the OS to add, delete or query registry values. Reg.exe does not have an explicit modify command, but you can do it by doing delete and then add.

C# how to wait for a webpage to finish loading before continuing

I think the DocumentCompleted event of the WebBrowser control should get you where you need to go.

Difference between signature versions - V1 (Jar Signature) and V2 (Full APK Signature) while generating a signed APK in Android Studio?

Should I use(or both) for signing apk for play store release? An answer is YES.

As per https://source.android.com/security/apksigning/v2.html#verification :

In Android 7.0, APKs can be verified according to the APK Signature Scheme v2 (v2 scheme) or JAR signing (v1 scheme). Older platforms ignore v2 signatures and only verify v1 signatures.

I tried to generate build with checking V2(Full Apk Signature) option. Then when I tried to install a release build in below 7.0 device and I am unable to install build in the device.

After that I tried to build by checking both version checkbox and generate release build. Then able to install build.

Could not find com.android.tools.build:gradle:3.0.0-alpha1 in circle ci

mtrakal's solution worked fine.

Added to gradle.build:

buildscript {
    repositories {
        maven { url 'https://maven.google.com' }
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-alpha2'

        // NOTE: Do not place your application dependencies here; 
        // they belong in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

Then it automatically upgraded to alpha2.

Invalidate the caches and restarted all is fine.

File | Invalidate Caches / Restart

choose 'Invalidate & Restart'

MVC - Set selected value of SelectList

Further to @Womp answer, it's worth noting that the "Where" Can be dropped, and the predicate can be put into the "First" call directly, like this:

list.First(x => x.Value == "selectedValue").Selected = true;

What is (functional) reactive programming?

I found this nice video on the Clojure subreddit about FRP. It is pretty easy to understand even if you don't know Clojure.

Here's the video: http://www.youtube.com/watch?v=nket0K1RXU4

Here's the source the video refers to in the 2nd half: https://github.com/Cicayda/yolk-examples/blob/master/src/yolk_examples/client/autocomplete.cljs

Android Stop Emulator from Command Line

Sometimes the command

adb -s emulator-5554 emu kill

did not work on my CI servers or desktops, for unknown reason. I think on Windows it's OK to kill the process of qemu, just like

Taskkill /IM qemu-system-x86_64.exe /F /T

Datetime format Issue: String was not recognized as a valid DateTime

Your date time string doesn't contains any seconds. You need to reflect that in your format (remove the :ss).
Also, you need to specify H instead of h if you are using 24 hour times:

DateTime.ParseExact("04/30/2013 23:00", "MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture)

See here for more information:

Custom Date and Time Format Strings

Calculate days between two Dates in Java 8

If the goal is just to get the difference in days and since the above answers mention about delegate methods would like to point out that once can also simply use -

public long daysInBetween(java.time.LocalDate startDate, java.time.LocalDate endDate) {
  // Check for null values here

  return endDate.toEpochDay() - startDate.toEpochDay();
}

How to make bootstrap 3 fluid layout without horizontal scrollbar

This worked for me. Tested in FF, Chrome, IE11, IE10

.row {
    width:99.99%;
}

What is Bit Masking?

Masking means to keep/change/remove a desired part of information. Lets see an image-masking operation; like- this masking operation is removing any thing that is not skin-

enter image description here

We are doing AND operation in this example. There are also other masking operators- OR, XOR.


Bit-Masking means imposing mask over bits. Here is a bit-masking with AND-

     1 1 1 0 1 1 0 1   [input]
(&)  0 0 1 1 1 1 0 0    [mask]
------------------------------
     0 0 1 0 1 1 0 0  [output]

So, only the middle 4 bits (as these bits are 1 in this mask) remain.

Lets see this with XOR-

     1 1 1 0 1 1 0 1   [input]
(^)  0 0 1 1 1 1 0 0    [mask]
------------------------------
     1 1 0 1 0 0 0 1  [output]

Now, the middle 4 bits are flipped (1 became 0, 0 became 1).


So, using bit-mask we can access individual bits [examples]. Sometimes, this technique may also be used for improving performance. Take this for example-

bool isOdd(int i) {
    return i%2;
}

This function tells if an integer is odd/even. We can achieve the same result with more efficiency using bit-mask-

bool isOdd(int i) {
    return i&1;
}

Short Explanation: If the least significant bit of a binary number is 1 then it is odd; for 0 it will be even. So, by doing AND with 1 we are removing all other bits except for the least significant bit i.e.:

     55  ->  0 0 1 1 0 1 1 1   [input]
(&)   1  ->  0 0 0 0 0 0 0 1    [mask]
---------------------------------------
      1  <-  0 0 0 0 0 0 0 1  [output]

What is a bus error?

I was getting a bus error when the root directory was at 100%.

How can I return an empty IEnumerable?

public IEnumerable<Friend> FindFriends()
{
    return userExists ? doc.Descendants("user").Select(user => new Friend
        {
            ID = user.Element("id").Value,
            Name = user.Element("name").Value,
            URL = user.Element("url").Value,
            Photo = user.Element("photo").Value
        }): new List<Friend>();
}

How to return a 200 HTTP Status Code from ASP.NET MVC 3 controller

In your controller you'd return an HttpStatusCodeResult like this...

[HttpPost]
public ActionResult SomeMethod(...your method parameters go here...)
{
   // todo: put your processing code here

   //If not using MVC5
   return new HttpStatusCodeResult(200);

   //If using MVC5
   return new HttpStatusCodeResult(HttpStatusCode.OK);  // OK = 200
}

How to do case insensitive string comparison?

Since no answer clearly provided a simple code snippet for using RegExp, here's my attempt:

function compareInsensitive(str1, str2){ 
  return typeof str1 === 'string' && 
    typeof str2 === 'string' && 
    new RegExp("^" + str1.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') + "$", "i").test(str2);
}

It has several advantages:

  1. Verifies parameter type (any non-string parameter, like undefined for example, would crash an expression like str1.toUpperCase()).
  2. Does not suffer from possible internationalization issues.
  3. Escapes the RegExp string.

How to check if a string array contains one string in JavaScript?

This will do it for you:

function inArray(needle, haystack) {
    var length = haystack.length;
    for(var i = 0; i < length; i++) {
        if(haystack[i] == needle)
            return true;
    }
    return false;
}

I found it in Stack Overflow question JavaScript equivalent of PHP's in_array().

unix diff side-to-side results?

From man diff, you can use -y to do side-by-side.

-y, --side-by-side
       output in two columns

Hence, say:

diff -y /tmp/test1  /tmp/test2

Test

$ cat a                $ cat b
hello                  hello
my name                my name
is me                  is you

Let's compare them:

$ diff -y a b
hello                                                           hello
my name                                                         my name
is me                                                         | is you

How to save a pandas DataFrame table as a png

The easiest and fastest way to convert a Pandas dataframe into a png image using Anaconda Spyder IDE- just double-click on the dataframe in variable explorer, and the IDE table will appear, nicely packaged with automatic formatting and color scheme. Just use a snipping tool to capture the table for use in your reports, saved as a png:

2020 Blue Chip Ratio

This saves me lots of time, and is still elegant and professional.

"Bitmap too large to be uploaded into a texture"

As pointed by Larcho, starting from API level 10, you can use BitmapRegionDecoder to load specific regions from an image and with that, you can accomplish to show a large image in high resolution by allocating in memory just the needed regions. I've recently developed a lib that provides the visualisation of large images with touch gesture handling. The source code and samples are available here.

How to add java plugin for Firefox on Linux?

Do you want the JDK or the JRE? Anyways, I had this problem too, a few weeks ago. I followed the instructions here and it worked:

http://www.backtrack-linux.org/wiki/index.php/Java_Install

NOTE: Before installing Java make sure you kill Firefox.

root@bt:~# killall -9 /opt/firefox/firefox-bin

You can download java from the official website. (Download tar.gz version)

We first create the directory and place java there:

root@bt:~# mkdir /opt/java

root@bt:~# mv -f jre1.7.0_05/ /opt/java/

Final changes.

root@bt:~# update-alternatives --install /usr/bin/java java /opt/java/jre1.7.0_05/bin/java 1

root@bt:~# update-alternatives --set java /opt/java/jre1.7.0_05/bin/java

root@bt:~# export JAVA_HOME="/opt/java/jre1.7.0_05"

Adding the plugin to Firefox.

For Java 7 (32 bit)

root@bt:~# ln -sf $JAVA_HOME/lib/i386/libnpjp2.so /usr/lib/mozilla/plugins/

For Java 8 (64 bit)

root@bt:~# ln -sf $JAVA_HOME/jre/lib/amd64/libnpjp2.so /usr/lib/mozilla/plugins/

Testing the plugin.

root@bt:~# firefox http://java.com/en/download/testjava.jsp

MySQL - SELECT all columns WHERE one column is DISTINCT

  SELECT OTHER_COLUMNS FROM posted WHERE link in (
  SELECT DISTINCT link FROM posted WHERE ad='$key' )
  ORDER BY day, month

In c++ what does a tilde "~" before a function name signify?

It's the destructor. This method is called when the instance of your class is destroyed:

Stack<int> *stack= new Stack<int>;
//do something
delete stack; //<- destructor is called here;

How to continue the code on the next line in VBA

(i, j, n + 1) = k * b_xyt(xi, yi, tn) / (4 * hx * hy) * U_matrix(i + 1, j + 1, n) + _
(k * (a_xyt(xi, yi, tn) / hx ^ 2 + d_xyt(xi, yi, tn) / (2 * hx)))

From ms support

To continue a statement from one line to the next, type a space followed by the line-continuation character [the underscore character on your keyboard (_)].

You can break a line at an operator, list separator, or period.

Isn't the size of character in Java 2 bytes?

A char represents a character in Java (*). It is 2 bytes large (at least that's what the valid value range suggests).

That doesn't necessarily mean that every representation of a character is 2 bytes long. In fact many encodings only reserve 1 byte for every character (or use 1 byte for the most common characters).

When you call the String(byte[]) constructor you ask Java to convert the byte[] to a String using the platform default encoding. Since the platform default encoding is usually a 1-byte encoding such as ISO-8859-1 or a variable-length encoding such as UTF-8, it can easily convert that 1 byte to a single character.

If you run that code on a platform that uses UTF-16 (or UTF-32 or UCS-2 or UCS-4 or ...) as the platform default encoding, then you will not get a valid result (you'll get a String containing the Unicode Replacement Character instead).

That's one of the reasons why you should not depend on the platform default encoding: when converting between byte[] and char[]/String or between InputStream and Reader or between OutputStream and Writer, you should always specify which encoding you want to use. If you don't, then your code will be platform-dependent.

(*) that's not entirely true: a char represents a UTF-16 codepoint. Either one or two UTF-16 codepoints represent a Unicode codepoint. A Unicode codepoint usually represents a character, but sometimes multiple Unicode codepoints are used to make up a single character. But the approximation above is close enough to discuss the topic at hand.

How to run a C# application at Windows startup?

for WPF: (where lblInfo is a label, chkRun is a checkBox)

this.Topmost is just to keep my app on the top of other windows, you will also need to add a using statement " using Microsoft.Win32; ", StartupWithWindows is my application's name

public partial class MainWindow : Window
    {
        // The path to the key where Windows looks for startup applications
        RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);

        public MainWindow()
        {
            InitializeComponent();
            if (this.IsFocused)
            {
                this.Topmost = true;
            }
            else
            {
                this.Topmost = false;
            }

            // Check to see the current state (running at startup or not)
            if (rkApp.GetValue("StartupWithWindows") == null)
            {
                // The value doesn't exist, the application is not set to run at startup, Check box
                chkRun.IsChecked = false;
                lblInfo.Content = "The application doesn't run at startup";
            }
            else
            {
                // The value exists, the application is set to run at startup
                chkRun.IsChecked = true;
                lblInfo.Content = "The application runs at startup";
            }
            //Run at startup
            //rkApp.SetValue("StartupWithWindows",System.Reflection.Assembly.GetExecutingAssembly().Location);

            // Remove the value from the registry so that the application doesn't start
            //rkApp.DeleteValue("StartupWithWindows", false);

        }

        private void btnConfirm_Click(object sender, RoutedEventArgs e)
        {
            if ((bool)chkRun.IsChecked)
            {
                // Add the value in the registry so that the application runs at startup
                rkApp.SetValue("StartupWithWindows", System.Reflection.Assembly.GetExecutingAssembly().Location);
                lblInfo.Content = "The application will run at startup";
            }
            else
            {
                // Remove the value from the registry so that the application doesn't start
                rkApp.DeleteValue("StartupWithWindows", false);
                lblInfo.Content = "The application will not run at startup";
            }
        }

    }

Set value to an entire column of a pandas dataframe

I had a similar issue before even with this approach df.loc[:,'industry'] = 'yyy', but once I refreshed the notebook, it ran well.

You may want to try refreshing the cells after you have df.loc[:,'industry'] = 'yyy'.

How do I horizontally center an absolute positioned element inside a 100% width div?

Was missing the use of calc in the answers, which is a cleaner solution.

#logo {
  position: absolute;
  left: calc(50% - 25px);
  height: 50px;
  width: 50px;
  background: red;
}

jsFiddle

Works in most modern browsers: http://caniuse.com/calc

Maybe it's too soon to use it without a fallback, but I thought maybe for future visitors it would be helpful.

How to save username and password in Git?

Turn on the credential helper so that Git will save your password in memory for some time:

In Terminal, enter the following:

# Set git to use the credential memory cache
git config --global credential.helper cache

By default, Git will cache your password for 15 minutes.

To change the default password cache timeout, enter the following:

# Set the cache to timeout after 1 hour (setting is in seconds)
git config --global credential.helper 'cache --timeout=3600'

From GitHub Help

Good PHP ORM Library?

There are only two good ones: Doctrine and Propel. We favor Doctrine, and it works well with Symfony. However if you're looking for database support besides the main ones you'll have to write your own code.

How to find numbers from a string?

This a variant of brettdj's & pstraton post.

This will return a true Value and not give you the #NUM! error. And \D is shorthand for anything but digits. The rest is much like the others only with this minor fix.

Function StripChar(Txt As String) As Variant
With CreateObject("VBScript.RegExp")
    .Global = True
    .Pattern = "\D"
    StripChar = Val(.Replace(Txt, " "))
End With
End Function

Why did my Git repo enter a detached HEAD state?

A simple accidental way is to do a git checkout head as a typo of HEAD.

Try this:

git init
touch Readme.md
git add Readme.md
git commit
git checkout head

which gives

Note: checking out 'head'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:

  git checkout -b <new-branch-name>

HEAD is now at 9354043... Readme

How to throw RuntimeException ("cannot find symbol")

An Exception is an Object like any other in Java. You need to use the new keyword to create a new Exception before you can throw it.

throw new RuntimeException();

Optionally you could also do the following:

RuntimeException e = new RuntimeException();
throw e;

Both code snippets are equivalent.

Link to the tutorials for completeness.

How can I see what has changed in a file before committing to git?

Go to your respective git repo, then run the below command:

git diff filename

It will open the file with the changes marked, press return/enter key to scroll down the file.

P.S. filename should include the full path of the file or else you can run without the full file path by going in the respective directory/folder of the file

How to increase the Java stack size?

The only way to control the size of stack within process is start a new Thread. But you can also control by creating a self-calling sub Java process with the -Xss parameter.

public class TT {
    private static int level = 0;

    public static long fact(int n) {
        level++;
        return n < 2 ? n : n * fact(n - 1);
    }

    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread(null, null, "TT", 1000000) {
            @Override
            public void run() {
                try {
                    level = 0;
                    System.out.println(fact(1 << 15));
                } catch (StackOverflowError e) {
                    System.err.println("true recursion level was " + level);
                    System.err.println("reported recursion level was "
                            + e.getStackTrace().length);
                }
            }

        };
        t.start();
        t.join();
        try {
            level = 0;
            System.out.println(fact(1 << 15));
        } catch (StackOverflowError e) {
            System.err.println("true recursion level was " + level);
            System.err.println("reported recursion level was "
                    + e.getStackTrace().length);
        }
    }

}

What is “2's Complement”?

The simplest answer:

1111 + 1 = (1)0000. So 1111 must be -1. Then -1 + 1 = 0.

It's perfect to understand these all for me.

.m2 , settings.xml in Ubuntu

.m2 directory on linux box usually would be $HOME/.m2

you could get the $HOME :

echo $HOME

or simply:

cd <enter>

to go to your home directory.

other information from maven site: http://maven.apache.org/download.html#Installation

How to check if an integer is within a range?

You could do it using in_array() combined with range()

if (in_array($value, range($min, $max))) {
    // Value is in range
}

Note As has been pointed out in the comments however, this is not exactly a great solution if you are focussed on performance. Generating an array (escpecially with larger ranges) will slow down the execution.

How to remove newlines from beginning and end of a string?

If your string is potentially null, consider using StringUtils.trim() - the null-safe version of String.trim().

Delete empty rows

To delete rows empty in table

syntax:

DELETE FROM table_name 
WHERE column_name IS NULL;

example:

Table name: data ---> column name: pkdno

DELETE FROM data 
WHERE pkdno IS NULL;

Answer: 5 rows deleted. (sayso)

CSS submit button weird rendering on iPad/iPhone

The above answer for webkit appearance worked, but the button still looked kind pale/dull compared to the browser on other devices/desktop. I also had to set opacity to full (ranges from 0 to 1)

-webkit-appearance:none;
opacity: 1

After setting the opacity, the button looked the same on all the different devices/emulator/desktop.

What is the difference between json.dumps and json.load?

dumps takes an object and produces a string:

>>> a = {'foo': 3}
>>> json.dumps(a)
'{"foo": 3}'

load would take a file-like object, read the data from that object, and use that string to create an object:

with open('file.json') as fh:
    a = json.load(fh)

Note that dump and load convert between files and objects, while dumps and loads convert between strings and objects. You can think of the s-less functions as wrappers around the s functions:

def dump(obj, fh):
    fh.write(dumps(obj))

def load(fh):
    return loads(fh.read())

Macro to Auto Fill Down to last adjacent cell

Untested....but should work.

Dim lastrow as long

lastrow = range("D65000").end(xlup).Row

ActiveCell.FormulaR1C1 = _
        "=IF(MONTH(RC[-1])>3,"" ""&YEAR(RC[-1])&""-""&RIGHT(YEAR(RC[-1])+1,2),"" ""&YEAR(RC[-1])-1&""-""&RIGHT(YEAR(RC[-1]),2))"
    Selection.AutoFill Destination:=Range("E2:E" & lastrow)
    'Selection.AutoFill Destination:=Range("E2:E"& lastrow)
    Range("E2:E1344").Select

Only exception being are you sure your Autofill code is perfect...

How to disable an Android button?

You just write a single line of code in your activity

Button btn = (Button) findViewById(R.id.button1);
btn.setEnabled(false);

When you want to enable the same button just write

Button btn = (Button) findViewById(R.id.button1);
btn.setEnabled(true);

Angular 4.3 - HttpClient set params

This solutions working for me,

let params = new HttpParams(); Object.keys(data).forEach(p => { params = params.append(p.toString(), data[p].toString()); });

Is there a Google Keep API?

I have been waiting to see if Google would open a Keep API. When I discovered Google Tasks, and saw that it had an Android app, web app, and API, I converted over to Tasks. This may not directly answer your question, but it is my solution to the Keep API problem.

Tasks doesn't have a reminder alarm exactly like Keep. I can live without that if I also connect with the Calendar API.

https://developers.google.com/google-apps/tasks/

Shared folder between MacOSX and Windows on Virtual Box

Edit

4+ years later after the original reply in 2015, virtualbox.org now offers an official user manual in both html and pdf formats, which effectively deprecates the previous version of this answer:

  • Step 3 (Guest Additions) mentioned in this response as well as several others, is discussed in great detail in manual sections 4.1 and 4.2
  • Step 1 (Shared Folders Setting in VirtualBox Manager) is discussed in section 4.3

Original Answer

Because there isn't an official answer yet and I literally just did this for my OS X/WinXP install, here's what I did:

  1. VirtualBox Manager: Open the Shared Folders setting and click the '+' icon to add a new folder. Then, populate the Folder Path (or use the drop-down to navigate) with the folder you want shared and make sure "Auto-Mount" and "Make Permanent" are checked.
  2. Boot Windows
  3. Once Windows is running, goto the Devices menu (at the top of the VirtualBox Manager window) and select "Insert Guest Additions CD Image...". Cycle through the prompts and once you finish installing, let it reboot.
  4. After Windows reboots, your new drive should show up as a Network Drive in Windows Explorer.

Hope that helps.

PHP convert date format dd/mm/yyyy => yyyy-mm-dd

Try Using DateTime::createFromFormat

$date = DateTime::createFromFormat('d/m/Y', "24/04/2012");
echo $date->format('Y-m-d');

Output

2012-04-24

EDIT:

If the date is 5/4/2010 (both D/M/YYYY or DD/MM/YYYY), this below method is used to convert 5/4/2010 to 2010-4-5 (both YYYY-MM-DD or YYYY-M-D) format.

$old_date = explode('/', '5/4/2010'); 
$new_data = $old_date[2].'-'.$old_date[1].'-'.$old_date[0];

OUTPUT:

2010-4-5

How to retry after exception?

_x000D_
_x000D_
attempts = 3_x000D_
while attempts:_x000D_
  try:_x000D_
     ..._x000D_
     ..._x000D_
     <status ok>_x000D_
     break_x000D_
  except:_x000D_
    attempts -=1_x000D_
else: # executed only break was not  raised_x000D_
   <status failed>
_x000D_
_x000D_
_x000D_

How to show PIL Image in ipython notebook

I found that this is working

# source: http://nbviewer.ipython.org/gist/deeplook/5162445
from io import BytesIO

from IPython import display
from PIL import Image


def display_pil_image(im):
   """Displayhook function for PIL Images, rendered as PNG."""

   b = BytesIO()
   im.save(b, format='png')
   data = b.getvalue()

   ip_img = display.Image(data=data, format='png', embed=True)
   return ip_img._repr_png_()


# register display func with PNG formatter:
png_formatter = get_ipython().display_formatter.formatters['image/png']
dpi = png_formatter.for_type(Image.Image, display_pil_image)

After this I can just do:

pil_im

But this must be last line in cell, with no print after it

How to send SMS in Java

You can use AT & T commands for sending sms using GSM modem.

Get ASCII value at input word

char (with a lower-case c) is a numeric type. It already holds the ascii value of the char. Just cast it to an integer to display it as a numeric value rather than a textual value:

System.out.println("char " + ch + " has the following value : " + (int) ch);

Trying to handle "back" navigation button action in iOS

None of the other solutions worked for me, but this does:

Create your own subclass of UINavigationController, make it implement the UINavigationBarDelegate (no need to manually set the navigation bar's delegate), add a UIViewController extension that defines a method to be called on a back button press, and then implement this method in your UINavigationController subclass:

func navigationBar(_ navigationBar: UINavigationBar, shouldPop item: UINavigationItem) -> Bool {
    self.topViewController?.methodToBeCalledOnBackButtonPress()
    self.popViewController(animated: true)
    return true
}

Change an image with onclick()

Here, when clicking next or previous, the src attribute of an img tag is changed to the next or previous value in an array.

<div id="imageGallery">    
    <img id="image" src="http://adamyost.com/images/wasatch_thumb.gif" />
    <div id="previous">Previous</div>    
    <div id="next">Next</div>        
</div>

<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>

<script>
    $( document ).ready(function() {

        var images = [
            "http://placehold.it/350x150",
            "http://placehold.it/150x150",
            "http://placehold.it/50x150"    
        ];

        var imageIndex = 0;

        $("#previous").on("click", function(){          
            imageIndex = (imageIndex + images.length -1) % (images.length);    
            $("#image").attr('src', images[imageIndex]);
        });

        $("#next").on("click", function(){
            imageIndex = (imageIndex+1) % (images.length);    
            $("#image").attr('src', images[imageIndex]);
        });

        $("#image").attr(images[0]);

    });
</script>

I was able to implement this by modifying this answer: jQuery array with next and previous buttons to scroll through entries

How do I use Assert to verify that an exception has been thrown?

MSTest (v2) now has an Assert.ThrowsException function which can be used like this:

Assert.ThrowsException<System.FormatException>(() =>
            {
                Story actual = PersonalSite.Services.Content.ExtractHeader(String.Empty);
            }); 

You can install it with nuget: Install-Package MSTest.TestFramework

Cloning git repo causes error - Host key verification failed. fatal: The remote end hung up unexpectedly

I had the same issue, and the solution is very simple, just change to git bash from cmd or other windows command line tools. Windows sometimes does not work well with git npm dependencies.

What are the true benefits of ExpandoObject?

It's all about programmer convenience. I can imagine writing quick and dirty programs with this object.

Unable to open debugger port in IntelliJ

Your Service/ Application might already be running. In Search enter Services and you will get list of services. Stop yours and then try again.

How to add border around linear layout except at the bottom?

Kenny is right, just want to clear some things out.

  1. Create the file border.xml and put it in the folder res/drawable/
  2. add the code

    <shape xmlns:android="http://schemas.android.com/apk/res/android"> 
       <stroke android:width="4dp" android:color="#FF00FF00" /> 
       <solid android:color="#ffffff" /> 
       <padding android:left="7dp" android:top="7dp" 
            android:right="7dp" android:bottom="0dp" /> 
       <corners android:radius="4dp" /> 
    </shape>
    
  3. set back ground like android:background="@drawable/border" wherever you want the border

Mine first didn't work cause i put the border.xml in the wrong folder!

How to open a link in new tab using angular?

I have just discovered an alternative way of opening a new tab with the Router.

On your template,

<a (click)="openNewTab()" >page link</a>

And on your component.ts, you can use serializeUrl to convert the route into a string, which can be used with window.open()

openNewTab() {
  const url = this.router.serializeUrl(
    this.router.createUrlTree(['/example'])
  );

  window.open(url, '_blank');
}

Mysql Compare two datetime fields

The query you want to show as an example is:

SELECT * FROM temp WHERE mydate > '2009-06-29 16:00:44';

04:00:00 is 4AM, so all the results you're displaying come after that, which is correct.

If you want to show everything after 4PM, you need to use the correct (24hr) notation in your query.

To make things a bit clearer, try this:

SELECT mydate, DATE_FORMAT(mydate, '%r') FROM temp;

That will show you the date, and its 12hr time.

Changing background color of ListView items on Android

You can do This.

 final List<String> fruits_list = new ArrayList<String>(Arrays.asList(fruits));

    // Create an ArrayAdapter from List
    final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>
            (this, android.R.layout.simple_list_item_1, fruits_list){
        @Override
        public View getView(int position, View convertView, ViewGroup parent){
            // Get the current item from ListView
            View view = super.getView(position,convertView,parent);
            if(position %2 == 1)
            {
                // Set a background color for ListView regular row/item
                view.setBackgroundColor(Color.parseColor("#FFB6B546"));
            }
            else
            {
                // Set the background color for alternate row/item
                view.setBackgroundColor(Color.parseColor("#FFCCCB4C"));
            }
            return view;
        }
    };

    // DataBind ListView with items from ArrayAdapter
    lv.setAdapter(arrayAdapter);
}

}

What is Bootstrap?

By today's standards and web terminology, I'd say Bootstrap is actually not a framework, although that's what their website claims. Most developers consider Angular, Vue and React frameworks, while Bootstrap is commonly referred to as a "library".

But, to be exact and correct, Bootstrap is an open-source, mobile-first collection of CSS, JavaScript and HTML design utilities aimed at providing means to develop commonly used web elements considerably faster (and smarter) than having to code them from scratch.

A few core principles which contributed to Bootstrap's success:

  • it's reusable
  • it's flexible (i.e: allows custom grid systems, changing responsiveness breakpoints, column gutter sizes or state colors with ease; as a rule of thumb, most settings are controlled by global variables)
  • it's intuitive
  • it's modular (both JavaScript and (S)CSS use a modular approach; one can easily find tutorials on making custom Bootstrap builds, to include only the parts they need)
  • has above average cross-browser compatibility
  • web accessibility out of the box (screenreader ready)
  • it's fairly well documented

It contains design templates and functionality for: layout, typography, forms, navigation, menus (including dropdowns), buttons, panels, badges, modals, alerts, tabs, collapsible, accordions, carousels, lists, tables, pagination, media utilities (including embeds, images and image replacement), responsiveness utilities, color-based utilities (primary, secondary, danger, warning, info, light, dark, muted, white), other utilities (position, margin, padding, sizing, spacing, alignment, visibility), scrollspy, affix, tooltips, popovers.


By default it relies on jQuery, but you'll find jQuery free variants powered by each of the modern popular progressive JavaScript frameworks:

Working with Bootstrap relies heavily on applying certain classes (or, depending on JS framework: directives, methods or attributes/props) and on using particular markup structures.

Documentation typically contains generic examples which can be easily copy-pasted and used as starter templates.


Another advantage of developing with Bootstrap is its vibrant community, translated into an abundance of themes, templates and plugins available for it, most of which are open-source (i.e: calendars, date/time-pickers, plugins for tabular content management, as well as libraries/component collections built on top of Bootstrap, such as MDB, portfolio templates, admin templates, etc...)

Last, but not least, Bootstrap has been well maintained over the years, which makes it a solid choice for production-ready applications/websites.

How to change the color of header bar and address bar in newest Chrome version on Lollipop?

You actually need 3 meta tags to support Android, iPhone and Windows Phone

<!-- Chrome, Firefox OS and Opera -->
<meta name="theme-color" content="#4285f4">
<!-- Windows Phone -->
<meta name="msapplication-navbutton-color" content="#4285f4">
<!-- iOS Safari -->
<meta name="apple-mobile-web-app-status-bar-style" content="#4285f4">

Should I call Close() or Dispose() for stream objects?

A quick jump into Reflector.NET shows that the Close() method on StreamWriter is:

public override void Close()
{
    this.Dispose(true);
    GC.SuppressFinalize(this);
}

And StreamReader is:

public override void Close()
{
    this.Dispose(true);
}

The Dispose(bool disposing) override in StreamReader is:

protected override void Dispose(bool disposing)
{
    try
    {
        if ((this.Closable && disposing) && (this.stream != null))
        {
            this.stream.Close();
        }
    }
    finally
    {
        if (this.Closable && (this.stream != null))
        {
            this.stream = null;
            /* deleted for brevity */
            base.Dispose(disposing);
        }
    }
}

The StreamWriter method is similar.

So, reading the code it is clear that that you can call Close() & Dispose() on streams as often as you like and in any order. It won't change the behaviour in any way.

So it comes down to whether or not it is more readable to use Dispose(), Close() and/or using ( ... ) { ... }.

My personal preference is that using ( ... ) { ... } should always be used when possible as it helps you to "not run with scissors".

But, while this helps correctness, it does reduce readability. In C# we already have plethora of closing curly braces so how do we know which one actually performs the close on the stream?

So I think it is best to do this:

using (var stream = ...)
{
    /* code */

    stream.Close();
}

It doesn't affect the behaviour of the code, but it does aid readability.

How to convert numbers to words without using num2word library?

single_digit = {0: 'zero', 1: 'one', 2: 'two', 3: 'three', 4: 'four', 
            5: 'five', 6: 'six', 7: 'seven', 8: 'eight',
            9: 'nine'}

teen = {10: 'ten', 11: 'eleven', 12: 'twelve', 13: 'thirteen', 
        14: 'fourteen', 15: 'fifteen', 16: 'sixteen',
        17: 'seventeen', 18: 'eighteen', 19: 'nineteen'}

tens = {20: 'twenty', 30: 'thirty', 40: 'forty', 50: 'fifty', 60: 'sixty', 
        70: 'seventy', 80: 'eighty', 90: 'ninety'}

def spell_single_digit(digit):
    if 0 <= digit < 10:
        return single_digit[digit]

def spell_two_digits(number):
    if 10 <= number < 20:
        return teen[number]

    if 20 <= number < 100:
        div = (number // 10) * 10
        mod = number % 10
        if mod != 0:
            return tens[div] + "-" + spell_single_digit(mod)
        else:
            return tens[number]

def spell_three_digits(number):
    if 100 <= number < 1000:
        div = number // 100
        mod = number % 100
        if mod != 0:
            if mod < 10:
                return spell_single_digit(div) + " hundred " +  \
                   spell_single_digit(mod)
            elif mod < 100:
                return spell_single_digit(div) + " hundred " + \
                   spell_two_digits(mod)
        else:
            return spell_single_digit(div) + " hundred"

def spell(number):
    if -1000000000 < number < 1000000000:
        if number == 0:
            return spell_single_digit(number)
        a = ""
        neg = False
        if number < 0:
            neg = True
            number *= -1
        loop = 0
        while number:
            mod = number % 1000
            if mod != 0:
                c = spell_three_digits(mod) or spell_two_digits(mod) \
                    or spell_single_digit(mod)
                if loop == 0:
                    a = c + " " + a
                elif loop == 1:
                    a = c + " thousand " + a
                elif loop == 2:
                    a = c + " million " + a
            number = number // 1000
            loop += 1
        if neg:
            return "negative " + a
        return a

Disable form autofill in Chrome without disabling autocomplete

I stumbled upon the weird chrome autofill behaviour today. It happened to enable on fields called: "embed" and "postpassword" (filling there login and password) with no apparent reason. Those fields had already autocomplete set to off.

None of the described methods seemed to work. None of the methods from the another answer worked as well. I came upon my own idea basing on Steele's answer (it might have actually worked, but I require the fixed post data format in my application):

Before the real password, add those two dummy fields:

<input type='text' style='display: none'>
<input type='password' style='display: none'>

Only this one finally disabled autofill altogether for my form.

It's a shame, that disabling such a basic behavior is that hard and hacky.

WindowsError: [Error 126] The specified module could not be found

Note that even if the DLL is in your path. If that DLL relies on other DLLs that are NOT in your path, you can get the same error. Windows could not find a dependency in this case. Windows is not real good at telling you what it could not find, only that it did not find something. It is up to you to figure that out. The Windows dll search path can be found here: http://msdn.microsoft.com/en-us/library/7d83bc18.aspx

In my case, being sure all needed dlls were in the same directory and doing a os.chdir() to that directory solved the problem.

Using Notepad++ to validate XML against an XSD

  1. In Notepad++ go to Plugins > Plugin manager > Show Plugin Manager then find Xml Tools plugin. Tick the box and click Install

    enter image description here

  2. Open XML document you want to validate and click Ctrl+Shift+Alt+M (Or use Menu if this is your preference Plugins > XML Tools > Validate Now).
    Following dialog will open: enter image description here

  3. Click on .... Point to XSD file and I am pretty sure you'll be able to handle things from here.

Hope this saves you some time.

EDIT: Plugin manager was not included in some versions of Notepad++ because many users didn't like commercials that it used to show. If you want to keep an older version, however still want plugin manager, you can get it on github, and install it by extracting the archive and copying contents to plugins and updates folder.
In version 7.7.1 plugin manager is back under a different guise... Plugin Admin so now you can simply update notepad++ and have it back.

enter image description here

How to find column names for all tables in all databases in SQL Server

try the below query

DECLARE @Query VARCHAR(max) 
SELECT @Query = 'USE ? SELECT ''?'' AS DataBaseName,
                                sys.columns.name AS ColumnName  ,
                                sys.tables.name  AS TableName   ,
                                schema_name (sys.tables.schema_Id) AS schemaName
                         FROM sys.columns
                         JOIN sys.tables 
              ON sys.columns.object_id = sys.tables.object_id
              WHERE sys.columns.name = ''id'' '
EXEC SP_MSFOREACHDB @Query

gives list of tables containing ID column from all databases.

How do I reference tables in Excel using VBA?

Adding a third option. The "shorthand" version of @AndrewD's second option.

  1. SheetObject.ListObjects("TableName")
  2. Application.Range("TableName").ListObject
  3. [TableName].ListObject

Yes, there are no quotes in the bracket reference.

"Continue" (to next iteration) on VBScript

I use to use the Do, Loop a lot but I have started using a Sub or a Function that I could exit out of instead. It just seemed cleaner to me. If any variables you need are not global you will need to pass them to the Sub also.

For i=1 to N
 DoWork i
Next

Sub DoWork(i)
    [Code]
    If Condition1 Then
      Exit Sub
    End If

    [MoreCode]
    If Condition2 Then
      Exit Sub
    End If

    [MoreCode]
    If Condition2 Then
      Exit Sub
    End If

    [...]
End Sub

Date in to UTC format Java

Try to format your date with the Z or z timezone flags:

new SimpleDateFormat("MM/dd/yyyy KK:mm:ss a Z").format(dateObj);

Format of the initialization string does not conform to specification starting at index 0

My problem wasn't that the connection string I was providing was wrong, or that the connection string in the app.config I thought I was using was wrong, but that I was using the wrong app.config.

Regex for parsing directory and filename

Reasoning:

I did a little research through trial and error method. Found out that all the values that are available in keyboard are eligible to be a file or directory except '/' in *nux machine.

I used touch command to create file for following characters and it created a file.

(Comma separated values below)
'!', '@', '#', '$', "'", '%', '^', '&', '*', '(', ')', ' ', '"', '\', '-', ',', '[', ']', '{', '}', '`', '~', '>', '<', '=', '+', ';', ':', '|'

It failed only when I tried creating '/' (because it's root directory) and filename container / because it file separator.

And it changed the modified time of current dir . when I did touch .. However, file.log is possible.

And of course, a-z, A-Z, 0-9, - (hypen), _ (underscore) should work.

Outcome

So, by the above reasoning we know that a file name or directory name can contain anything except / forward slash. So, our regex will be derived by what will not be present in the file name/directory name.

/(?:(?P<dir>(?:[/]?)(?:[^\/]+/)+)(?P<filename>[^/]+))/

Step by Step regexp creation process

Pattern Explanation

Step-1: Start with matching root directory

A directory can start with / when it is absolute path and directory name when it's relative. Hence, look for / with zero or one occurrence.

/(?P<filepath>(?P<root>[/]?)(?P<rest_of_the_path>.+))/

enter image description here

Step-2: Try to find the first directory.

Next, a directory and its child is always separated by /. And a directory name can be anything except /. Let's match /var/ first then.

/(?P<filepath>(?P<first_directory>(?P<root>[/]?)[^\/]+/)(?P<rest_of_the_path>.+))/

enter image description here

Step-3: Get full directory path for the file

Next, let's match all directories

/(?P<filepath>(?P<dir>(?P<root>[/]?)(?P<single_dir>[^\/]+/)+)(?P<rest_of_the_path>.+))/

enter image description here

Here, single_dir is yz/ because, first it matched var/, then it found next occurrence of same pattern i.e. log/, then it found the next occurrence of same pattern yz/. So, it showed the last occurrence of pattern.

Step-4: Match filename and clean up

Now, we know that we're never going to use the groups like single_dir, filepath, root. Hence let's clean that up.

Let's keep them as groups however don't capture those groups.

And rest_of_the_path is just the filename! So, rename it. And a file will not have / in its name, so it's better to keep [^/]

/(?:(?P<dir>(?:[/]?)(?:[^\/]+/)+)(?P<filename>[^/]+))/

This brings us to the final result. Of course, there are several other ways you can do it. I am just mentioning one of the ways here.

enter image description here

Regex Rules used above are listed here

^ means string starts with
(?P<dir>pattern) means capture group by group name. We have two groups with group name dir and file
(?:pattern) means don't consider this group or non-capturing group.
? means match zero or one. + means match one or more [^\/] means matches any char except forward slash (/)

[/]? means if it is absolute path then it can start with / otherwise it won't. So, match zero or one occurrence of /.

[^\/]+/ means one or more characters which aren't forward slash (/) which is followed by a forward slash (/). This will match var/ or xyz/. One directory at a time.

Django values_list vs values

The values() method returns a QuerySet containing dictionaries:

<QuerySet [{'comment_id': 1}, {'comment_id': 2}]>

The values_list() method returns a QuerySet containing tuples:

<QuerySet [(1,), (2,)]>

If you are using values_list() with a single field, you can use flat=True to return a QuerySet of single values instead of 1-tuples:

<QuerySet [1, 2]>

How to call javascript function from asp.net button click event

If you don't need to initiate a post back when you press this button, then making the overhead of a server control isn't necesary.

<input id="addButton" type="button" value="Add" />

<script type="text/javascript" language="javascript">
     $(document).ready(function()
     {
         $('#addButton').click(function() 
         { 
             showDialog('#addPerson'); 
         });
     });
</script>

If you still need to be able to do a post back, you can conditionally stop the rest of the button actions with a little different code:

<asp:Button ID="buttonAdd" runat="server" Text="Add" />

<script type="text/javascript" language="javascript">
     $(document).ready(function()
     {
         $('#<%= buttonAdd.ClientID %>').click(function(e) 
         { 
             showDialog('#addPerson');

             if(/*Some Condition Is Not Met*/) 
                return false;
         });
     });
</script>

How to completely remove Python from a Windows machine?

You will also have to look in your system path. Python puts itself there and does not remove itself: http://www.computerhope.com/issues/ch000549.htm

Your problems probably started because your python path is pointing to the wrong one.

Preloading @font-face fonts?

As I found the best way is doing is preloading a stylesheet that contains the font face, and then let browser to load it automatically. I used the font-face in other locations (in the html page), but then I could observe the font changing effect briefly.

<link href="fonts.css?family=Open+Sans" rel="preload stylesheet" as="style">

then in the font.css file, specify as following.

@font-face {
  font-family: 'Open Sans';
  font-style: normal;
  font-weight: 400;
  src: local('Open Sans Regular'), local('OpenSans-Regular'),
       url('open-sans-v16-latin-regular.woff2') format('woff2'); /*  Super Modern Browsers */
}

You can't assign a name to fonts when it's preloaded through link tag (correct me if I was wrong I couldn't find a way yet), and thus you have to use font-face to assign the name to the font. Even though it's possible to load a font through link tag, it's not recommended as you can't assign a name to the font with it. Without a name as with font-face, you won't be able to use it anywhere in the web page. According to gtmetrix, style sheet loads at the beginning, then rest of the scripts/style by order, then the font before dom is loaded, and therefore you don't see font changing effect.

How to change date format (MM/DD/YY) to (YYYY-MM-DD) in date picker

I had the same issue and I have tried many answers but nothing worked.

I tried the following and it worked successfully :

<input type=text  data-date-format='yy-mm-dd'  > 

Making href (anchor tag) request POST instead of GET?

To do POST you'll need to have a form.

<form action="employee.action" method="post">
    <input type="submit" value="Employee1" />
</form>

There are some ways to post data with hyperlinks, but you'll need some javascript, and a form.

Some tricks: Make a link use POST instead of GET and How do you post data with a link

Edit: to load response on a frame you can target your form to your frame:

<form action="employee.action" method="post" target="myFrame">

SQL Server reports 'Invalid column name', but the column is present and the query works through management studio

In my case I restart Microsoft SQL Sever Management Studio and this works well for me.

Error: Selection does not contain a main type

If you are working with a Maven project you have to understand the fact that directory layout is bit different. In this the package name must be src/main/java.

For this update your source folder by right click on project root folder -> properties -> java build path -> source tab. Here remove all other source folders as they might have been added in wrong manner. Now, select project /src/main/java as the source folder. Add and apply the changes. Now refresh your workspace using F5.

This should fix the issue of not recognizing a main type.

How to check if running as root in a bash script

if [[ $(id -u) -ne 0 ]] ; then echo "Please run as root" ; exit 1 ; fi

or

if [[ `id -u` -ne 0 ]] ; then echo "Please run as root" ; exit 1 ; fi

:)

Read Content from Files which are inside Zip file

As of Java 7, the NIO Api provides a better and more generic way of accessing the contents of Zip or Jar files. Actually, it is now a unified API which allows you to treat Zip files exactly like normal files.

In order to extract all of the files contained inside of a zip file in this API, you'd do this:

In Java 8:

private void extractAll(URI fromZip, Path toDirectory) throws IOException{
    FileSystems.newFileSystem(fromZip, Collections.emptyMap())
            .getRootDirectories()
            .forEach(root -> {
                // in a full implementation, you'd have to
                // handle directories 
                Files.walk(root).forEach(path -> Files.copy(path, toDirectory));
            });
}

In java 7:

private void extractAll(URI fromZip, Path toDirectory) throws IOException{
    FileSystem zipFs = FileSystems.newFileSystem(fromZip, Collections.emptyMap());

    for(Path root : zipFs.getRootDirectories()) {
        Files.walkFileTree(root, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) 
                    throws IOException {
                // You can do anything you want with the path here
                Files.copy(file, toDirectory);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) 
                    throws IOException {
                // In a full implementation, you'd need to create each 
                // sub-directory of the destination directory before 
                // copying files into it
                return super.preVisitDirectory(dir, attrs);
            }
        });
    }
}

How to declare array of zeros in python (or an array of a certain size)

Depending on what you're actually going to do with the data after it's collected, collections.defaultdict(int) might be useful.

Can an Option in a Select tag carry multiple values?

In HTML

<SELECT NAME="Testing" id="Testing">  
  <OPTION VALUE="1,2010"> One  
  <OPTION VALUE="2,2122"> Two  
  <OPTION VALUE="3,0"> Three
</SELECT>

For JS

  var valueOne= $('#Testing').val().split(',')[0];
  var valueTwo =$('#Testing').val().split(',')[1];
  console.log(valueOne); //output 1
  console.log(valueTwo); //output 2010

OR FOR PHP

  $selectedValue= explode(',', $value);
  $valueOne= $exploded_value[0]; //output 1
  $valueTwo= $exploded_value[1]; //output 2010

Clear data in MySQL table with PHP?

Actually I believe the MySQL optimizer carries out a TRUNCATE when you DELETE all rows.

How to count number of files in each directory?

Everyone else's solution has one drawback or another.

find -type d -readable -exec sh -c 'printf "%s " "$1"; ls -1UA "$1" | wc -l' sh {} ';'

Explanation:

  • -type d: we're interested in directories.
  • -readable: We only want them if it's possible to list the files in them. Note that find will still emit an error when it tries to search for more directories in them, but this prevents calling -exec for them.
  • -exec sh -c BLAH sh {} ';': for each directory, run this script fragment, with $0 set to sh and $1 set to the filename.
  • printf "%s " "$1": portably and minimally print the directory name, followed by only a space, not a newline.
  • ls -1UA: list the files, one per line, in directory order (to avoid stalling the pipe), excluding only the special directories . and ..
  • wc -l: count the lines

Parsing arguments to a Java command line program

Use the Apache Commons CLI library commandline.getArgs() to get arg1, arg2, arg3, and arg4. Here is some code:



    import org.apache.commons.cli.CommandLine;
    import org.apache.commons.cli.Option;
    import org.apache.commons.cli.Options;
    import org.apache.commons.cli.Option.Builder;
    import org.apache.commons.cli.CommandLineParser;
    import org.apache.commons.cli.DefaultParser;
    import org.apache.commons.cli.ParseException;

    public static void main(String[] parameters)
    {
        CommandLine commandLine;
        Option option_A = Option.builder("A")
            .required(true)
            .desc("The A option")
            .longOpt("opt3")
            .build();
        Option option_r = Option.builder("r")
            .required(true)
            .desc("The r option")
            .longOpt("opt1")
            .build();
        Option option_S = Option.builder("S")
            .required(true)
            .desc("The S option")
            .longOpt("opt2")
            .build();
        Option option_test = Option.builder()
            .required(true)
            .desc("The test option")
            .longOpt("test")
            .build();
        Options options = new Options();
        CommandLineParser parser = new DefaultParser();

        String[] testArgs =
        { "-r", "opt1", "-S", "opt2", "arg1", "arg2",
          "arg3", "arg4", "--test", "-A", "opt3", };

        options.addOption(option_A);
        options.addOption(option_r);
        options.addOption(option_S);
        options.addOption(option_test);

        try
        {
            commandLine = parser.parse(options, testArgs);

            if (commandLine.hasOption("A"))
            {
                System.out.print("Option A is present.  The value is: ");
                System.out.println(commandLine.getOptionValue("A"));
            }

            if (commandLine.hasOption("r"))
            {
                System.out.print("Option r is present.  The value is: ");
                System.out.println(commandLine.getOptionValue("r"));
            }

            if (commandLine.hasOption("S"))
            {
                System.out.print("Option S is present.  The value is: ");
                System.out.println(commandLine.getOptionValue("S"));
            }

            if (commandLine.hasOption("test"))
            {
                System.out.println("Option test is present.  This is a flag option.");
            }

            {
                String[] remainder = commandLine.getArgs();
                System.out.print("Remaining arguments: ");
                for (String argument : remainder)
                {
                    System.out.print(argument);
                    System.out.print(" ");
                }

                System.out.println();
            }

        }
        catch (ParseException exception)
        {
            System.out.print("Parse error: ");
            System.out.println(exception.getMessage());
        }
    }

Post-increment and pre-increment within a 'for' loop produce same output

Yes, you'll get exactly same outputs for both. why do you think they should give you different outputs?

Post-increment or pre-increment matters in situations like this:

int j = ++i;
int k = i++;
f(i++);
g(++i);

where you provide some value, either by assigning or by passing an argument. You do neither in your for loops. It gets incremented only. Post- and pre- don't make sense there!

Error message "Linter pylint is not installed"

Check the path Pylint has been installed to, by typing which pylint on your terminal.

You will get something like: /usr/local/bin/pylint

Copy it.

Go to your Visual Studio Code settings in the preferences tab and find the line that goes

"python.linting.pylintPath": "pylint"

Edit the line to be

"python.linting.pylintPath": "/usr/local/bin/pylint",

replacing the value "pylint" with the path you got from typing which pylint.

Save your changes and reload Visual Studio Code.

How to disable and then enable onclick event on <div> with javascript

To enable use bind() method

$("#id").bind("click",eventhandler);

call this handler

 function  eventhandler(){
      alert("Bind click")
    }

To disable click useunbind()

$("#id").unbind("click");

MongoDB: Is it possible to make a case-insensitive query?

These have been tested for string searches

{'_id': /.*CM.*/}               ||find _id where _id contains   ->CM
{'_id': /^CM/}                  ||find _id where _id starts     ->CM
{'_id': /CM$/}                  ||find _id where _id ends       ->CM

{'_id': /.*UcM075237.*/i}       ||find _id where _id contains   ->UcM075237, ignore upper/lower case
{'_id': /^UcM075237/i}          ||find _id where _id starts     ->UcM075237, ignore upper/lower case
{'_id': /UcM075237$/i}          ||find _id where _id ends       ->UcM075237, ignore upper/lower case

How do I fix the multiple-step OLE DB operation errors in SSIS?

This query should identify columns that are potential problems...

SELECT * 
FROM [source].INFORMATION_SCHEMA.COLUMNS src
    INNER JOIN [dest].INFORMATION_SCHEMA.COLUMNS dst 
        ON dst.COLUMN_NAME = src.COLUMN_NAME
WHERE dst.CHARACTER_MAXIMUM_LENGTH < src.CHARACTER_MAXIMUM_LENGTH 

CSS/HTML: What is the correct way to make text italic?

Use <em> if you need some words/characters in italic in content without other styles. It also helps make content semantic.

text-style is better suited for multiple styles and no semantic need.

ArrayList - How to modify a member of an object?

Assuming Customer has a setter for email - myList.get(3).setEmail("[email protected]")

How to Run Terminal as Administrator on Mac Pro

You can run a command as admin using

sudo <command>

You can also switch to root and every command will be run as root

sudo su

How to align an indented line in a span that wraps into multiple lines?

Also you can try to use

display:inline-block;

if you would like the span element to align horizontally.

Incase you would like to align span elements vertically, just use

 display:block;

Import Error: No module named numpy

After trying many suggestions from various sites and similar questions, what worked for me was to uninstall all Python stuff and reinstall Anaconda only (see https://stackoverflow.com/a/38330088/1083292)

The previous Python installation I had was not only redundant but only caused me trouble.

How to have css3 animation to loop forever

Whilst Elad's solution will work, you can also do it inline:

   -moz-animation: fadeinphoto 7s 20s infinite;
-webkit-animation: fadeinphoto 7s 20s infinite;
     -o-animation: fadeinphoto 7s 20s infinite;
        animation: fadeinphoto 7s 20s infinite;

Converting String to Double in Android

String sc1="0.0";
Double s1=Double.parseDouble(sc1.toString());

Activate a virtualenv with a Python script

For python2/3, Using below code snippet we can activate virtual env.

activate_this = "/home/<--path-->/<--virtual env name -->/bin/activate_this.py" #for ubuntu
activate_this = "D:\<-- path -->\<--virtual env name -->\Scripts\\activate_this.py" #for windows
with open(activate_this) as f:
    code = compile(f.read(), activate_this, 'exec')
    exec(code, dict(__file__=activate_this))

How to Apply Mask to Image in OpenCV?

You can use the mask to copy only the region of interest of an original image to a destination one:

cvCopy(origImage,destImage,mask);

where mask should be an 8-bit single channel array.

See more at the OpenCV docs

jQuery rotate/transform

Why not just use, toggleClass on click?

js:

$(this).toggleClass("up");

css:

button.up {
    -webkit-transform: rotate(180deg);
       -moz-transform: rotate(180deg);
        -ms-transform: rotate(180deg);
         -o-transform: rotate(180deg);
            transform: rotate(180deg);
               /* IE6–IE9 */
               filter: progid:DXImageTransform.Microsoft.Matrix(M11=0.9914448613738104, M12=-0.13052619222005157,M21=0.13052619222005157, M22=0.9914448613738104, sizingMethod='auto expand');
                 zoom: 1;
    }

you can also add this to the css:

button{
        -webkit-transition: all 500ms ease-in-out;
        -moz-transition: all 500ms ease-in-out;
        -o-transition: all 500ms ease-in-out;
        -ms-transition: all 500ms ease-in-out;
}

which will add the animation.

PS...

to answer your original question:

you said that it rotates but never stops. When using set timeout you need to make sure you have a condition that will not call settimeout or else it will run forever. So for your code:

<script type="text/javascript">
    $(function() {
     var $elie = $("#bkgimg");
     rotate(0);
     function rotate(degree) {

      // For webkit browsers: e.g. Chrome
    $elie.css({ WebkitTransform: 'rotate(' + degree + 'deg)'});
      // For Mozilla browser: e.g. Firefox
    $elie.css({ '-moz-transform': 'rotate(' + degree + 'deg)'});


    /* add a condition here for the extremity */ 
    if(degree < 180){
      // Animate rotation with a recursive call
      setTimeout(function() { rotate(++degree); },65);
     }
    }
    });
    </script>

How do a LDAP search/authenticate against this LDAP in Java

Another approach is using UnboundID. Its api is very readable and shorter

Create a Ldap Connection

public static LDAPConnection getConnection() throws LDAPException {
    // host, port, username and password
    return new LDAPConnection("com.example.local", 389, "[email protected]", "admin");
}

Get filter result

public static List<SearchResultEntry> getResults(LDAPConnection connection, String baseDN, String filter) throws LDAPSearchException {
    SearchResult searchResult;

    if (connection.isConnected()) {
        searchResult = connection.search(baseDN, SearchScope.ONE, filter);

        return searchResult.getSearchEntries();
    }

    return null;
}

Get all Oragnization Units and Containers

String baseDN = "DC=com,DC=example,DC=local";
String filter = "(&(|(objectClass=organizationalUnit)(objectClass=container)))";

LDAPConnection connection = getConnection();        
List<SearchResultEntry> results = getResults(connection, baseDN, filter);

Get a specific Organization Unit

String baseDN = "DC=com,DC=example,DC=local";
String dn = "CN=Users,DC=com,DC=example,DC=local";

String filterFormat = "(&(|(objectClass=organizationalUnit)(objectClass=container))(distinguishedName=%s))";
String filter = String.format(filterFormat, dn);

LDAPConnection connection =  getConnection();

List<SearchResultEntry> results = getResults(connection, baseDN, filter);

Get all users under an Organizational Unit

String baseDN = "CN=Users,DC=com,DC=example,DC=local";
String filter = "(&(objectClass=user)(!(objectCategory=computer)))";

LDAPConnection connection =  getConnection();       
List<SearchResultEntry> results = getResults(connection, baseDN, filter);

Get a specific user under an Organization Unit

String baseDN = "CN=Users,DC=com,DC=example,DC=local";
String userDN = "CN=abc,CN=Users,DC=com,DC=example,DC=local";

String filterFormat = "(&(objectClass=user)(distinguishedName=%s))";
String filter = String.format(filterFormat, userDN);

LDAPConnection connection =  getConnection();
List<SearchResultEntry> results = getResults(connection, baseDN, filter);

Display result

for (SearchResultEntry e : results) {
    System.out.println("name: " + e.getAttributeValue("name"));
}

Dropdown select with images

If you think about it the concept behind a dropdown select it's pretty simple. For what you're trying to accomplish, a simple <ul> will do.

<ul id="menu">
    <li>
        <a href="#"><img src="" alt=""/></a> <!-- Selected -->
        <ul>
            <li><a href="#"><img src="" alt=""/></a></li>
            <li><a href="#"><img src="" alt=""/></a></li>
            <li><a href="#"><img src="" alt=""/></a></li>
            <li><a href="#"><img src="" alt=""/></a></li>
        </ul>
    </li>
</ul>

You style it with css and then some simple jQuery will do. I haven't tried this tho:

$('#menu ul li').click(function(){
    var $a = $(this).find('a');
    $(this).parents('#menu').children('li a').replaceWith($a).
});

Spring not autowiring in unit tests with JUnit

Missing Context file location in configuration can cause this, one approach to solve this:

  • Specifying Context file location in ContextConfiguration

like:

@ContextConfiguration(locations = { "classpath:META-INF/your-spring-context.xml" })

More details

@RunWith( SpringJUnit4ClassRunner.class )
@ContextConfiguration(locations = { "classpath:META-INF/your-spring-context.xml" })
public class UserServiceTest extends AbstractJUnit4SpringContextTests {}

Reference:Thanks to @Xstian

Is it safe to delete the "InetPub" folder?

IIS will create it again AFAIK.

Angular 4 img src is not found

Angular can only access static files like images and config files from assets folder. Nice way to download string path of remote stored image and load it to template.

  public concateInnerHTML(path: string): string {
     if(path){
        let front = "<img class='d-block' src='";
        let back = "' alt='slide'>";
        let result = front + path + back;
        return result;
     }
     return null;
  }

In a Component imlement DoCheck interface and past in it formula for database. Data base query is only a sample.

ngDoCheck(): void {
   this.concatedPathName = this.concateInnerHTML(database.query('src'));
}

And in html tamplate <div [innerHtml]="concatedPathName"></div>

How to automatically update your docker containers, if base-images are updated

I had the same issue and thought it can be simply solved by a cron job calling unattended-upgrade daily.

My intention is to have this as an automatic and quick solution to ensure that production container is secure and updated because it can take me sometime to update my images and deploy a new docker image with the latest security updates.

It is also possible to automate the image build and deployment with Github hooks

I've created a basic docker image with that automatically checks and installs security updates daily (can run directly by docker run itech/docker-unattended-upgrade ).

I also came across another different approach to check if the container needs an update.

My complete implementation:

Dockerfile

FROM ubuntu:14.04   

RUN apt-get update \
&& apt-get install -y supervisor unattended-upgrades \
&& rm -rf /var/lib/apt/lists/*

COPY install /install
RUN chmod 755 install
RUN /install

COPY start /start
RUN chmod 755 /start

Helper scripts

install

#!/bin/bash
set -e

cat > /etc/supervisor/conf.d/cron.conf <<EOF
[program:cron]
priority=20
directory=/tmp
command=/usr/sbin/cron -f
user=root
autostart=true
autorestart=true
stdout_logfile=/var/log/supervisor/%(program_name)s.log
stderr_logfile=/var/log/supervisor/%(program_name)s.log
EOF

rm -rf /var/lib/apt/lists/*

ENTRYPOINT ["/start"]

start

#!/bin/bash

set -e

echo "Adding crontab for unattended-upgrade ..."
echo "0 0 * * * root /usr/bin/unattended-upgrade" >> /etc/crontab

# can also use @daily syntax or use /etc/cron.daily

echo "Starting supervisord ..."
exec /usr/bin/supervisord -n -c /etc/supervisor/supervisord.conf

Edit

I developed a small tool docker-run that runs as docker container and can be used to update packages inside all or selected running containers, it can also be used to run any arbitrary commands.

Can be easily tested with the following command:

docker run --rm -v /var/run/docker.sock:/tmp/docker.sock itech/docker-run exec

which by default will execute date command in all running containers and display the results. If you pass update instead of exec it will execute apt-get update followed by apt-get upgrade -y in all running containers

'printf' vs. 'cout' in C++

I'd like to point out that if you want to play with threads in C++, if you use cout you can get some interesting results.

Consider this code:

#include <string>
#include <iostream>
#include <thread>

using namespace std;

void task(int taskNum, string msg) {
    for (int i = 0; i < 5; ++i) {
        cout << "#" << taskNum << ": " << msg << endl;
    }
}

int main() {
    thread t1(task, 1, "AAA");
    thread t2(task, 2, "BBB");
    t1.join();
    t2.join();
    return 0;
}

// g++ ./thread.cpp -o thread.out -ansi -pedantic -pthread -std=c++0x

Now, the output comes all shuffled. It can yield different results too, try executing several times:

##12::  ABABAB

##12::  ABABAB

##12::  ABABAB

##12::  ABABAB

##12::  ABABAB

You can use printf to get it right, or you can use mutex.

#1: AAA
#2: BBB
#1: AAA
#2: BBB
#1: AAA
#2: BBB
#1: AAA
#2: BBB
#1: AAA
#2: BBB

Have fun!

How to Create a Form Dynamically Via Javascript

some thing as follows ::

Add this After the body tag

This is a rough sketch, you will need to modify it according to your needs.

<script>
var f = document.createElement("form");
f.setAttribute('method',"post");
f.setAttribute('action',"submit.php");

var i = document.createElement("input"); //input element, text
i.setAttribute('type',"text");
i.setAttribute('name',"username");

var s = document.createElement("input"); //input element, Submit button
s.setAttribute('type',"submit");
s.setAttribute('value',"Submit");

f.appendChild(i);
f.appendChild(s);

//and some more input elements here
//and dont forget to add a submit button

document.getElementsByTagName('body')[0].appendChild(f);

</script>

mySQL convert varchar to date

select date_format(str_to_date('31/12/2010', '%d/%m/%Y'), '%Y%m'); 

or

select date_format(str_to_date('12/31/2011', '%m/%d/%Y'), '%Y%m'); 

hard to tell from your example

Best approach to converting Boolean object to string in java

If you are sure that your value is not null you can use third option which is

String str3 = b.toString();

and its code looks like

public String toString() {
    return value ? "true" : "false";
}

If you want to be null-safe use String.valueOf(b) which code looks like

public static String valueOf(Object obj) {
    return (obj == null) ? "null" : obj.toString();
}

so as you see it will first test for null and later invoke toString() method on your object.


Calling Boolean.toString(b) will invoke

public static String toString(boolean b) {
    return b ? "true" : "false";
}

which is little slower than b.toString() since JVM needs to first unbox Boolean to boolean which will be passed as argument to Boolean.toString(...), while b.toString() reuses private boolean value field in Boolean object which holds its state.

pthread_join() and pthread_exit()

It because every time

void pthread_exit(void *ret);

will be called from thread function so which ever you want to return simply its pointer pass with pthread_exit().

Now at

int pthread_join(pthread_t tid, void **ret);

will be always called from where thread is created so here to accept that returned pointer you need double pointer ..

i think this code will help you to understand this

#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <stdlib.h>

void* thread_function(void *ignoredInThisExample)
{
    char *a = malloc(10);
    strcpy(a,"hello world");
    pthread_exit((void*)a);
}
int main()
{
    pthread_t thread_id;
    char *b;

    pthread_create (&thread_id, NULL,&thread_function, NULL);

    pthread_join(thread_id,(void**)&b); //here we are reciving one pointer 
                                        value so to use that we need double pointer 
    printf("b is %s\n",b); 
    free(b); // lets free the memory

}

Get text from DataGridView selected cells

A lot of the answers on this page only apply to a single cell, and OP asked for all the selected cells.

If all you want is the cell contents, and you don't care about references to the actual cells that are selected, you can just do this:

Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim SelectedThings As String = DataGridView1.GetClipboardContent().GetText().Replace(ChrW(9), ",")
    TextBox1.Text = SelectedThings
End Sub

When Button1 is clicked, this will fill TextBox1 with the comma-separated values of the selected cells.

How to enable bulk permission in SQL Server

Try this:

USE master;

GO;
 
GRANT ADMINISTER BULK OPERATIONS TO shira;

Get class list for element with jQuery

You can follow something like this.

$('#elementID').prop('classList').add('yourClassName')
$('#elementID').prop('classList').remove('yourClassName')

Vue.js get selected option on @change

You can also use v-model for the rescue

<template>
    <select name="LeaveType" v-model="leaveType" @change="onChange()" class="form-control">
         <option value="1">Annual Leave/ Off-Day</option>
         <option value="2">On Demand Leave</option>
    </select>
</template>

<script>
export default {
    data() {
        return {
            leaveType: '',
        }
    },

    methods: {
        onChange() {
            console.log('The new value is: ', this.leaveType)
        }
    }
}
</script>

How to make a .NET Windows Service start right after the installation?

To start it right after installation, I generate a batch file with installutil followed by sc start

It's not ideal, but it works....

Do I need a content-type header for HTTP GET requests?

GET requests can have "Accept" headers, which say which types of content the client understands. The server can then use that to decide which content type to send back.

They're optional though.

http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1

Cannot use mkdir in home directory: permission denied (Linux Lubuntu)

you can try writing the command using 'sudo':

sudo mkdir DirName

How to modify memory contents using GDB?

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

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

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

(gdb) set {int}0x83040 = 4

There's more. Read the manual.

How to convert from java.sql.Timestamp to java.util.Date?

tl;dr

Instant instant = myResultSet.getObject( … , Instant.class ) ;

…or, if your JDBC driver does not support the optional Instant, it is required to support OffsetDateTime:

OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;

Avoid both java.util.Date & java.sql.Timestamp. They have been replaced by the java.time classes. Specifically, the Instant class representing a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Different Values ? Unverified Problem

To address the main part of the Question: "Why different dates between java.util.Date and java.sql.Timestamp objects when one is derived from the other?"

There must be a problem with your code. You did not post your code, so we cannot pinpoint the problem.

First, that string value you show for value of java.util.Date did not come from its default toString method, so you obviously were doing additional operations.

Secondly, when I run similar code I do indeed get exact same date-time values.

First create a java.sql.Timestamp object.

// Timestamp
long millis1 =  new java.util.Date().getTime();
java.sql.Timestamp ts = new java.sql.Timestamp(millis1);

Now extract the count-of-milliseconds-since-epoch to instantiate a java.util.Date object.

// Date
long millis2 = ts.getTime();
java.util.Date date = new java.util.Date( millis2 );

Dump values to console.

System.out.println("millis1 = " + millis1 );
System.out.println("ts = " + ts );
System.out.println("millis2 = " + millis2 );
System.out.println("date = " + date );

When run.

millis1 = 1434666385642
ts = 2015-06-18 15:26:25.642
millis2 = 1434666385642
date = Thu Jun 18 15:26:25 PDT 2015

So the code shown in the Question is indeed a valid way to convert from java.sql.Timestamp to java.util.Date, though you will lose any nanoseconds data.

java.util.Date someDate = new Date( someJUTimestamp.getTime() ); 

Different Formats Of String Output

Note that the output of the toString methods is a different format, as documented. The java.sql.Timestamp follows SQL format, similar to ISO 8601 format but without the T in middle.

Ignore Inheritance

As discussed on comments on other Answers and the Question, you should ignore the fact that java.sql.Timestamp inherits from java.util.Date. The j.s.Timestamp doc clearly states that you should not view one as a sub-type of the other: (emphasis mine)

Due to the differences between the Timestamp class and the java.util.Date class mentioned above, it is recommended that code not view Timestamp values generically as an instance of java.util.Date. The inheritance relationship between Timestamp and java.util.Date really denotes implementation inheritance, and not type inheritance.

If you ignore the Java team’s advice and take such a view, one critical problem is that you will lose data: any microsecond or nanosecond part of a second that may be coming from the database is lost as a Date has only millisecond resolution.

Basically, all the old date-time classes from early Java are a big mess: java.util.Date, j.u.Calendar, java.text.SimpleDateFormat, java.sql.Timestamp/.Date/.Time. They were one of the first valiant efforts at a date-time framework in the industry, but ultimately they fail. Specifically here, java.sql.Timestamp is a java.util.Date with nanoseconds tacked on; this is a hack, not good design.

java.time

Avoid the old date-time classes bundled with early versions of Java.

Instead use the java.time package (Tutorial) built into Java 8 and later whenever possible.

Basics of java.time… An Instant is a moment on the timeline in UTC. Apply a time zone (ZoneId) to get a ZonedDateTime.

Example code using java.time as of Java 8. With a JDBC driver supporting JDBC 4.2 and later, you can directly exchange java.time classes with your database; no need for the legacy classes.

Instant instant = myResultSet.getObject( … , Instant.class) ;  // Instant is the raw underlying data, an instantaneous point on the time-line stored as a count of nanoseconds since epoch.

You may want to adjust into a time zone other than UTC.

ZoneId z = ZoneId.of( "America/Montreal" );  // Always make time zone explicit rather than relying implicitly on the JVM’s current default time zone being applied.
ZonedDateTime zdt = instant.atZone( z ) ;

Perform your business logic. Here we simply add a day.

ZonedDateTime zdtNextDay = zdt.plusDays( 1 ); // Add a day to get "day after".

At the last stage, if absolutely needed, convert to a java.util.Date for interoperability.

java.util.Date dateNextDay = Date.from( zdtNextDay.toInstant( ) );  // WARNING: Losing data (the nanoseconds resolution).

Dump to console.

System.out.println( "instant = " + instant );
System.out.println( "zdt = " + zdt );
System.out.println( "zdtNextDay = " + zdtNextDay );
System.out.println( "dateNextDay = " + dateNextDay );

When run.

instant = 2015-06-18T16:44:13.123456789Z
zdt = 2015-06-18T19:44:13.123456789-04:00[America/Montreal]
zdtNextDay = 2015-06-19T19:44:13.123456789-04:00[America/Montreal]
dateNextDay = Fri Jun 19 16:44:13 PDT 2015

Conversions

If you must use the legacy types to interface with old code not yet updated for java.time, you may convert. Use new methods added to the old java.util.Date and java.sql.* classes for conversion.

Instant instant = myJavaSqlTimestamp.toInstant() ;

…and…

java.sql.Timestamp ts = java.sql.Timestamp.from( instant ) ;

See the Tutorial chapter, Legacy Date-Time Code, for more info on conversions.

Fractional Second

Be aware of the resolution of the fractional second. Conversions from nanoseconds to milliseconds means potentially losing some data.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

How to get element by classname or id

@tasseKATT's Answer is great, but if you don't want to make a directive, why not use $document?

.controller('ExampleController', ['$scope', '$document', function($scope, $document) {
  var dumb = function (id) {
  var queryResult = $document[0].getElementById(id)
  var wrappedID = angular.element(queryResult);
  return wrappedID;
};

PLUNKR

How to check if a process is running via a batch script

Another possibility I came up with, inspired by using grep, is:

tasklist /FI "IMAGENAME eq myapp.exe" 2>NUL | find /I /N "myapp.exe">NUL
if "%ERRORLEVEL%"=="0" echo Program is running

It doesn't need to save an extra file, so I prefer this method.

How to check if a query string value is present via JavaScript?

this function help you to get parameter from URL in JS

function getQuery(q) {
    return (window.location.search.match(new RegExp('[?&]' + q + '=([^&]+)')) || [, null])[1];
}

ORA-01652: unable to extend temp segment by 128 in tablespace SYSTEM: How to extend?

Each tablespace has one or more datafiles that it uses to store data.

The max size of a datafile depends on the block size of the database. I believe that, by default, that leaves with you with a max of 32gb per datafile.

To find out if the actual limit is 32gb, run the following:

select value from v$parameter where name = 'db_block_size';

Compare the result you get with the first column below, and that will indicate what your max datafile size is.

I have Oracle Personal Edition 11g r2 and in a default install it had an 8,192 block size (32gb per data file).

Block Sz   Max Datafile Sz (Gb)   Max DB Sz (Tb)

--------   --------------------   --------------

   2,048                  8,192          524,264

   4,096                 16,384        1,048,528

   8,192                 32,768        2,097,056

  16,384                 65,536        4,194,112

  32,768                131,072        8,388,224

You can run this query to find what datafiles you have, what tablespaces they are associated with, and what you've currrently set the max file size to (which cannot exceed the aforementioned 32gb):

select bytes/1024/1024 as mb_size,
       maxbytes/1024/1024 as maxsize_set,
       x.*
from   dba_data_files x

MAXSIZE_SET is the maximum size you've set the datafile to. Also relevant is whether you've set the AUTOEXTEND option to ON (its name does what it implies).

If your datafile has a low max size or autoextend is not on you could simply run:

alter database datafile 'path_to_your_file\that_file.DBF' autoextend on maxsize unlimited;

However if its size is at/near 32gb an autoextend is on, then yes, you do need another datafile for the tablespace:

alter tablespace system add datafile 'path_to_your_datafiles_folder\name_of_df_you_want.dbf' size 10m autoextend on maxsize unlimited;

How do I mock an autowired @Value field in Spring with Mockito?

You can use the magic of Spring's ReflectionTestUtils.setField in order to avoid making any modifications whatsoever to your code.

The comment from Michal Stochmal provides an example:

use ReflectionTestUtils.setField(bean, "fieldName", "value"); before invoking your bean method during test.

Check out this tutorial for even more information, although you probably won't need it since the method is very easy to use

UPDATE

Since the introduction of Spring 4.2.RC1 it is now possible to set a static field without having to supply an instance of the class. See this part of the documentation and this commit.

Finding square root without using sqrt function?

Why not try to use the Babylonian method for finding a square root.

Here is my code for it:

double sqrt(double number)
{
    double error = 0.00001; //define the precision of your result
    double s = number;

    while ((s - number / s) > error) //loop until precision satisfied 
    {
        s = (s + number / s) / 2;
    }
    return s;
}

Good luck!

C# : Converting Base Class to Child Class

If you HAVE to, and you don't mind a hack, you could let serialization do the work for you.

Given these classes:

public class ParentObj
{
    public string Name { get; set; }
}

public class ChildObj : ParentObj
{
    public string Value { get; set; }
}

You can create a child instance from a parent instance like so:

var parent = new ParentObj() { Name = "something" };
var serialized = JsonConvert.SerializeObject(parent);
var child = JsonConvert.DeserializeObject<ChildObj>(serialized);

This assumes your objects play nice with serialization, obv.

Be aware that this is probably going to be slower than an explicit converter.

How do I tell if a variable has a numeric value in Perl?

I don't believe there is anything builtin to do it. For more than you ever wanted to see on the subject, see Perlmonks on Detecting Numeric

SQL ROWNUM how to return rows between a specific range

select * 
from emp 
where rownum <= &upperlimit 
minus 
select * 
from emp 
where rownum <= &lower limit ;

Django - Static file not found

In your cmd type command python manage.py findstatic --verbosity 2 static It will give the directory in which Django is looking for static files.If you have created a virtual environment then there will be a static folder inside this virtual_environment_name folder. VIRTUAL_ENVIRONMENT_NAME\Lib\site-packages\django\contrib\admin\static. On running the above 'findstatic' command if Django shows you this path then just paste all your static files in this static directory. In your html file use JINJA syntax for href and check for other inline css. If still there is an image src or url after giving JINJA syntax then prepend it with '/static'. This worked for me.

Removing Duplicate Values from ArrayList

     public List<Contact> removeDuplicates(List<Contact> list) {
    // Set set1 = new LinkedHashSet(list);
    Set set = new TreeSet(new Comparator() {
        @Override
        public int compare(Object o1, Object o2) {
                 if(((Contact)o1).getId().equalsIgnoreCase(((Contact)2).getId()) ) {
                return 0;
            }
            return 1;
        }
    });
    set.addAll(list);
    final List newList = new ArrayList(set);
    return newList;
}

C++ delete vector, objects, free memory

There are two separate things here:

  1. object lifetime
  2. storage duration

For example:

{
    vector<MyObject> v;
    // do some stuff, push some objects onto v
    v.clear(); // 1
    // maybe do some more stuff
} // 2

At 1, you clear v: this destroys all the objects it was storing. Each gets its destructor called, if your wrote one, and anything owned by that MyObject is now released. However, vector v has the right to keep the raw storage around in case you want it later.

If you decide to push some more things into it between 1 and 2, this saves time as it can reuse the old memory.

At 2, the vector v goes out of scope: any objects you pushed into it since 1 will be destroyed (as if you'd explicitly called clear again), but now the underlying storage is also released (v won't be around to reuse it any more).


If I change the example so v becomes a pointer to a dynamically-allocated vector, you need to explicitly delete it, as the pointer going out of scope at 2 doesn't do that for you. It's better to use something like std::unique_ptr in that case, but if you don't and v is leaked, the storage it allocated will be leaked as well. As above, you need to make sure v is deleted, and calling clear isn't sufficient.

How to create an integer array in Python?

If you need to initialize an array fast, you might do it by blocks instead of with a generator initializer, and it's going to be much faster. Creating a list by [0]*count is just as fast, still.

import array

def zerofill(arr, count):
    count *= arr.itemsize
    blocksize = 1024
    blocks, rest = divmod(count, blocksize)
    for _ in xrange(blocks):
        arr.fromstring("\x00"*blocksize)
    arr.fromstring("\x00"*rest)

def test_zerofill(count):
    iarr = array.array('i')
    zerofill(iarr, count)
    assert len(iarr) == count

def test_generator(count):
    iarr = array.array('i', (0 for _ in xrange(count)))
    assert len(iarr) == count

def test_list(count):
    L = [0]*count
    assert len(L) == count

if __name__ == '__main__':
    import timeit
    c = 100000
    n = 10
    print timeit.Timer("test(c)", "from __main__ import c, test_zerofill as test").repeat(number=n)
    print timeit.Timer("test(c)", "from __main__ import c, test_generator as test").repeat(number=n)
    print timeit.Timer("test(c)", "from __main__ import c, test_list as test").repeat(number=n)

Results:

(array in blocks) [0.022809982299804688, 0.014942169189453125, 0.014089107513427734]
(array with generator) [1.1884641647338867, 1.1728270053863525, 1.1622772216796875]
(list) [0.023866891860961914, 0.035660028457641602, 0.023386955261230469]

Push local Git repo to new remote including all branches and tags

Mirroring a repository

Create a bare clone of the repository.

git clone --bare https://github.com/exampleuser/old-repository.git

Mirror-push to the new repository.

cd old-repository.git
git push --mirror https://github.com/exampleuser/new-repository.git

Remove the temporary local repository you created in step 1.

cd ..
rm -rf old-repository.git

Mirroring a repository that contains Git Large File Storage objects

Create a bare clone of the repository. Replace the example username with the name of the person or organization who owns the repository, and replace the example repository name with the name of the repository you'd like to duplicate.

git clone --bare https://github.com/exampleuser/old-repository.git

Navigate to the repository you just cloned.

cd old-repository.git

Pull in the repository's Git Large File Storage objects.

git lfs fetch --all

Mirror-push to the new repository.

git push --mirror https://github.com/exampleuser/new-repository.git

Push the repository's Git Large File Storage objects to your mirror.

git lfs push --all https://github.com/exampleuser/new-repository.git

Remove the temporary local repository you created in step 1.

cd ..
rm -rf old-repository.git

Above instruction comes from Github Help: https://help.github.com/articles/duplicating-a-repository/

Handling the TAB character in Java

You can also use the tab character '\t' to represent a tab, instead of "\t".

char c ='t';
char c =(char)9;

Chrome ignores autocomplete="off"

In Chrome 48+ use this solution:

  1. Put fake fields before real fields:

    <form autocomplete="off">
      <input name="fake_email"    class="visually-hidden" type="text">
      <input name="fake_password" class="visually-hidden" type="password">
    
      <input autocomplete="off" name="email"    type="text">
      <input autocomplete="off" name="password" type="password">
    </form>
    
  2. Hide fake fields:

    .visually-hidden {
      margin: -1px;
      padding: 0;
      width: 1px;
      height: 1px;
      overflow: hidden;
      clip: rect(0 0 0 0);
      clip: rect(0, 0, 0, 0);
      position: absolute;
    }
    
  3. You did it!

Also this will work for older versions.

Can I check if Bootstrap Modal Shown / Hidden?

if($('.modal').hasClass('in')) {
    alert($('.modal .in').attr('id')); //ID of the opened modal
} else {
    alert("No pop-up opened");
}

how to get current month and year

using System.Globalization;

LblMonth.Text = DateTime.Now.Month.ToString();

DateTimeFormatInfo dinfo = new DateTimeFormatInfo();
int month = Convert.ToInt16(LblMonth.Text);

LblMonth.Text = dinfo.GetMonthName(month);

html5 <input type="file" accept="image/*" capture="camera"> display as image rather than "choose file" button

You have to use Javascript Filereader for this. (Introduction into filereader-api: http://www.html5rocks.com/en/tutorials/file/dndfiles/)

Once the user have choose a image you can read the file-path of the chosen image and place it into your html.

Example:

<form id="form1" runat="server">
    <input type='file' id="imgInp" />
    <img id="blah" src="#" alt="your image" />
</form>

Javascript:

function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $('#blah').attr('src', e.target.result);
        }

        reader.readAsDataURL(input.files[0]);
    }
}

$("#imgInp").change(function(){
    readURL(this);
});

How to run a script at the start up of Ubuntu?

First of all, the easiest way to run things at startup is to add them to the file /etc/rc.local.

Another simple way is to use @reboot in your crontab. Read the cron manpage for details.

However, if you want to do things properly, in addition to adding a script to /etc/init.d you need to tell ubuntu when the script should be run and with what parameters. This is done with the command update-rc.d which creates a symlink from some of the /etc/rc* directories to your script. So, you'd need to do something like:

update-rc.d yourscriptname start 2

However, real init scripts should be able to handle a variety of command line options and otherwise integrate to the startup process. The file /etc/init.d/README has some details and further pointers.

Is there a performance difference between i++ and ++i in C?

Executive summary: No.

i++ could potentially be slower than ++i, since the old value of i might need to be saved for later use, but in practice all modern compilers will optimize this away.

We can demonstrate this by looking at the code for this function, both with ++i and i++.

$ cat i++.c
extern void g(int i);
void f()
{
    int i;

    for (i = 0; i < 100; i++)
        g(i);

}

The files are the same, except for ++i and i++:

$ diff i++.c ++i.c
6c6
<     for (i = 0; i < 100; i++)
---
>     for (i = 0; i < 100; ++i)

We'll compile them, and also get the generated assembler:

$ gcc -c i++.c ++i.c
$ gcc -S i++.c ++i.c

And we can see that both the generated object and assembler files are the same.

$ md5 i++.s ++i.s
MD5 (i++.s) = 90f620dda862cd0205cd5db1f2c8c06e
MD5 (++i.s) = 90f620dda862cd0205cd5db1f2c8c06e

$ md5 *.o
MD5 (++i.o) = dd3ef1408d3a9e4287facccec53f7d22
MD5 (i++.o) = dd3ef1408d3a9e4287facccec53f7d22

How can I drop all the tables in a PostgreSQL database?

I modified Pablo's answer slightly for the convenience of having the generated SQL commands returned as one single string:

select string_agg('drop table "' || tablename || '" cascade', '; ') 
from pg_tables where schemaname = 'public'

Android: How do bluetooth UUIDs work?

The UUID is used for uniquely identifying information. It identifies a particular service provided by a Bluetooth device. The standard defines a basic BASE_UUID: 00000000-0000-1000-8000-00805F9B34FB.

Devices such as healthcare sensors can provide a service, substituting the first eight digits with a predefined code. For example, a device that offers an RFCOMM connection uses the short code: 0x0003

So, an Android phone can connect to a device and then use the Service Discovery Protocol (SDP) to find out what services it provides (UUID).

In many cases, you don't need to use these fixed UUIDs. In the case your are creating a chat application, for example, one Android phone interacts with another Android phone that uses the same application and hence the same UUID.

So, you can set an arbitrary UUID for your application using, for example, one of the many random UUID generators on the web (for example).

Debugging the error "gcc: error: x86_64-linux-gnu-gcc: No such file or directory"

I was getting the error “gcc: error: x86_64-linux-gnu-gcc: No such file or directory” as I was trying to build a simple c-extension module to run in Python. I tried all the things above to no avail, and finally realized that I had an error in my module.c code! So I thought it would be helpful to add that, if you are getting this error message but you have python-dev and everything correctly installed, you should look for issues in your code.

PHP: cannot declare class because the name is already in use

Another option to include_once or require_once is to use class autoloading. http://php.net/manual/en/language.oop5.autoload.php

How can I convert IPV6 address to IPV4 address?

Some googling led me to the following post:

http://www.developerweb.net/forum/showthread.php?t=3434

The code provided in the post is in C, but it shouldn't be too hard to rewrite it to Java.

If input field is empty, disable submit button

Try this code

$(document).ready(function(){
    $('.sendButton').attr('disabled',true);

    $('#message').keyup(function(){
        if($(this).val().length !=0){
            $('.sendButton').attr('disabled', false);
        }
        else
        {
            $('.sendButton').attr('disabled', true);        
        }
    })
});

Check demo Fiddle

You are missing the else part of the if statement (to disable the button again if textbox is empty) and parentheses () after val function in if($(this).val.length !=0){

Printing all properties in a Javascript Object

Your syntax is incorrect. The var keyword in your for loop must be followed by a variable name, in this case its propName

var propValue;
for(var propName in nyc) {
    propValue = nyc[propName]

    console.log(propName,propValue);
}

I suggest you have a look here for some basics:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

Equivalent of jQuery .hide() to set visibility: hidden

There isn't one built in but you could write your own quite easily:

(function($) {
    $.fn.invisible = function() {
        return this.each(function() {
            $(this).css("visibility", "hidden");
        });
    };
    $.fn.visible = function() {
        return this.each(function() {
            $(this).css("visibility", "visible");
        });
    };
}(jQuery));

You can then call this like so:

$("#someElem").invisible();
$("#someOther").visible();

Here's a working example.

array of string with unknown size

string[ ] array = {};

// it is not null instead it is empty.

Using XPATH to search text containing &nbsp;

Bear in mind that a standards-compliant XML processor will have replaced any entity references other than XML's five standard ones (&amp;, &gt;, &lt;, &apos;, &quot;) with the corresponding character in the target encoding by the time XPath expressions are evaluated. Given that behavior, PhiLho's and jsulak's suggestions are the way to go if you want to work with XML tools. When you enter &#160; in the XPath expression, it should be converted to the corresponding byte sequence before the XPath expression is applied.

Scala best way of turning a Collection into a Map-by-key?

c map (_.getP) zip c

Works well and is very intuitiv

How to populate/instantiate a C# array with a single value?

What about a parallel implementation

public static void InitializeArray<T>(T[] array, T value)
{
    var cores = Environment.ProcessorCount;

    ArraySegment<T>[] segments = new ArraySegment<T>[cores];

    var step = array.Length / cores;
    for (int i = 0; i < cores; i++)
    {
        segments[i] = new ArraySegment<T>(array, i * step, step);
    }
    var remaining = array.Length % cores;
    if (remaining != 0)
    {
        var lastIndex = segments.Length - 1;
        segments[lastIndex] = new ArraySegment<T>(array, lastIndex * step, array.Length - (lastIndex * step));
    }

    var initializers = new Task[cores];
    for (int i = 0; i < cores; i++)
    {
        var index = i;
        var t = new Task(() =>
        {
            var s = segments[index];
            for (int j = 0; j < s.Count; j++)
            {
                array[j + s.Offset] = value;
            }
        });
        initializers[i] = t;
        t.Start();
    }

    Task.WaitAll(initializers);
}

When only initializing an array the power of this code can't be seen but I think you should definitely forget about the "pure" for.

Why use the 'ref' keyword when passing an object?

Ref denotes whether the function can get its hands on the object itself, or only on its value.

Passing by reference is not bound to a language; it's a parameter binding strategy next to pass-by-value, pass by name, pass by need etc...

A sidenote: the class name TestRef is a hideously bad choice in this context ;).

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

I know you've found another solution, but for those like me who find this question, looking for the same thing, it can be achieved with requests as follows:

Firstly, as Marcus did, check the source of the login form to get three pieces of information - the url that the form posts to, and the name attributes of the username and password fields. In his example, they are inUserName and inUserPass.

Once you've got that, you can use a requests.Session() instance to make a post request to the login url with your login details as a payload. Making requests from a session instance is essentially the same as using requests normally, it simply adds persistence, allowing you to store and use cookies etc.

Assuming your login attempt was successful, you can simply use the session instance to make further requests to the site. The cookie that identifies you will be used to authorise the requests.

Example

import requests

# Fill in your details here to be posted to the login form.
payload = {
    'inUserName': 'username',
    'inUserPass': 'password'
}

# Use 'with' to ensure the session context is closed after use.
with requests.Session() as s:
    p = s.post('LOGIN_URL', data=payload)
    # print the html returned or something more intelligent to see if it's a successful login page.
    print p.text

    # An authorised request.
    r = s.get('A protected web page url')
    print r.text
        # etc...

Check for column name in a SqlDataReader object

In your particular situation (all procedures has the same columns except 1 which has additional 1 column), it will be better and faster to check reader. FieldCount property to distinguish between them.

const int NormalColCount=.....
if(reader.FieldCount > NormalColCount)
{
// Do something special
}

I know it is an old post but I decided to answer to help other in the same situation. you can also (for performance reason) mix this solution with the solution iterating solution.

fail to change placeholder color with Bootstrap 3

The others did not work in my case (Bootstrap 4). Here is the solution I used.

html .form-control::-webkit-input-placeholder { color:white; }
html .form-control:-moz-placeholder { color:white; }
html .form-control::-moz-placeholder { color:white; }
html .form-control:-ms-input-placeholder { color:white; }

If we use a stronger selector (html first), we don't need to use the hacky value !important.

This overrides bootstraps CSS as we use a higher level of specificity to target .form-control elements (html first instead of .form-control first).

How to format a float in javascript?

There is a problem with all those solutions floating around using multipliers. Both kkyy and Christoph's solutions are wrong unfortunately.

Please test your code for number 551.175 with 2 decimal places - it will round to 551.17 while it should be 551.18 ! But if you test for ex. 451.175 it will be ok - 451.18. So it's difficult to spot this error at a first glance.

The problem is with multiplying: try 551.175 * 100 = 55117.49999999999 (ups!)

So my idea is to treat it with toFixed() before using Math.round();

function roundFix(number, precision)
{
    var multi = Math.pow(10, precision);
    return Math.round( (number * multi).toFixed(precision + 1) ) / multi;
}

Get user input from textarea

<pre>
  <input type="text"  #titleInput>
  <button type="submit" (click) = 'addTodo(titleInput.value)'>Add</button>
</pre>

{
  addTodo(title:string) {
    console.log(title);
  }
}    

Regular expression which matches a pattern, or is an empty string

To match pattern or an empty string, use

^$|pattern

Explanation

  • ^ and $ are the beginning and end of the string anchors respectively.
  • | is used to denote alternates, e.g. this|that.

References


On \b

\b in most flavor is a "word boundary" anchor. It is a zero-width match, i.e. an empty string, but it only matches those strings at very specific places, namely at the boundaries of a word.

That is, \b is located:

  • Between consecutive \w and \W (either order):
    • i.e. between a word character and a non-word character
  • Between ^ and \w
    • i.e. at the beginning of the string if it starts with \w
  • Between \w and $
    • i.e. at the end of the string if it ends with \w

References


On using regex to match e-mail addresses

This is not trivial depending on specification.

Related questions

Specific Time Range Query in SQL Server

I (using PostgrSQL on PGadmin4) queried for results that are after or on 21st Nov 2017 at noon, like this (considering the display format of hours on my database):

select * from Table1 where FIELD >='2017-11-21 12:00:00' 

How to download Javadoc to read offline?

update 2019-09-29: Java version 11

The technique below does not now work with Java 11, and probably higher versions: there is no way of ignoring multiple "broken links" (i.e. to other classes, other APIs). Solution: keep your javadoc executable file (or javadoc.exe) from Java version 8


There are good reasons for making your own local javadocs, and it's not particularly difficult!

First you need the source. At the time of writing the Java 8 JDK comes with a zip file called src.zip. Sometimes, for unexplained reasons, Oracle don't always include the source. So for some older versions (and who knows about the future) you have to get hold of the Java source in another way. It's worth also being aware that, in the past, Oracle have sometimes included the source with the Linux version of the JDK, but not with the Windows one.

I just unzipped this file... the top directories are "com", "java", "javax", "launcher" and "org". Directory launcher contains no files to document.

You can generate the javadocs very very simply from any or all of these by CD'ing at the command prompt/terminal to the directory ...\src. Then go

javadoc -d docs -Xmaxwarns 10 -Xmaxerrs 10 -Xdoclint:none -sourcepath . -subpackages java:javax:org:com

NB note that there is a "." after -sourcepath

Simple as that. Generating your own javadocs also has 2 huge advantages

  1. you know they are precisely the right javadocs for the JDK (or any exernal jar file) you are using on your system
  2. once you get into the habit, reconstituting your Javadocs is not a tiresome challenge (i.e. where to go looking for them). For example I just unzipped a couple of source jars whose packages are closely coupled, so their sources were in effect "merged" & then made a single Javadoc from them...

NB Swing is semi-officially DEAD. We should all be switching to JavaFX, which is helpfully bundled with Java 8 JDK, but in its own source file, javafx-src.zip.

Unzipped, this reveals 3 "root" packages: com, javafx and netscape (wha'?). These should be manually moved over the to appropriate places under the unzipped src directory (including the JavaFX com.sun packages under the Java com.sun strcture). Compiling all these Javadoc files took my machine a non-negligible time. I'd expect to see all the JavaFX source classes in with all the other source classes some time soon.


BTW, the same thinking applies to documenting any and all Java jars (with source) which you use. However, all versions of most jars will be found with their documentation available for download at Maven Central http://search.maven.org...

PS afterthought:
using Eclipse and the "Gradle STS" plugin: the "New Gradle STS Project" wizard will create a gradle.build file containing the line

include plugin: 'eclipse'

This magically downloads the source jar with the executable jar (under GRADLE_HOME) when you go

./gradlew build

[addendum 2020-01-13: if you have chosen not to include the Eclipse plugin in your build.gradle, it would appear that you can go (with the selection on your project in the Project Explorer) Right-click Gradle --> Refresh Gradle Project to get Eclipse to download the source files.]

... giving you an extra degree of certainty that you have got the right src and therefore the right javadoc for the dependency in question.

Kotlin - Property initialization using "by lazy" vs. "lateinit"

Here are the significant differences between lateinit var and by lazy { ... } delegated property:

  • lazy { ... } delegate can only be used for val properties, whereas lateinit can only be applied to vars, because it can't be compiled to a final field, thus no immutability can be guaranteed;

  • lateinit var has a backing field which stores the value, and by lazy { ... } creates a delegate object in which the value is stored once calculated, stores the reference to the delegate instance in the class object and generates the getter for the property that works with the delegate instance. So if you need the backing field present in the class, use lateinit;

  • In addition to vals, lateinit cannot be used for nullable properties or Java primitive types (this is because of null used for uninitialized value);

  • lateinit var can be initialized from anywhere the object is seen from, e.g. from inside a framework code, and multiple initialization scenarios are possible for different objects of a single class. by lazy { ... }, in turn, defines the only initializer for the property, which can be altered only by overriding the property in a subclass. If you want your property to be initialized from outside in a way probably unknown beforehand, use lateinit.

  • Initialization by lazy { ... } is thread-safe by default and guarantees that the initializer is invoked at most once (but this can be altered by using another lazy overload). In the case of lateinit var, it's up to the user's code to initialize the property correctly in multi-threaded environments.

  • A Lazy instance can be saved, passed around and even used for multiple properties. On contrary, lateinit vars do not store any additional runtime state (only null in the field for uninitialized value).

  • If you hold a reference to an instance of Lazy, isInitialized() allows you to check whether it has already been initialized (and you can obtain such instance with reflection from a delegated property). To check whether a lateinit property has been initialized, you can use property::isInitialized since Kotlin 1.2.

  • A lambda passed to by lazy { ... } may capture references from the context where it is used into its closure.. It will then store the references and release them only once the property has been initialized. This may lead to object hierarchies, such as Android activities, not being released for too long (or ever, if the property remains accessible and is never accessed), so you should be careful about what you use inside the initializer lambda.

Also, there's another way not mentioned in the question: Delegates.notNull(), which is suitable for deferred initialization of non-null properties, including those of Java primitive types.

JSON string to JS object

the string in your question is not a valid json string. From json.org website:

JSON is built on two structures:

* A collection of name/value pairs. In various languages, this is 
  realized as an object, record, struct, dictionary, hash table, keyed list, or
  associative array.
* An ordered list of values. In most languages, this is realized as an
  array, vector, list, or sequence.

Basically a json string will always start with either { or [.

Then as @Andy E and @Cryo said you can parse the string with json2.js or some other libraries.

IMHO you should avoid eval because it will any javascript program, so you might incur in security issues.

exporting multiple modules in react.js

You can have only one default export which you declare like:

export default App; or export default class App extends React.Component {...

and later do import App from './App'

If you want to export something more you can use named exports which you declare without default keyword like:

export {
  About,
  Contact,
}

or:

export About;
export Contact;

or:

export const About = class About extends React.Component {....
export const Contact = () => (<div> ... </div>);

and later you import them like:

import App, { About, Contact } from './App';

EDIT:

There is a mistake in the tutorial as it is not possible to make 3 default exports in the same main.js file. Other than that why export anything if it is no used outside the file?. Correct main.js :

import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, Link, browserHistory, IndexRoute  } from 'react-router'

class App extends React.Component {
...
}

class Home extends React.Component {
...
}


class About extends React.Component {
...
}


class Contact extends React.Component {
...
}


ReactDOM.render((
   <Router history = {browserHistory}>
      <Route path = "/" component = {App}>
         <IndexRoute component = {Home} />
         <Route path = "home" component = {Home} />
         <Route path = "about" component = {About} />
         <Route path = "contact" component = {Contact} />
      </Route>
   </Router>

), document.getElementById('app'))

EDIT2:

another thing is that this tutorial is based on react-router-V3 which has different api than v4.

How to add an UIViewController's view as subview

I feel like all of these answers are slightly incomplete, so here's the proper way to add a viewController's view as a subview of another viewController's view:

    [self addChildViewController:viewControllerToAdd];
    [self.view addSubview:viewControllerToAdd.view];
    [viewControllerToAdd didMoveToParentViewController:self];

If you'd like, you can copy this into your code as a snippet. SO doesn't seem to understand code replacement formatting, but they will show up clean in Xcode:

    [self addChildViewController:<#viewControllerToAdd#>];
    [self.view addSubview:<#viewControllerToAdd#>.view];
    [<#viewControllerToAdd#> didMoveToParentViewController:self];

willMove is called automatically w/ addChild. Thanks @iOSSergey

When your custom container calls the addChildViewController: method, it automatically calls the willMoveToParentViewController: method of the view controller to be added as a child before adding it.

Batch script to find and replace a string in text file without creating an extra output file for storing the modified file

@echo off 
    setlocal enableextensions disabledelayedexpansion

    set "search=%1"
    set "replace=%2"

    set "textFile=Input.txt"

    for /f "delims=" %%i in ('type "%textFile%" ^& break ^> "%textFile%" ') do (
        set "line=%%i"
        setlocal enabledelayedexpansion
        >>"%textFile%" echo(!line:%search%=%replace%!
        endlocal
    )

for /f will read all the data (generated by the type comamnd) before starting to process it. In the subprocess started to execute the type, we include a redirection overwritting the file (so it is emptied). Once the do clause starts to execute (the content of the file is in memory to be processed) the output is appended to the file.

Make Div Draggable using CSS

After going down the rabbit-hole of trying to do this myself by copy-pasting various code-snippets from Stack Overflow, I would highly recommend just using the InteractJS library, which allows you to create a draggable and resizable div (somewhat) easily.

What's better at freeing memory with PHP: unset() or $var = null

unset is not actually a function, but a language construct. It is no more a function call than a return or an include.

Aside from performance issues, using unset makes your code's intent much clearer.

What does !important mean in CSS?

!important is a part of CSS1.

Browsers supporting it: IE5.5+, Firefox 1+, Safari 3+, Chrome 1+.

It means, something like:

Use me, if there is nothing important else around!

Cant say it better.

What is the Python equivalent for a case/switch statement?

The direct replacement is if/elif/else.

However, in many cases there are better ways to do it in Python. See "Replacements for switch statement in Python?".

Why should a Java class implement comparable?

When you implement Comparable interface, you need to implement method compareTo(). You need it to compare objects, in order to use, for example, sorting method of ArrayList class. You need a way to compare your objects to be able to sort them. So you need a custom compareTo() method in your class so you can use it with the ArrayList sort method. The compareTo() method returns -1,0,1.

I have just read an according chapter in Java Head 2.0, I'm still learning.

Change Background color (css property) using Jquery

You're using a colon instead of a comma. Try:

$(body).css("background-color","blue");

You also need to wrap the id in quotes or it will look for a variable called #co

$("#co").click(change()

There are many more issues here. click isn't an HTML attribute. You want onclick (which is redundant). Try this:

<div id="co"> <!-- no onclick method needed -->
<script>
$(document).ready(function() {
    $("#co").click(function() {
        $("body").css("background-color","blue"); //edit, body must be in quotes!
    });
});
</script>

You were trying to call an undefined method. It looks like you were trying to declare it inside the callback statement? I'm not sure. But please compare this to your code and see the differences.

http://jsfiddle.net/CLwE5/ demo fiddle

Difference between git checkout --track origin/branch and git checkout -b branch origin/branch

The book seems to indicate that those commands yield the same effect:

The simple case is the example you just saw, running git checkout -b [branch] [remotename]/[branch]. If you have Git version 1.6.2 or later, you can also use the --track shorthand:

$ git checkout --track origin/serverfix 
Branch serverfix set up to track remote branch serverfix from origin. 
Switched to a new branch 'serverfix' 

To set up a local branch with a different name than the remote branch, you can easily use the first version with a different local branch name:

$ git checkout -b sf origin/serverfix

That's particularly handy when your bash or oh-my-zsh git completions are able to pull the origin/serverfix name for you - just append --track (or -t) and you are on your way.

Can I create view with parameter in MySQL?

CREATE VIEW MyView AS
   SELECT Column, Value FROM Table;


SELECT Column FROM MyView WHERE Value = 1;

Is the proper solution in MySQL, some other SQLs let you define Views more exactly.

Note: Unless the View is very complicated, MySQL will optimize this just fine.

Construct pandas DataFrame from items in nested dictionary

So I used to use a for loop for iterating through the dictionary as well, but one thing I've found that works much faster is to convert to a panel and then to a dataframe. Say you have a dictionary d

import pandas as pd
d
{'RAY Index': {datetime.date(2014, 11, 3): {'PX_LAST': 1199.46,
'PX_OPEN': 1200.14},
datetime.date(2014, 11, 4): {'PX_LAST': 1195.323, 'PX_OPEN': 1197.69},
datetime.date(2014, 11, 5): {'PX_LAST': 1200.936, 'PX_OPEN': 1195.32},
datetime.date(2014, 11, 6): {'PX_LAST': 1206.061, 'PX_OPEN': 1200.62}},
'SPX Index': {datetime.date(2014, 11, 3): {'PX_LAST': 2017.81,
'PX_OPEN': 2018.21},
datetime.date(2014, 11, 4): {'PX_LAST': 2012.1, 'PX_OPEN': 2015.81},
datetime.date(2014, 11, 5): {'PX_LAST': 2023.57, 'PX_OPEN': 2015.29},
datetime.date(2014, 11, 6): {'PX_LAST': 2031.21, 'PX_OPEN': 2023.33}}}

The command

pd.Panel(d)
<class 'pandas.core.panel.Panel'>
Dimensions: 2 (items) x 2 (major_axis) x 4 (minor_axis)
Items axis: RAY Index to SPX Index
Major_axis axis: PX_LAST to PX_OPEN
Minor_axis axis: 2014-11-03 to 2014-11-06

where pd.Panel(d)[item] yields a dataframe

pd.Panel(d)['SPX Index']
2014-11-03  2014-11-04  2014-11-05 2014-11-06
PX_LAST 2017.81 2012.10 2023.57 2031.21
PX_OPEN 2018.21 2015.81 2015.29 2023.33

You can then hit the command to_frame() to turn it into a dataframe. I use reset_index as well to turn the major and minor axis into columns rather than have them as indices.

pd.Panel(d).to_frame().reset_index()
major   minor      RAY Index    SPX Index
PX_LAST 2014-11-03  1199.460    2017.81
PX_LAST 2014-11-04  1195.323    2012.10
PX_LAST 2014-11-05  1200.936    2023.57
PX_LAST 2014-11-06  1206.061    2031.21
PX_OPEN 2014-11-03  1200.140    2018.21
PX_OPEN 2014-11-04  1197.690    2015.81
PX_OPEN 2014-11-05  1195.320    2015.29
PX_OPEN 2014-11-06  1200.620    2023.33

Finally, if you don't like the way the frame looks you can use the transpose function of panel to change the appearance before calling to_frame() see documentation here http://pandas.pydata.org/pandas-docs/dev/generated/pandas.Panel.transpose.html

Just as an example

pd.Panel(d).transpose(2,0,1).to_frame().reset_index()
major        minor  2014-11-03  2014-11-04  2014-11-05  2014-11-06
RAY Index   PX_LAST 1199.46    1195.323     1200.936    1206.061
RAY Index   PX_OPEN 1200.14    1197.690     1195.320    1200.620
SPX Index   PX_LAST 2017.81    2012.100     2023.570    2031.210
SPX Index   PX_OPEN 2018.21    2015.810     2015.290    2023.330

Hope this helps.

INNER JOIN vs INNER JOIN (SELECT . FROM)

There won't be much difference. Howver version 2 is easier when you have some calculations, aggregations, etc that should be joined outside of it

--Version 2 
SELECT p.Name, s.OrderQty 
FROM Product p 
INNER JOIN 
(SELECT ProductID, SUM(OrderQty) as OrderQty FROM SalesOrderDetail GROUP BY ProductID
HAVING SUM(OrderQty) >1000) s 
on p.ProductID = s.ProdctId 

How to prevent a dialog from closing when a button is clicked

For pre API 8 i solved the problem using a boolean flag, a dismiss listener and calling dialog.show again if in case the content of the editText wasn´t correct. Like this:

case ADD_CLIENT:
        LayoutInflater factoryClient = LayoutInflater.from(this);
        final View EntryViewClient = factoryClient.inflate(
                R.layout.alert_dialog_add_client, null);

        EditText ClientText = (EditText) EntryViewClient
                .findViewById(R.id.client_edit);

        AlertDialog.Builder builderClient = new AlertDialog.Builder(this);
        builderClient
                .setTitle(R.string.alert_dialog_client)
                .setCancelable(false)
                .setView(EntryViewClient)
                .setPositiveButton("Save",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int whichButton) {
                                EditText newClient = (EditText) EntryViewClient
                                        .findViewById(R.id.client_edit);
                                String newClientString = newClient
                                        .getText().toString();
                                if (checkForEmptyFields(newClientString)) {
                                    //If field is empty show toast and set error flag to true;
                                    Toast.makeText(getApplicationContext(),
                                            "Fields cant be empty",
                                            Toast.LENGTH_SHORT).show();
                                    add_client_error = true;
                                } else {
                                    //Here save the info and set the error flag to false
                                    add_client_error = false;
                                }
                            }
                        })
                .setNegativeButton("Cancel",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int id) {
                                add_client_error = false;
                                dialog.cancel();
                            }
                        });
        final AlertDialog alertClient = builderClient.create();
        alertClient.show();

        alertClient
                .setOnDismissListener(new DialogInterface.OnDismissListener() {

                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        //If the error flag was set to true then show the dialog again
                        if (add_client_error == true) {
                            alertClient.show();
                        } else {
                            return;
                        }

                    }
                });
        return true;

How do I monitor all incoming http requests?

You can also try the HTTP Debugger, it has the built-in ability to display incoming HTTP requests and does not require any changes to the system configuration.

HTTP Debugger

How to mark-up phone numbers?

The tel: scheme was used in the late 1990s and documented in early 2000 with RFC 2806 (which was obsoleted by the more-thorough RFC 3966 in 2004) and continues to be improved. Supporting tel: on the iPhone was not an arbitrary decision.

callto:, while supported by Skype, is not a standard and should be avoided unless specifically targeting Skype users.

Me? I'd just start including properly-formed tel: URIs on your pages (without sniffing the user agent) and wait for the rest of the world's phones to catch up :) .

Example:

_x000D_
_x000D_
<a href="tel:+18475555555">1-847-555-5555</a>
_x000D_
_x000D_
_x000D_

Sorting a vector of custom objects

A simple example using std::sort

struct MyStruct
{
    int key;
    std::string stringValue;

    MyStruct(int k, const std::string& s) : key(k), stringValue(s) {}
};

struct less_than_key
{
    inline bool operator() (const MyStruct& struct1, const MyStruct& struct2)
    {
        return (struct1.key < struct2.key);
    }
};

std::vector < MyStruct > vec;

vec.push_back(MyStruct(4, "test"));
vec.push_back(MyStruct(3, "a"));
vec.push_back(MyStruct(2, "is"));
vec.push_back(MyStruct(1, "this"));

std::sort(vec.begin(), vec.end(), less_than_key());

Edit: As Kirill V. Lyadvinsky pointed out, instead of supplying a sort predicate, you can implement the operator< for MyStruct:

struct MyStruct
{
    int key;
    std::string stringValue;

    MyStruct(int k, const std::string& s) : key(k), stringValue(s) {}

    bool operator < (const MyStruct& str) const
    {
        return (key < str.key);
    }
};

Using this method means you can simply sort the vector as follows:

std::sort(vec.begin(), vec.end());

Edit2: As Kappa suggests you can also sort the vector in the descending order by overloading a > operator and changing call of sort a bit:

struct MyStruct
{
    int key;
    std::string stringValue;

    MyStruct(int k, const std::string& s) : key(k), stringValue(s) {}

    bool operator > (const MyStruct& str) const
    {
        return (key > str.key);
    }
};

And you should call sort as:

std::sort(vec.begin(), vec.end(),greater<MyStruct>());