Programs & Examples On #Memory pressure

file path Windows format to java format

Java 7 and up supports the Path class (in java.nio package). You can use this class to convert a string-path to one that works for your current OS.

Using:

Paths.get("\\folder\\subfolder").toString()

on a Unix machine, will give you /folder/subfolder. Also works the other way around.

https://docs.oracle.com/javase/tutorial/essential/io/pathOps.html

Refresh Excel VBA Function Results

To switch to Automatic:

Application.Calculation = xlCalculationAutomatic    

To switch to Manual:

Application.Calculation = xlCalculationManual    

Installing Bower on Ubuntu

sudo ln -s /usr/bin/nodejs /usr/bin/node

or install legacy nodejs:

sudo apt-get install nodejs-legacy

As seen in this GitHub issue.

How to decode a Base64 string?

I had issues with spaces showing in between my output and there was no answer online at all to fix this issue. I literally spend many hours trying to find a solution and found one from playing around with the code to the point that I almost did not even know what I typed in at the time that I got it to work. Here is my fix for the issue: [System.Text.Encoding]::UTF8.GetString(([System.Convert]::FromBase64String($base64string)|?{$_}))

Android - Launcher Icon Size

LDPI should be 36 x 36.

MDPI 48 x 48.

TVDPI 64 x 64.

HDPI 72 x 72.

XHDPI 96 x 96.

XXHDPI 144 x 144.

XXXHDPI 192 x 192.

Alternative to header("Content-type: text/xml");

No. You can't send headers after they were sent. Try to use hooks in wordpress

List of tables, db schema, dump etc using the Python sqlite3 API

Check out here for dump. It seems there is a dump function in the library sqlite3.

Date in to UTC format Java

java.time

It’s about time someone provides the modern answer. The modern solution uses java.time, the modern Java date and time API. The classes SimpleDateFormat and Date used in the question and in a couple of the other answers are poorly designed and long outdated, the former in particular notoriously troublesome. TimeZone is poorly designed to. I recommend you avoid those.

    ZoneId utc = ZoneId.of("Etc/UTC");
    DateTimeFormatter targetFormatter = DateTimeFormatter.ofPattern(
            "MM/dd/yyyy hh:mm:ss a zzz", Locale.ENGLISH);

    String itsAlarmDttm = "2013-10-22T01:37:56";
    ZonedDateTime utcDateTime = LocalDateTime.parse(itsAlarmDttm)
            .atZone(ZoneId.systemDefault())
            .withZoneSameInstant(utc);
    String formatterUtcDateTime = utcDateTime.format(targetFormatter);
    System.out.println(formatterUtcDateTime);

When running in my time zone, Europe/Copenhagen, the output is:

10/21/2013 11:37:56 PM UTC

I have assumed that the string you got was in the default time zone of your JVM, a fragile assumption since that default setting can be changed at any time from another part of your program or another programming running in the same JVM. If you can, instead specify time zone explicitly, for example ZoneId.of("Europe/Podgorica") or ZoneId.of("Asia/Kolkata").

I am exploiting the fact that you string is in ISO 8601 format, the format the the modern classes parse as their default, that is, without any explicit formatter.

I am using a ZonedDateTime for the result date-time because it allows us to format it with UTC in the formatted string to eliminate any and all doubt. For other purposes one would typically have wanted an OffsetDateTime or an Instant instead.

Links

How to style icon color, size, and shadow of Font Awesome Icons

Looks like the FontAwesome icon color responds to text-info, text-error, etc.

<div style="font-size: 44px;">
   <i class="icon-umbrella icon-large text-error"></i>
</div>

java.util.Date and getYear()

tl;dr

LocalDate.now()       // Capture the date-only value current in the JVM’s current default time zone.
         .getYear()   // Extract the year number from that date.

2018

java.time

Both the java.util.Date and java.util.Calendar classes are legacy, now supplanted by the java.time framework built into Java 8 and later.

A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.

If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment, so your results may vary. Better to specify your desired/expected time zone explicitly as an argument.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "Africa/Tunis" ) ;  

If you want only the date without time-of-day, use LocalDate. This class lacks time zone info but you can specify a time zone to determine the current date.

ZoneId zoneId = ZoneId.of( "America/Montreal" );
LocalDate localDate = LocalDate.now( zoneId );

You can get the various pieces of information with getYear, getMonth, and getDayOfMonth. You will actually get the year number with java.time!

int year = localDate.getYear();

2016

If you want a date-time instead of just a date, use ZonedDateTime class.

ZonedDateTime zdt = ZonedDateTime.now( zoneId ) ;

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as java.util.Date, .Calendar, & java.text.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.

Much of the java.time functionality is back-ported to Java 6 & Java 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).

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.

Add item to array in VBScript

For your copy and paste ease

' add item to array
Function AddItem(arr, val)
    ReDim Preserve arr(UBound(arr) + 1)
    arr(UBound(arr)) = val
    AddItem = arr
End Function

Used like so

a = Array()
a = AddItem(a, 5)
a = AddItem(a, "foo")

OS X cp command in Terminal - No such file or directory

In my case, I had accidentally named a folder 'samples '. I couldn't see the space when I did 'ls -la'.

Eventually I realized this when I tried tabbing to autocomplete and saw 'samples\ /'.

To fix this I ran

mv samples\  samples

AngularJS sorting by property

I will add my upgraded version of filter which able to supports next syntax:

ng-repeat="(id, item) in $ctrl.modelData | orderObjectBy:'itemProperty.someOrder':'asc'

app.filter('orderObjectBy', function(){

         function byString(o, s) {
            s = s.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties
            s = s.replace(/^\./, '');           // strip a leading dot
            var a = s.split('.');
            for (var i = 0, n = a.length; i < n; ++i) {
                var k = a[i];
                if (k in o) {
                    o = o[k];
                } else {
                    return;
                }
            }
            return o;
        }

        return function(input, attribute, direction) {
            if (!angular.isObject(input)) return input;

            var array = [];
            for(var objectKey in input) {
                if (input.hasOwnProperty(objectKey)) {
                    array.push(input[objectKey]);
                }
            }

            array.sort(function(a, b){
                a = parseInt(byString(a, attribute));
                b = parseInt(byString(b, attribute));
                return direction == 'asc' ? a - b : b - a;
            });
            return array;
        }
    })

Thanks to Armin and Jason for their answers in this thread, and Alnitak in this thread.

could not extract ResultSet in hibernate

If you don't have 'HIBERNATE_SEQUENCE' sequence created in database (if use oracle or any sequence based database), you shall get same type of error;

Ensure the sequence is present there;

Socket File "/var/pgsql_socket/.s.PGSQL.5432" Missing In Mountain Lion (OS X Server)

I just created a new cluster and that worked for me, I was using (PostgreSQL) 9.3.20:

sudo pg_createcluster 9.3 main --start

Is there a way to perform "if" in python's lambda

Probably the worst python line I've written so far:

f = lambda x: sys.stdout.write(["2\n",][2*(x==2)-2])

If x == 2 you print,

if x != 2 you raise.

How to convert NSDate into unix timestamp iphone sdk?

If you want to store these time in a database or send it over the server...best is to use Unix timestamps. Here's a little snippet to get that:

+ (NSTimeInterval)getUTCFormateDate{

    NSDateComponents *comps = [[NSCalendar currentCalendar] 
                               components:NSDayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit 
                               fromDate:[NSDate date]];
    [comps setHour:0];
    [comps setMinute:0];    
    [comps setSecond:[[NSTimeZone systemTimeZone] secondsFromGMT]];

    return [[[NSCalendar currentCalendar] dateFromComponents:comps] timeIntervalSince1970];  
}

How to compare type of an object in Python?

For other types, check out the types module:

>>> import types
>>> x = "mystring"
>>> isinstance(x, types.StringType)
True
>>> x = 5
>>> isinstance(x, types.IntType)
True
>>> x = None
>>> isinstance(x, types.NoneType)
True

P.S. Typechecking is a bad idea.

tsc throws `TS2307: Cannot find module` for a local file

If use webstorm, press Ctrl+Alt+S and bring up the settings window. Languages&Frameworks>TypeScript, enable "use tsconfig.json" option.

How do I increase the contrast of an image in Python OpenCV

img = cv2.imread("/x2.jpeg")

image = cv2.resize(img, (1800, 1800))

alpha=1.5
beta=20

new_image=cv2.addWeighted(image,alpha,np.zeros(image.shape, image.dtype),0,beta)

cv2.imshow("new",new_image)
cv2.waitKey(0)
cv2.destroyAllWindows()

How to scroll to the bottom of a UITableView on the iPhone before the view appears

In Swift, you just need

self.tableView.scrollToNearestSelectedRowAtScrollPosition(UITableViewScrollPosition.Bottom, animated: true)

to make it automatically scroll to the buttom

Where does the iPhone Simulator store its data?

Looks like Xcode 6.0 has moved this location once again, at least for iOS 8 simulators.

~/Library/Developer/CoreSimulator/Devices/[DeviceID]/data/Containers/Data/Application/[AppID]

How do I enable --enable-soap in php on linux?

As far as your question goes: no, if activating from .ini is not enough and you can't upgrade PHP, there's not much you can do. Some modules, but not all, can be added without recompilation (zypper install php5-soap, yum install php-soap). If it is not enough, try installing some PEAR class for interpreted SOAP support (NuSOAP, etc.).

In general, the double-dash --switches are designed to be used when recompiling PHP from scratch.

You would download the PHP source package (as a compressed .tgz tarball, say), expand it somewhere and then, e.g. under Linux, run the configure script

./configure --prefix ...

The configure command used by your PHP may be shown with phpinfo(). Repeating it identical should give you an exact copy of the PHP you now have installed. Adding --enable-soap will then enable SOAP in addition to everything else.

That said, if you aren't familiar with PHP recompilation, don't do it. It also requires several ancillary libraries that you might, or might not, have available - freetype, gd, libjpeg, XML, expat, and so on and so forth (it's not enough they are installed; they must be a developer version, i.e. with headers and so on; in most distributions, having libjpeg installed might not be enough, and you might need libjpeg-dev also).

I have to keep a separate virtual machine with everything installed for my recompilation purposes.

java.nio.file.Path for a classpath resource

I wrote a small helper method to read Paths from your class resources. It is quite handy to use as it only needs a reference of the class you have stored your resources as well as the name of the resource itself.

public static Path getResourcePath(Class<?> resourceClass, String resourceName) throws URISyntaxException {
    URL url = resourceClass.getResource(resourceName);
    return Paths.get(url.toURI());
}  

What generates the "text file busy" message in Unix?

You may find this to be more common on CIFS/SMB network shares. Windows doesn't allow for a file to be written when something else has that file open, and even if the service is not Windows (it might be some other NAS product), it will likely reproduce the same behaviour. Potentially, it might also be a manifestation of some underlying NAS issue vaguely related to locking/replication.

How to make RatingBar to show five stars

You should just use numStars="5" in your XML, and set android:layout_width="wrap_content".
Then, you can play around with styles and other stuff, but the "wrap_content" in layout_width is what does the trick.

Flutter command not found

Do the following steps:

  1. Download the Flutter SDK Flutter SDK Archive

  2. Extract it where do you want (for example /home/development/flutter)

  3. Set your PATH, edit your file with this command gedit ~/.profile, you need to add this line

export PATH=[location_where_you_extracted_flutter]/flutter/bin:$PATH

I showed you above where I've extracted mine, so my export will look like this

export PATH=/home/myUser/development/flutter/bin:$PATH
  1. Save the file and close it.
  2. Run source ~/.profile to load the changes
  3. If you run now flutter doctor should work!

What is the difference between ArrayList.clear() and ArrayList.removeAll()?

The time complexity of ArrayList.clear() is O(n) and of removeAll is O(n^2).

So yes, ArrayList.clear is much faster.

Regex to match words of a certain length

Length of characters to be matched.

{n,m}  n <= length <= m
{n}    length == n
{n,}   length >= n

And by default, the engine is greedy to match this pattern. For example, if the input is 123456789, \d{2,5} will match 12345 which is with length 5.

If you want the engine returns when length of 2 matched, use \d{2,5}?

Android ImageView's onClickListener does not work

Same Silly thing happed with me.

I just copied one activity and pasted. Defined in Manifest.

Open from MainActivity.java but I was forgot that Copied Activity is getting some params in bundle and If I don't pass any params, just finished.

So My Activity is getting started but finished at same moment.

I had written Toast and found this silly mistake. :P

Breaking a list into multiple columns in Latex

By combining the multicol package and enumitem package packages it is easy to define environments that are multi-column analogues of the enumerate and itemize environments:

\documentclass{article}
\usepackage{enumitem}
\usepackage{multicol}

\newlist{multienum}{enumerate}{1}
\setlist[multienum]{
    label=\alph*),
    before=\begin{multicols}{2},
    after=\end{multicols}
}

\newlist{multiitem}{itemize}{1}
\setlist[multiitem]{
    label=\textbullet,
    before=\begin{multicols}{2},
    after=\end{multicols}
}

\begin{document}

  \textsf{Two column enumerate}
  \begin{multienum}
    \item item 1
    \item item 2
    \item item 3
    \item item 4
    \item item 5
    \item item 6
  \end{multienum}

  \textsf{Two column itemize}
  \begin{multiitem}
    \item item 1
    \item item 2
    \item item 3
    \item item 4
    \item item 5
    \item item 6
  \end{multiitem}

\end{document}

The output is what you would hope for:

enter image description here

Recursively find files with a specific extension

Using find's -regex argument:

find . -regex '.*/Robert\.\(h\|cpp\)$'

Or just using -name:

find . -name 'Robert.*' -a \( -name '*.cpp' -o -name '*.h' \)

How do I sum values in a column that match a given condition using pandas?

The essential idea here is to select the data you want to sum, and then sum them. This selection of data can be done in several different ways, a few of which are shown below.

Boolean indexing

Arguably the most common way to select the values is to use Boolean indexing.

With this method, you find out where column 'a' is equal to 1 and then sum the corresponding rows of column 'b'. You can use loc to handle the indexing of rows and columns:

>>> df.loc[df['a'] == 1, 'b'].sum()
15

The Boolean indexing can be extended to other columns. For example if df also contained a column 'c' and we wanted to sum the rows in 'b' where 'a' was 1 and 'c' was 2, we'd write:

df.loc[(df['a'] == 1) & (df['c'] == 2), 'b'].sum()

Query

Another way to select the data is to use query to filter the rows you're interested in, select column 'b' and then sum:

>>> df.query("a == 1")['b'].sum()
15

Again, the method can be extended to make more complicated selections of the data:

df.query("a == 1 and c == 2")['b'].sum()

Note this is a little more concise than the Boolean indexing approach.

Groupby

The alternative approach is to use groupby to split the DataFrame into parts according to the value in column 'a'. You can then sum each part and pull out the value that the 1s added up to:

>>> df.groupby('a')['b'].sum()[1]
15

This approach is likely to be slower than using Boolean indexing, but it is useful if you want check the sums for other values in column a:

>>> df.groupby('a')['b'].sum()
a
1    15
2     8

PHP string concatenation

This should be faster.

while ($personCount < 10) {
    $result .= "{$personCount} people ";
    $personCount++;
}

echo $result;

How to animate button in android?

Dependency

Add it in your root build.gradle at the end of repositories:

allprojects {
repositories {
    ...
    maven { url "https://jitpack.io" }
}}

and then add dependency dependencies { compile 'com.github.varunest:sparkbutton:1.0.5' }

Usage

XML

<com.varunest.sparkbutton.SparkButton
        android:id="@+id/spark_button"
        android:layout_width="40dp"
        android:layout_height="40dp"
        app:sparkbutton_activeImage="@drawable/active_image"
        app:sparkbutton_inActiveImage="@drawable/inactive_image"
        app:sparkbutton_iconSize="40dp"
        app:sparkbutton_primaryColor="@color/primary_color"
        app:sparkbutton_secondaryColor="@color/secondary_color" />

Java (Optional)

SparkButton button  = new SparkButtonBuilder(context)
            .setActiveImage(R.drawable.active_image)
            .setInActiveImage(R.drawable.inactive_image)
            .setDisabledImage(R.drawable.disabled_image)
            .setImageSizePx(getResources().getDimensionPixelOffset(R.dimen.button_size))
            .setPrimaryColor(ContextCompat.getColor(context, R.color.primary_color))
            .setSecondaryColor(ContextCompat.getColor(context, R.color.secondary_color))
            .build();

Check if program is running with bash shell script?

If you want to execute that command, you should probably change:

PROCESS_NUM='ps -ef | grep "$1" | grep -v "grep" | wc -l'

to:

PROCESS_NUM=$(ps -ef | grep "$1" | grep -v "grep" | wc -l)

Facebook share button and custom text

This is the current solution (Dec 2014) and works quite well. It features

  • open a popup window
  • self-contained snippet, doesn't require anything else
  • works with or without JS. If JS is disabled, the share window still opens, albeit not as a small popup.

<a onclick="return !window.open(this.href, 'Share on Facebook', 'width=640, height=536')" href="https://www.facebook.com/sharer/sharer.php?u=href=$url&display=popup&ref=plugin" target="_window"><img src='/_img/icons/facebook.png' /></a>

$url var should be defined as the URL to share.

Call a Class From another class

First create an object of class2 in class1 and then use that object to call any function of class2 for example write this in class1

class2 obj= new class2();
obj.thefunctioname(args);

How can I have linebreaks in my long LaTeX equations?

There are a couple ways you can deal with this. First, and perhaps best, is to rework your equation so that it is not so long; it is likely unreadable if it is that long.

If it must be so, check out the AMS Short Math Guide for some ways to handle it. (on the second page)

Personally, I'd use an align environment, so that the breaking and alignment can be precisely controlled. e.g.

\begin{align*}
   x&+y+\dots+\dots+x_100000000\\
   &+x_100000001+\dots+\dots
\end{align*}

which would line up the first plus signs of each line... but obviously, you can set the alignments wherever you like.

HashMap: One Key, multiple Values

Libraries exist to do this, but the simplest plain Java way is to create a Map of List like this:

Map<Object,ArrayList<Object>> multiMap = new HashMap<>();

Cast Object to Generic Type for returning

You have to use a Class instance because of the generic type erasure during compilation.

public static <T> T convertInstanceOfObject(Object o, Class<T> clazz) {
    try {
        return clazz.cast(o);
    } catch(ClassCastException e) {
        return null;
    }
}

The declaration of that method is:

public T cast(Object o)

This can also be used for array types. It would look like this:

final Class<int[]> intArrayType = int[].class;
final Object someObject = new int[]{1,2,3};
final int[] instance = convertInstanceOfObject(someObject, intArrayType);

Note that when someObject is passed to convertToInstanceOfObject it has the compile time type Object.

How do I force Robocopy to overwrite files?

I did this for a home folder where all the folders are on the desktops of the corresponding users, reachable through a shortcut which did not have the appropriate permissions, so that users couldn't see it even if it was there. So I used Robocopy with the parameter to overwrite the file with the right settings:

FOR /F "tokens=*" %G IN ('dir /b') DO robocopy  "\\server02\Folder with shortcut" "\\server02\home\%G\Desktop" /S /A /V /log+:C:\RobocopyShortcut.txt /XF *.url *.mp3 *.hta *.htm *.mht *.js *.IE5 *.css *.temp *.html *.svg *.ocx *.3gp *.opus *.zzzzz *.avi *.bin *.cab *.mp4 *.mov *.mkv *.flv *.tiff *.tif *.asf *.webm *.exe *.dll *.dl_ *.oc_ *.ex_ *.sy_ *.sys *.msi *.inf *.ini *.bmp *.png *.gif *.jpeg *.jpg *.mpg *.db *.wav *.wma *.wmv *.mpeg *.tmp *.old *.vbs *.log *.bat *.cmd *.zip /SEC /IT /ZB /R:0

As you see there are many file types which I set to ignore (just in case), just set them for your needs or your case scenario.

It was tested on Windows Server 2012, and every switch is documented on Microsoft's sites and others.

Run java jar file on a server as background process

You can try this:

#!/bin/sh
nohup java -jar /web/server.jar &

The & symbol, switches the program to run in the background.

The nohup utility makes the command passed as an argument run in the background even after you log out.

jQuery get value of selected radio button

I am not a javascript person, but I found here for searching this problem. For who google it and find here, I am hoping that this helps some. So, as in question if we have a list of radio buttons:

<div class="list">
    <input type="radio" name="b1" value="1">
    <input type="radio" name="b2" value="2" checked="checked">
    <input type="radio" name="b3" value="3">
</div>

I can find which one selected with this selector:

$('.list input[type="radio"]:checked:first').val();

Even if there is no element selected, I still don't get undefined error. So, you don't have to write extra if statement before taking element's value.

Here is very basic jsfiddle example.

Using awk to print all columns from the nth to the last

I personally tried all the answers mentioned above, but most of them were a bit complex or just not right. The easiest way to do it from my point of view is:

awk -F" " '{ for (i=4; i<=NF; i++) print $i }'
  1. Where -F" " defines the delimiter for awk to use. In my case is the whitespace, which is also the default delimiter for awk. This means that -F" " can be ignored.

  2. Where NF defines the total number of fields/columns. Therefore the loop will begin from the 4th field up to the last field/column.

  3. Where $N retrieves the value of the Nth field. Therefore print $i will print the current field/column based based on the loop count.

How do I get the current absolute URL in Ruby on Rails?

You can use the ruby method:

:root_url

which will get the full path with base url:

localhost:3000/bla

Using TortoiseSVN via the command line

There is a confusion that is causing a lot of TortoiseSVN users to use the wrong command line tools when they actually were looking for svn.exe command line client.

What should I do or can't TortoiseSVN be used from the command line?

svn.exe

If you want to run Subversion commands from the command prompt, you should run the svn.exe command line client. TortoiseSVN 1.6.x and older versions did not include SVN command-line tools, but modern versions do.

If you want to get SVN command line tools without having to install TortoiseSVN, check the SVN binary distributions page or simply download the latest version from VisualSVN downloads page.

If you have SVN command line tools installed on your system, but still get the error 'svn' is not recognized as an internal or external command, you should check %PATH% environment variable. %PATH% must include the path to SVN tools directory e.g. C:\Program Files (x86)\VisualSVN\bin.

TortoiseProc.exe

Apart from svn.exe, TortoiseSVN comes with TortoiseProc.exe that can be called from command prompt. In most cases, you do not need to use this tool, because it should be only used for GUI automation. TortoiseProc.exe is not a replacement for SVN command-line client.

How can I detect when the mouse leaves the window?

This worked for me. A combination of some of the answers here. And I included the code showing a model only once. And the model goes away when clicked anywhere else.

<script>
    var leave = 0
    //show modal when mouse off of page
    $("html").mouseleave(function() {
       //check for first time
       if (leave < 1) {
          modal.style.display = "block";
          leave = leave + 1;
       }
    });

    // Get the modal with id="id01"
       var modal = document.getElementById('id01');

    // When the user clicks anywhere outside of the modal, close it
       window.onclick = function(event) {
          if (event.target == modal) {
             modal.style.display = "none";
          }
       }
</script>

How to access your website through LAN in ASP.NET

You may also need to enable the World Wide Web Service inbound firewall rule.

On Windows 7: Start -> Control Panel -> Windows Firewall -> Advanced Settings -> Inbound Rules

Find World Wide Web Services (HTTP Traffic-In) in the list and select to enable the rule. Change is pretty much immediate.

How to round up value C# to the nearest integer?

It is simple. So follow this code.

decimal d = 10.5;
int roundNumber = (int)Math.Floor(d + 0.5);

Result is 11

importing pyspark in python shell

To get rid of ImportError: No module named py4j.java_gateway, you need to add following lines:

import os
import sys


os.environ['SPARK_HOME'] = "D:\python\spark-1.4.1-bin-hadoop2.4"


sys.path.append("D:\python\spark-1.4.1-bin-hadoop2.4\python")
sys.path.append("D:\python\spark-1.4.1-bin-hadoop2.4\python\lib\py4j-0.8.2.1-src.zip")

try:
    from pyspark import SparkContext
    from pyspark import SparkConf

    print ("success")

except ImportError as e:
    print ("error importing spark modules", e)
    sys.exit(1)

How to find top three highest salary in emp table in oracle?

Select ename, job, sal from emp
    where sal >=(select max(sal) from emp
    where sal < (select max(sal) from emp
    where sal < (select max(sal) from emp)))
    order by sal;

ENAME      JOB              SAL
---------- --------- ----------
KING       PRESIDENT       5000
FORD       ANALYST         3000
SCOTT      ANALYST         3000

How to plot two histograms together in R?

Here is an even simpler solution using base graphics and alpha-blending (which does not work on all graphics devices):

set.seed(42)
p1 <- hist(rnorm(500,4))                     # centered at 4
p2 <- hist(rnorm(500,6))                     # centered at 6
plot( p1, col=rgb(0,0,1,1/4), xlim=c(0,10))  # first histogram
plot( p2, col=rgb(1,0,0,1/4), xlim=c(0,10), add=T)  # second

The key is that the colours are semi-transparent.

Edit, more than two years later: As this just got an upvote, I figure I may as well add a visual of what the code produces as alpha-blending is so darn useful:

enter image description here

Extract public/private key from PKCS12 file for later use in SSH-PK-Authentication

Update: I noticed that my answer was just a poor duplicate of a well explained question on https://unix.stackexchange.com/... by BryKKan

Here is an extract from it:

openssl pkcs12 -in <filename.pfx> -nocerts -nodes | sed -ne '/-BEGIN PRIVATE KEY-/,/-END PRIVATE KEY-/p' > <clientcert.key>

openssl pkcs12 -in <filename.pfx> -clcerts -nokeys | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > <clientcert.cer>

openssl pkcs12 -in <filename.pfx> -cacerts -nokeys -chain | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > <cacerts.cer>

Setting the target version of Java in ant javac

Use "target" attribute and remove the 'compiler' attribute. See here. So it should go something like this:

<target name="compile">
  <javac target="1.5" srcdir=.../>
</target>

Hope this helps

'0000-00-00 00:00:00' can not be represented as java.sql.Timestamp error

You can use this JDBC URL directly in your data source configuration:

jdbc:mysql://yourserver:3306/yourdatabase?zeroDateTimeBehavior=convertToNull

How to remove "index.php" in codeigniter's path

I have tried many solutions but the one i came up with is this:

DirectoryIndex index.php
RewriteEngine on

RewriteCond $1 !^(index\.php|(.*)\.swf|forums|images|css|downloads|jquery|js|robots  \.txt|favicon\.ico)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ ./index.php?$1 [L,QSA]

This iwill remove the index.php from the url as required.

MongoDB relationships: embed or reference?

In general, embed is good if you have one-to-one or one-to-many relationships between entities, and reference is good if you have many-to-many relationships.

How can I execute a PHP function in a form action?

In PHP functions will not be evaluated inside strings, because there are different rules for variables.

<?php
function name() {
  return 'Mark';
}

echo 'My name is: name()';   // Output: My name is name()
echo 'My name is: '. name(); // Output: My name is Mark

The action parameter to the tag in HTML should not reference the PHP function you want to run. Action should refer to a page on the web server that will process the form input and return new HTML to the user. This can be the same location as the PHP script that outputs the form, or some people prefer to make a separate PHP file to handle actions.

The basic process is the same either way:

  1. Generate HTML form to the user.
  2. User fills in the form, clicks submit.
  3. The form data is sent to the locations defined by action on the server.
  4. The script validates the data and does something with it.
  5. Usually a new HTML page is returned.

A simple example would be:

<?php
// $_POST is a magic PHP variable that will always contain
// any form data that was posted to this page.
// We check here to see if the textfield called 'name' had
// some data entered into it, if so we process it, if not we
// output the form.
if (isset($_POST['name'])) {
  print_name($_POST['name']);
}
else {
  print_form();
}

// In this function we print the name the user provided.
function print_name($name) {
  // $name should be validated and checked here depending on use.
  // In this case we just HTML escape it so nothing nasty should
  // be able to get through:
  echo 'Your name is: '. htmlentities($name);
}

// This function is called when no name was sent to us over HTTP.
function print_form() {
  echo '
    <form name="form1" method="post" action="">
    <p><label><input type="text" name="name" id="textfield"></label></p>
    <p><label><input type="submit" name="button" id="button" value="Submit"></label></p>
    </form>
  ';
}
?>

For future information I recommend reading the PHP tutorials: http://php.net/tut.php

There is even a section about Dealing with forms.

set value of input field by php variable's value

inside the Form, You can use this code. Replace your variable name (i use $variable)

<input type="text" value="<?php echo (isset($variable))?$variable:'';?>">

Switch/toggle div (jQuery)

Since one div is initially hidden, you can simply call toggle for both divs:

<a href="javascript:void(0);" id="forgot-password">forgot password?</a>
<div id="login-form">login form</div>

<div id="recover-password" style="display:none;">recover password</div>

<script type="text/javascript">
$(function(){
  $('#forgot-password').click(function(){
     $('#login-form').toggle();
     $('#recover-password').toggle(); 
  });
});
</script>

In Node.js, how do I turn a string to a json?

use the JSON function >

JSON.parse(theString)

C Linking Error: undefined reference to 'main'

Generally you compile most .c files in the following way:

gcc foo.c -o foo. It might vary depending on what #includes you used or if you have any external .h files. Generally, when you have a C file, it looks somewhat like the following:

#include <stdio.h>
    /* any other includes, prototypes, struct delcarations... */
    int main(){
    */ code */
}

When I get an 'undefined reference to main', it usually means that I have a .c file that does not have int main() in the file. If you first learned java, this is an understandable manner of confusion since in Java, your code usually looks like the following:

//any import statements you have
public class Foo{
    int main(){}
 }

I would advise looking to see if you have int main() at the top.

How to modify list entries during for loop?

It's considered poor form. Use a list comprehension instead, with slice assignment if you need to retain existing references to the list.

a = [1, 3, 5]
b = a
a[:] = [x + 2 for x in a]
print(b)

How can I generate a tsconfig.json file?

i am using this,

yarn tsc --init

this fixed it for me

JQuery, setTimeout not working

SetTimeout is used to make your set of code to execute after a specified time period so for your requirements its better to use setInterval because that will call your function every time at a specified time interval.

commons httpclient - Adding query string parameters to GET/POST request

I am using httpclient 4.4.

For solr query I used the following way and it worked.

NameValuePair nv2 = new BasicNameValuePair("fq","(active:true) AND (category:Fruit OR category1:Vegetable)");
nvPairList.add(nv2);
NameValuePair nv3 = new BasicNameValuePair("wt","json");
nvPairList.add(nv3);
NameValuePair nv4 = new BasicNameValuePair("start","0");
nvPairList.add(nv4);
NameValuePair nv5 = new BasicNameValuePair("rows","10");
nvPairList.add(nv5);

HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
URI uri = new URIBuilder(request.getURI()).addParameters(nvPairList).build();
            request.setURI(uri);

HttpResponse response = client.execute(request);    
if (response.getStatusLine().getStatusCode() != 200) {

}

BufferedReader br = new BufferedReader(
                             new InputStreamReader((response.getEntity().getContent())));

String output;
System.out.println("Output  .... ");
String respStr = "";
while ((output = br.readLine()) != null) {
    respStr = respStr + output;
    System.out.println(output);
}

How can I see the size of files and directories in linux?

ls -l --block-size=M will give you a long format listing (needed to actually see the file size) and round file sizes up to the nearest MiB.

If you want MB (10^6 bytes) rather than MiB (2^20 bytes) units, use --block-size=MB instead.

If you don't want the M suffix attached to the file size, you can use something like --block-size=1M. Thanks Stéphane Chazelas for suggesting this.

This is described in the man page for ls; man ls and search for SIZE. It allows for units other than MB/MiB as well, and from the looks of it (I didn't try that) arbitrary block sizes as well (so you could see the file size as number of 412-byte blocks, if you want to).

Note that the --block-size parameter is a GNU extension on top of the Open Group's ls, so this may not work if you don't have a GNU userland (which most Linux installations do). The ls from GNU coreutils 8.5 does support --block-size as described above.

How to stretch div height to fill parent div - CSS

What suited my purpose was to create a div that was always bounded within the overall browser window by a fixed amount.

What worked, at least on firefox, was this

<div style="position: absolute; top: 127px; left: 75px;right: 75px; bottom: 50px;">

Insofar as the actual window is not forced into scrolling, the div preserves its boundaries to the window edge during all re-sizing.

Hope this saves someone some time.

Git with SSH on Windows

I've found my ssh.exe in "C:/Program Files/Git/usr/bin" directory

How do I deal with "signed/unsigned mismatch" warnings (C4018)?

You can use:

  1. size_t type, to remove warning messages
  2. iterators + distance (like are first hint)
  3. only iterators
  4. function object

For example:

// simple class who output his value
class ConsoleOutput
{
public:
  ConsoleOutput(int value):m_value(value) { }
  int Value() const { return m_value; }
private:
  int m_value;
};

// functional object
class Predicat
{
public:
  void operator()(ConsoleOutput const& item)
  {
    std::cout << item.Value() << std::endl;
  }
};

void main()
{
  // fill list
  std::vector<ConsoleOutput> list;
  list.push_back(ConsoleOutput(1));
  list.push_back(ConsoleOutput(8));

  // 1) using size_t
  for (size_t i = 0; i < list.size(); ++i)
  {
    std::cout << list.at(i).Value() << std::endl;
  }

  // 2) iterators + distance, for std::distance only non const iterators
  std::vector<ConsoleOutput>::iterator itDistance = list.begin(), endDistance = list.end();
  for ( ; itDistance != endDistance; ++itDistance)
  {
    // int or size_t
    int const position = static_cast<int>(std::distance(list.begin(), itDistance));
    std::cout << list.at(position).Value() << std::endl;
  }

  // 3) iterators
  std::vector<ConsoleOutput>::const_iterator it = list.begin(), end = list.end();
  for ( ; it != end; ++it)
  {
    std::cout << (*it).Value() << std::endl;
  }
  // 4) functional objects
  std::for_each(list.begin(), list.end(), Predicat());
}

Python style - line continuation with strings?

Just pointing out that it is use of parentheses that invokes auto-concatenation. That's fine if you happen to already be using them in the statement. Otherwise, I would just use '\' rather than inserting parentheses (which is what most IDEs do for you automatically). The indent should align the string continuation so it is PEP8 compliant. E.g.:

my_string = "The quick brown dog " \
            "jumped over the lazy fox"

Hash Map in Python

Python Counter is also a good option in this case:

from collections import Counter

counter = Counter(["Sachin Tendulkar", "Sachin Tendulkar", "other things"])

print(counter)

This returns a dict with the count of each element in the list:

Counter({'Sachin Tendulkar': 2, 'other things': 1})

How do you open an SDF file (SQL Server Compact Edition)?

Download and install LINQPad, it works for SQL Server, MySQL, SQLite and also SDF (SQL CE 4.0).

Steps for open SDF Files:

  1. Click Add Connection

  2. Select Build data context automatically and Default (LINQ to SQL), then Next.

  3. Under Provider choose SQL CE 4.0.

  4. Under Database with Attach database file selected, choose Browse to select your .sdf file.

  5. Click OK.

How to write a caption under an image?

CSS is your friend; there is no need for the center tag (not to mention it is quite depreciated) nor the excessive non-breaking spaces. Here is a simple example:

CSS

.images {
    text-align:center;
}
.images img {
    width:100px;
    height:100px;
}
.images div {
    width:100px;
    text-align:center;
}
.images div span {
    display:block;
}
.margin_right {
    margin-right:50px;
}
.float {
    float:left;
}
.clear {
    clear:both;
    height:0;
    width:0;
}

HTML

<div class="images">
    <div class="float margin_right">
        <a href="http://xyz.com/hello"><img src="hello.png" width="100px" height="100px" /></a>
        <span>This is some text</span>
    </div>
    <div class="float">
        <a href="http://xyz.com/hi"><img src="hi.png" width="100px" height="100px" /></a>
        <span>And some more text</span>
    </div>
    <span class="clear"></span>
</div>

Npm Please try using this command again as root/administrator

It turns out that you don’t have to run the command again as Administrator, and doing so won’t fix the problem.

Try:

  1. npm cache clean first.

  2. If that doesn’t fix things, take a look in %APPDATA%\npm-cache, or if you’re using PowerShell, $env:APPDATA\npm-cache.

After cleaning the cache, you may still be left with remnants. Manually remove everything in that directory, and try again. This has always fixed things for me.

As @Crazzymatt was mentioning, as of the npm@5 version and up, we need to use npm cache verify instead of npm cache clean. Or else you will get an error as preceding.

npm ERR! As of npm@5, the npm cache self-heals from corruption issues and data extracted from the cache is guaranteed to be valid. If you want to make sure everything is consistent, use 'npm cache verify' instead.

(Source: MSDN Blog post)

What is the easiest way to get the current day of the week in Android?

If you do not want to use Calendar class at all you can use this

String weekday_name = new SimpleDateFormat("EEEE", Locale.ENGLISH).format(System.currentTimeMillis());

i.e., result is,

"Sunday"

Is there a way to call a stored procedure with Dapper?

I think the answer depends on which features of stored procedures you need to use.

Stored procedures returning a result set can be run using Query; stored procedures which don't return a result set can be run using Execute - in both cases (using EXEC <procname>) as the SQL command (plus input parameters as necessary). See the documentation for more details.

As of revision 2d128ccdc9a2 there doesn't appear to be native support for OUTPUT parameters; you could add this, or alternatively construct a more complex Query command which declared TSQL variables, executed the SP collecting OUTPUT parameters into the local variables and finallyreturned them in a result set:

DECLARE @output int

EXEC <some stored proc> @i = @output OUTPUT

SELECT @output AS output1

how to select first N rows from a table in T-SQL?

Try this:

SELECT * FROM USERS LIMIT 10;

Why do we have to specify FromBody and FromUri?

The default behavior is:

  1. If the parameter is a primitive type (int, bool, double, ...), Web API tries to get the value from the URI of the HTTP request.

  2. For complex types (your own object, for example: Person), Web API tries to read the value from the body of the HTTP request.

So, if you have:

  • a primitive type in the URI, or
  • a complex type in the body

...then you don't have to add any attributes (neither [FromBody] nor [FromUri]).

But, if you have a primitive type in the body, then you have to add [FromBody] in front of your primitive type parameter in your WebAPI controller method. (Because, by default, WebAPI is looking for primitive types in the URI of the HTTP request.)

Or, if you have a complex type in your URI, then you must add [FromUri]. (Because, by default, WebAPI is looking for complex types in the body of the HTTP request by default.)

Primitive types:

public class UsersController : ApiController
{
    // api/users
    public HttpResponseMessage Post([FromBody]int id)
    {

    }
    // api/users/id
    public HttpResponseMessage Post(int id)
    {

    }       
}

Complex types:

public class UsersController : ApiController
{       
    // api/users
    public HttpResponseMessage Post(User user)
    {

    }

    // api/users/user
    public HttpResponseMessage Post([FromUri]User user)
    {

    }       
}

This works as long as you send only one parameter in your HTTP request. When sending multiple, you need to create a custom model which has all your parameters like this:

public class MyModel
{
    public string MyProperty { get; set; }
    public string MyProperty2 { get; set; }
}

[Route("search")]
[HttpPost]
public async Task<dynamic> Search([FromBody] MyModel model)
{
    // model.MyProperty;
    // model.MyProperty2;
}

From Microsoft's documentation for parameter binding in ASP.NET Web API:

When a parameter has [FromBody], Web API uses the Content-Type header to select a formatter. In this example, the content type is "application/json" and the request body is a raw JSON string (not a JSON object). At most one parameter is allowed to read from the message body.

This should work:

public HttpResponseMessage Post([FromBody] string name) { ... }

This will not work:

// Caution: This won't work!    
public HttpResponseMessage Post([FromBody] int id, [FromBody] string name) { ... }

The reason for this rule is that the request body might be stored in a non-buffered stream that can only be read once.

CodeIgniter PHP Model Access "Unable to locate the model you have specified"

Just adding my problem i had:

$this->load->model("planning/plan_model.php");

and the .php shouldnt be there, so it should have been:

$this->load->model("planning/plan_model");

hope this helps someone

How to send data with angularjs $http.delete() request?

Please Try to pass parameters in httpoptions, you can follow function below

deleteAction(url, data) {
    const authToken = sessionStorage.getItem('authtoken');
    const options = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
        Authorization: 'Bearer ' + authToken,
      }),
      body: data,
    };
    return this.client.delete(url, options);
  }

How to make input type= file Should accept only pdf and xls

You could do so by using the attribute accept and adding allowed mime-types to it. But not all browsers do respect that attribute and it could easily be removed via some code inspector. So in either case you need to check the file type on the server side (your second question).

Example:

<input type="file" name="upload" accept="application/pdf,application/vnd.ms-excel" />

To your third question "And when I click the files (PDF/XLS) on webpage it automatically should open.":

You can't achieve that. How a PDF or XLS is opened on the client machine is set by the user.

how can I connect to a remote mongo server from Mac OS terminal

With Mongo 3.2 and higher just use your connection string as is:

mongo mongodb://username:[email protected]:10011/my_database

Getting TypeError: __init__() missing 1 required positional argument: 'on_delete' when trying to add parent table after child table with entries

Since Django 2.x, on_delete is required.

Django Documentation

Deprecated since version 1.9: on_delete will become a required argument in Django 2.0. In older versions it defaults to CASCADE.

MySQL error 1449: The user specified as a definer does not exist

The database user also seems to be case-sensitive, so while I had a root'@'% user I didn't have a ROOT'@'% user. I changed the user to be uppercase via workbench and the problem was resolved!

How to Git stash pop specific stash in 1.8.3?

If you want to be sure to not have to deal with quotes for the syntax stash@{x}, use Git 2.11 (Q4 2016)

See commit a56c8f5 (24 Oct 2016) by Aaron M Watson (watsona4).
(Merged by Junio C Hamano -- gitster -- in commit 9fa1f90, 31 Oct 2016)

stash: allow stashes to be referenced by index only

Instead of referencing "stash@{n}" explicitly, make it possible to simply reference as "n".
Most users only reference stashes by their position in the stash stack (what I refer to as the "index" here).

The syntax for the typical stash (stash@{n}) is slightly annoying and easy to forget, and sometimes difficult to escape properly in a script.

Because of this the capability to do things with the stash by simply referencing the index is desirable.

So:

git stash drop 1
git stash pop 1
git stash apply 1
git stash show 1

HashMap(key: String, value: ArrayList) returns an Object instead of ArrayList?

How is the HashMap declaration expressed in that scope? It should be:

HashMap<String, ArrayList> dictMap

If not, it is assumed to be Objects.

For instance, if your code is:

HashMap dictMap = new HashMap<String, ArrayList>();
...
ArrayList current = dictMap.get(dictCode);

that will not work. Instead you want:

HashMap<String, ArrayList> dictMap = new HashMap<String, Arraylist>();
...
ArrayList current = dictMap.get(dictCode);

The way generics work is that the type information is available to the compiler, but is not available at runtime. This is called type erasure. The implementation of HashMap (or any other generics implementation) is dealing with Object. The type information is there for type safety checks during compile time. See the Generics documentation.

Also note that ArrayList is also implemented as a generic class, and thus you might want to specify a type there as well. Assuming your ArrayList contains your class MyClass, the line above might be:

HashMap<String, ArrayList<MyClass>> dictMap

Space between Column's children in Flutter

The sized box will not help in the case, the phone is in landscape mode.

body: Column(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: <Widget>[
        Expanded(
           child: Container(
            margin: EdgeInsets.all(15.0),
            decoration: BoxDecoration(
              color: Color(0xFF1D1E33),
              borderRadius: BorderRadius.circular(10.0),
            ),
          ),
        ),
        Expanded(
           child: Container(
            margin: EdgeInsets.all(15.0),
            decoration: BoxDecoration(
              color: Color(0xFF1D1E33),
              borderRadius: BorderRadius.circular(10.0),
            ),
          ),
        ),
        Expanded(
           child: Container(
            margin: EdgeInsets.all(15.0),
            decoration: BoxDecoration(
              color: Color(0xFF1D1E33),
              borderRadius: BorderRadius.circular(10.0),
            ),
          ),
        ),
      ],
     )

Connecting to Microsoft SQL server using Python

I Prefer this way ... it was much easier

http://www.pymssql.org/en/stable/pymssql_examples.html

conn = pymssql.connect("192.168.10.198", "odoo", "secret", "EFACTURA")
cursor = conn.cursor()
cursor.execute('SELECT * FROM usuario')

How to manually trigger validation with jQuery validate?

In my similar case, I had my own validation logic and just wanted to use jQuery validation to show the message. This was what I did.

_x000D_
_x000D_
//1) Enable jQuery validation_x000D_
var validator = $('#myForm').validate();_x000D_
_x000D_
$('#myButton').click(function(){_x000D_
  //my own validation logic here_x000D_
  //....._x000D_
  //2) when validation failed, show the error message manually_x000D_
  validator.showErrors({_x000D_
    'myField': 'my custom error message'_x000D_
  });_x000D_
});
_x000D_
_x000D_
_x000D_

Create two-dimensional arrays and access sub-arrays in Ruby

Here is the simple version

 #one
 a = [[0]*10]*10

 #two
row, col = 10, 10
a = [[0]*row]*col

Replace \n with <br />

For some reason using python3 I had to escape the "\"-sign

somestring.replace('\\n', '')

Hope this helps someone else!

Fade In on Scroll Down, Fade Out on Scroll Up - based on element position in window

I know it's late, but I take the original code and change some stuff to control easily the css. So I made a code with the addClass() and the removeClass()

Here the full code : http://jsfiddle.net/e5qaD/4837/

        if( bottom_of_window > bottom_of_object ){
            $(this).addClass('showme');
       }
        if( bottom_of_window < bottom_of_object ){
            $(this).removeClass('showme');

How to use the toString method in Java?

Apart from what cletus answered with regards to debugging, it is used whenever you output an object, like when you use

 System.out.println(myObject);

or

System.out.println("text " + myObject);

How can I get around MySQL Errcode 13 with SELECT INTO OUTFILE?

Ubuntu uses AppArmor and that is whats preventing you from accessing /data/. Fedora uses selinux and that would prevent this on a RHEL/Fedora/CentOS machine.

To modify AppArmor to allow MySQL to access /data/ do the follow:

sudo gedit /etc/apparmor.d/usr.sbin.mysqld

add this line anywhere in the list of directories:

/data/ rw,

then do a :

sudo /etc/init.d/apparmor restart

Another option is to disable AppArmor for mysql altogether, this is NOT RECOMMENDED:

sudo mv /etc/apparmor.d/usr.sbin.mysqld /etc/apparmor.d/disable/

Don't forget to restart apparmor:

sudo /etc/init.d/apparmor restart

Difference between HashMap, LinkedHashMap and TreeMap

The most important among all the three is how they save the order of the entries.

HashMap - Does not save the order of the entries. eg.

public static void main(String[] args){
        HashMap<String,Integer> hashMap = new HashMap<>();
        hashMap.put("First",1);// First ---> 1 is put first in the map
        hashMap.put("Second",2);//Second ---> 2 is put second in the map
        hashMap.put("Third",3); // Third--->3 is put third in the map
        for(Map.Entry<String,Integer> entry : hashMap.entrySet())
        {
            System.out.println(entry.getKey()+"--->"+entry.getValue());
        }
    }

Output for HashMap

LinkedHashMap : It save the order in which entries were made. eg:

public static void main(String[] args){
        LinkedHashMap<String,Integer> linkedHashMap = new LinkedHashMap<>();
        linkedHashMap.put("First",1);// First ---> 1 is put first in the map
        linkedHashMap.put("Second",2);//Second ---> 2 is put second in the map
        linkedHashMap.put("Third",3); // Third--->3 is put third in the map
        for(Map.Entry<String,Integer> entry : linkedHashMap.entrySet())
        {
            System.out.println(entry.getKey()+"--->"+entry.getValue());
        }
    }

Output of LinkedHashMap

TreeMap : It saves the entries in ascending order of the keys. eg:

public static void main(String[] args) throws IOException {
        TreeMap<String,Integer> treeMap = new TreeMap<>();
        treeMap.put("A",1);// A---> 1 is put first in the map
        treeMap.put("C",2);//C---> 2 is put second in the map
        treeMap.put("B",3); //B--->3 is put third in the map
        for(Map.Entry<String,Integer> entry : treeMap.entrySet())
        {
            System.out.println(entry.getKey()+"--->"+entry.getValue());
        }
    }

Output of TreeMap

How to initialize var?

A var cannot be set to null since it needs to be statically typed.

var foo = null;
// compiler goes: "Huh, what's that type of foo?"

However, you can use this construct to work around the issue:

var foo = (string)null;
// compiler goes: "Ah, it's a string. Nice."

I don't know for sure, but from what I heard you can also use dynamic instead of var. This does not require static typing.

dynamic foo = null;
foo = "hi";

Also, since it was not clear to me from the question if you meant the varkeyword or variables in general: Only references (to classes) and nullable types can be set to null. For instance, you can do this:

string s = null; // reference
SomeClass c = null; // reference
int? i = null; // nullable

But you cannot do this:

int i = null; // integers cannot contain null

Making text background transparent but not text itself

If you use RGBA for modern browsers you don't need let older IEs use only the non-transparent version of the given color with RGB.

If you don't stick to CSS-only solutions, give CSS3PIE a try. With this syntax you can see exactly the same result in older IEs that you see in modern browsers:

div {
    -pie-background: rgba(223,231,233,0.8);
    behavior: url(../PIE.htc);
}

What method in the String class returns only the first N characters?

string.Substring(0,n); // 0 - start index and n - number of characters

selectOneMenu ajax events

The PrimeFaces ajax events sometimes are very poorly documented, so in most cases you must go to the source code and check yourself.

p:selectOneMenu supports change event:

<p:selectOneMenu ..>
    <p:ajax event="change" update="msgtext"
        listener="#{post.subjectSelectionChanged}" />
    <!--...-->
</p:selectOneMenu>

which triggers listener with AjaxBehaviorEvent as argument in signature:

public void subjectSelectionChanged(final AjaxBehaviorEvent event)  {...}

How to add double quotes to a string that is inside a variable?

You need to escape them by doubling them (verbatim string literal):

string str = @"""How to add doublequotes""";

Or with a normal string literal you escape them with a \:

string str = "\"How to add doublequotes\"";

What is the cause for "angular is not defined"

You have to put your script tag after the one that references Angular. Move it out of the head:

<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="main.js"></script>

The way you've set it up now, your script runs before Angular is loaded on the page.

Why is the default value of the string type null instead of an empty string?

Nullable types did not come in until 2.0.

If nullable types had been made in the beginning of the language then string would have been non-nullable and string? would have been nullable. But they could not do this du to backward compatibility.

A lot of people talk about ref-type or not ref type, but string is an out of the ordinary class and solutions would have been found to make it possible.

How to make war file in Eclipse

File -> Export -> Web -> WAR file

OR in Kepler follow as shown below :

enter image description here

How do I remove lines between ListViews on Android?

There are different ways to achieve this, but I'm not sure which one is the best (I don't even know is there is a best way). I know at least two different ways to do this in a ListView:

1. Set divider to null:

1.1. Programmatically

yourListView.setDivider(null);

1.2. XML

This goes inside your ListView element.

android:divider="@null"

2. Set divider to transparent and set its height to 0 to avoid adding space between listview elements:

2.1. Programmatically:

yourListView.setDivider(new ColorDrawable(android.R.color.transparent));
yourListView.setDividerHeight(0);

2.2. XML

android:divider="@android:color/transparent"
android:dividerHeight="0dp"

npm behind a proxy fails with status 403

I had the same issue and finally it was resolved by disconnecting from all VPN .

Pull is not possible because you have unmerged files, git stash doesn't work. Don't want to commit

You can use git checkout <file> to check out the committed version of the file (thus discarding your changes), or git reset --hard HEAD to throw away any uncommitted changes for all files.

How to define hash tables in Bash?

A coworker just mentioned this thread. I've independently implemented hash tables within bash, and it's not dependent on version 4. From a blog post of mine in March 2010 (before some of the answers here...) entitled Hash tables in bash:

I previously used cksum to hash but have since translated Java's string hashCode to native bash/zsh.

# Here's the hashing function
ht() {
  local h=0 i
  for (( i=0; i < ${#1}; i++ )); do
    let "h=( (h<<5) - h ) + $(printf %d \'${1:$i:1})"
    let "h |= h"
  done
  printf "$h"
}

# Example:

myhash[`ht foo bar`]="a value"
myhash[`ht baz baf`]="b value"

echo ${myhash[`ht baz baf`]} # "b value"
echo ${myhash[@]} # "a value b value" though perhaps reversed
echo ${#myhash[@]} # "2" - there are two values (note, zsh doesn't count right)

It's not bidirectional, and the built-in way is a lot better, but neither should really be used anyway. Bash is for quick one-offs, and such things should quite rarely involve complexity that might require hashes, except perhaps in your ~/.bashrc and friends.

Excel VBA If cell.Value =... then

You can determine if as certain word is found in a cell by using

If InStr(cell.Value, "Word1") > 0 Then

If Word1 is found in the string the InStr() function will return the location of the first character of Word1 in the string.

User Control - Custom Properties

You do this via attributes on the properties, like this:

[Description("Test text displayed in the textbox"),Category("Data")] 
public string Text {
  get => myInnerTextBox.Text;
  set => myInnerTextBox.Text = value;
}

The category is the heading under which the property will appear in the Visual Studio Properties box. Here's a more complete MSDN reference, including a list of categories.

How do emulators work and how are they written?

Emulator are very hard to create since there are many hacks (as in unusual effects), timing issues, etc that you need to simulate.

For an example of this, see http://queue.acm.org/detail.cfm?id=1755886.

That will also show you why you ‘need’ a multi-GHz CPU for emulating a 1MHz one.

How To Create Table with Identity Column

This has already been answered, but I think the simplest syntax is:

CREATE TABLE History (
    ID int primary key IDENTITY(1,1) NOT NULL,
    . . .

The more complicated constraint index is useful when you actually want to change the options.

By the way, I prefer to name such a column HistoryId, so it matches the names of the columns in foreign key relationships.

The view didn't return an HttpResponse object. It returned None instead

I had the same error using an UpdateView

I had this:

if form.is_valid() and form2.is_valid():
    form.save()
    form2.save()
    return HttpResponseRedirect(self.get_success_url())

and I solved just doing:

if form.is_valid() and form2.is_valid():
    form.save()
    form2.save()
    return HttpResponseRedirect(reverse_lazy('adopcion:solicitud_listar'))

Docker error: invalid reference format: repository name must be lowercase

I had the same error, and for some reason it appears to have been cause by uppercase letters in the Jenkins job that ran the docker run command.

JDBC connection failed, error: TCP/IP connection to host failed

If you are using a named instance, the port you using likely is 1434, instead of 1433, so please check that out using telnet or netstat aforementioned too.

MySQL: #126 - Incorrect key file for table

I got this error when I set ft_min_word_len = 2 in my.cnf, which lowers the minimum word length in a full text index to 2, from the default of 4.

Repairing the table fixed the problem.

Android - How to decode and decompile any APK file?

To decompile APK Use APKTool.
You can learn how APKTool works on http://www.decompileandroid.com/ or by reading the documentation.

Does --disable-web-security Work In Chrome Anymore?

Just create this batch file and run it on windows. It basically would kill all chrome instances and then would start chrome with disabling security. Save the following script in batch file say ***.bat and double click on it.

TASKKILL /F /IM chrome.exe
start chrome.exe --args --disable-web-security –-allow-file-access-from-files

Using Enum values as String literals

You can try this:

public enum Modes {
    some-really-long-string,
    mode1,
    mode2,
    mode3;

    public String toString(){
        switch(this) {
            case some-really-long-string:
                return "some-really-long-string";
            case mode2:
                return "mode2";
            default: return "undefined";
        }
    }

}

Python function global variables?

Here is one case that caught me out, using a global as a default value of a parameter.

globVar = None    # initialize value of global variable

def func(param = globVar):   # use globVar as default value for param
    print 'param =', param, 'globVar =', globVar  # display values

def test():
    global globVar
    globVar = 42  # change value of global
    func()

test()
=========
output: param = None, globVar = 42

I had expected param to have a value of 42. Surprise. Python 2.7 evaluated the value of globVar when it first parsed the function func. Changing the value of globVar did not affect the default value assigned to param. Delaying the evaluation, as in the following, worked as I needed it to.

def func(param = eval('globVar')):       # this seems to work
    print 'param =', param, 'globVar =', globVar  # display values

Or, if you want to be safe,

def func(param = None)):
    if param == None:
        param = globVar
    print 'param =', param, 'globVar =', globVar  # display values

How to return XML in ASP.NET?

Seems like at least 10 questions rolled into one here, a couple points.

Response.Clear - it really depends on what else is going on in the app - if you have httpmodules early in the pipeline that might be writing stuff you don't want - then clear it. Test it and find out. Fiddler or Wireshark useful for this.

Content Type to text/xml - yup - good idea - read up on HTTP spec as to why this is important. IMO anyone doing web work should have read the 1.0 and 1.1 spec at least once.

Encoding - how is your xml encoded - if it is utf-8, then say so, if not, say something else appropriate, just make sure they all match.

Page - personally, would use ashx or httpmodule, if you are using page, and want it a bit faster, get rid of autoeventwireup and bind the event handlers manually.

Would probably be a bit of a waste of memory to dump the xml into a string first, but it depends a lot on the size of the xml as to whether you would ever notice.

As others have suggested, saving the xml to the output stream probably the fastest, I would normally do that, but if you aren't sure, test it, don't rely on what you read on the interweb. Don't just believe anything I say.

For another approach, if the xml doesn't change that much, you could just write it to the disk and serve the file directly, which would likely be quite performant, but like everything in programming, it depends...

What's the difference between import java.util.*; and import java.util.Date; ?

but what I got is something like this: Date@124bbbf  
while I change the import to: import java.util.Date;  
the code works perfectly, why? 

What do you mean by "works perfectly"? The output of printing a Date object is the same no matter whether you imported java.util.* or java.util.Date. The output that you get when printing objects is the representation of the object by the toString() method of the corresponding class.

How to find rows that have a value that contains a lowercase letter

I'm not an expert on MySQL I would suggest you look at REGEXP.

SELECT * FROM MyTable WHERE ColumnX REGEXP '^[a-z]';

How to append multiple items in one line in Python

Use this :

#Inputs
L1 = [1, 2]
L2 = [3,4,5]

#Code
L1+L2

#Output
[1, 2, 3, 4, 5]

By using the (+) operator you can skip the multiple append & extend operators in just one line of code and this is valid for more then two of lists by L1+L2+L3+L4.......etc.

Happy Learning...:)

jQuery multiple conditions within if statement

Try

if (!(i == 'InvKey' || i == 'PostDate')) {

or

if (i != 'InvKey' || i != 'PostDate') {

that says if i does not equals InvKey OR PostDate

iPhone UIView Animation Best Practice

let's do try and checkout For Swift 3...

UIView.transition(with: mysuperview, duration: 0.75, options:UIViewAnimationOptions.transitionFlipFromRight , animations: {
    myview.removeFromSuperview()
}, completion: nil)

Difference between <? super T> and <? extends T> in Java

Using extends you can only get from the collection. You cannot put into it. Also, though super allows to both get and put, the return type during get is ? super T.

How to distinguish mouse "click" and "drag"

For a public action on an OSM map (position a marker on click) the question was: 1) how to determine the duration of mouse down->up (you can't imagine creating a new marker for each click) and 2) did the mouse move during down->up (i.e user is dragging the map).

const map = document.getElementById('map');

map.addEventListener("mousedown", position); 
map.addEventListener("mouseup", calculate);

let posX, posY, endX, endY, t1, t2, action;

function position(e) {

  posX = e.clientX;
  posY = e.clientY;
  t1 = Date.now();

}

function calculate(e) {

  endX = e.clientX;
  endY = e.clientY;
  t2 = (Date.now()-t1)/1000;
  action = 'inactive';

  if( t2 > 0.5 && t2 < 1.5) { // Fixing duration of mouse down->up

      if( Math.abs( posX-endX ) < 5 && Math.abs( posY-endY ) < 5 ) { // 5px error on mouse pos while clicking
         action = 'active';
         // --------> Do something
      }
  }
  console.log('Down = '+posX + ', ' + posY+'\nUp = '+endX + ', ' + endY+ '\nAction = '+ action);    

}

Gradle task - pass arguments to Java application

Since Gradle 4.9, the command line arguments can be passed with --args. For example, if you want to launch the application with command line arguments foo --bar, you can use

gradle run --args='foo --bar'

See Also Gradle Application Plugin

How to upgrade Gradle wrapper

How to increase Java heap space for a tomcat app

For Windows Service, you need to run tomcat9w.exe (or 6w/7w/8w) depending on your version of tomcat. First, make sure tomcat is stopped. Then double click on tomcat9w.exe. Navigate to the Java tab. If you know you have 64 bit Windows with 64 bit Java and 64 bit Tomcat, then feel free to set the memory higher than 512. You'll need to do some task manager monitoring to determine how high to set it. For most apps developed in 2019... I'd recommend an initial memory pool of 1024, and the maximum memory pool of 2048. Of course if your computer has tons of RAM... feel free to go as high as you want. Also, see this answer: How to increase Maximum Memory Pool Size? Apache Tomcat 9

MySQL - How to increase varchar size of an existing column in a database without breaking existing data?

For me this has worked-

ALTER TABLE table_name ALTER COLUMN column_name VARCHAR(50)

Output grep results to text file, need cleaner output

Redirection of program output is performed by the shell.

grep ... > output.txt

grep has no mechanism for adding blank lines between each match, but does provide options such as context around the matched line and colorization of the match itself. See the grep(1) man page for details, specifically the -C and --color options.

How to obtain a Thread id in Python?

You can get the ident of the current running thread. The ident could be reused for other threads, if the current thread ends.

When you crate an instance of Thread, a name is given implicit to the thread, which is the pattern: Thread-number

The name has no meaning and the name don't have to be unique. The ident of all running threads is unique.

import threading


def worker():
    print(threading.current_thread().name)
    print(threading.get_ident())


threading.Thread(target=worker).start()
threading.Thread(target=worker, name='foo').start()

The function threading.current_thread() returns the current running thread. This object holds the whole information of the thread.

Moment JS - check if a date is today or in the future

invert isBefore method of moment to check if a date is same as today or in future like this:

!moment(yourDate).isBefore(moment(), "day");

How to get the top 10 values in postgresql?

Seems you are looking for ORDER BY in DESCending order with LIMIT clause:

SELECT
 *
FROM
  scores
ORDER BY score DESC
LIMIT 10

Of course SELECT * could seriously affect performance, so use it with caution.

How to change users in TortoiseSVN

When you use Integrated Windows Authentication (i.e., Active Directory Single Sign-On), you authenticate to AD resources automatically with your AD credentials. You've are already signed in to AD and these credentials are reused automatically. Therefore if your server is IWA-enabled (e.g., VisualSVN Server), the server does not ask you to enter username and password, passing --username and --password does not work, and the SVN client does not cache your credentials on disk, too.

When you want to change the user account that's used to contact the server, you need use the Windows Credential Manager on client side. This is also helpful when your computer is not domain joined and you need to store your AD credentials to access your domain resources.

Follow these steps to save the user's domain credentials to Windows Credential Manager on the user's computer:

  1. Start Control Panel | Credential Manager on the client computer.
  2. Click Add a Windows Credential.
  3. As Internet or network address enter the FQDN of the server machine (e.g., svn.example.com).
  4. As Username enter your domain account's username in the DOMAIN\Username format.
  5. Complete the password field and click OK.

Now when you will contact https://svn.example.com/svn/MyRepo or a similar URL, the client or web browser will use the credentials saved in the Credential Manager to authenticate to the server.

enter image description here

Finding element's position relative to the document

If you don't mind using jQuery, then you can use offset() function. Refer to documentation if you want to read up more about this function.

What is the difference between the HashMap and Map objects in Java?

Adding to the top voted answer and many ones above stressing the "more generic, better", I would like to dig a little bit more.

Map is the structure contract while HashMap is an implementation providing its own methods to deal with different real problems: how to calculate index, what is the capacity and how to increment it, how to insert, how to keep the index unique, etc.

Let's look into the source code:

In Map we have the method of containsKey(Object key):

boolean containsKey(Object key);

JavaDoc:

boolean java.util.Map.containsValue(Object value)

Returns true if this map maps one or more keys to the specified value. More formally, returns true if and only if this map contains at least one mapping to a value v such that (value==null ? v==null : value.equals(v)). This operation will probably require time linear in the map size for most implementations of the Map interface.

Parameters:value

value whose presence in this map is to betested

Returns:true

if this map maps one or more keys to the specified

valueThrows:

ClassCastException - if the value is of an inappropriate type for this map (optional)

NullPointerException - if the specified value is null and this map does not permit null values (optional)

It requires its implementations to implement it, but the "how to" is at its freedom, only to ensure it returns correct.

In HashMap:

public boolean containsKey(Object key) {
    return getNode(hash(key), key) != null;
}

It turns out that HashMap uses hashcode to test if this map contains the key. So it has the benefit of hash algorithm.

What is the main difference between PATCH and PUT request?

put:
If I want to update my first name, then I send a put request:

{ "first": "Nazmul", "last": "hasan" } 

But here is a problem with using put request: When I want to send put request I have to send all two parameters that is first and last (whereas I only need to update first) so it is mandatory to send them all again with put request.

patch:
patch request, on the other hand, says: only specify the data which you need to update and it won't be affecting or changing other data.
So no need to send all values again. Do I only need to change first name? Well, It only suffices to specify first in patch request.

How to use HTTP.GET in AngularJS correctly? In specific, for an external API call?

I suggest you use Promise

myApp.service('dataService', function($http,$q) {

  delete $http.defaults.headers.common['X-Requested-With'];
  this.getData = function() {
     deferred = $q.defer();
     $http({
         method: 'GET',
         url: 'https://www.example.com/api/v1/page',
         params: 'limit=10, sort_by=created:desc',
         headers: {'Authorization': 'Token token=xxxxYYYYZzzz'}
     }).success(function(data){
         // With the data succesfully returned, we can resolve promise and we can access it in controller
         deferred.resolve();
     }).error(function(){
          alert("error");
          //let the function caller know the error
          deferred.reject(error);
     });
     return deferred.promise;
  }
});

so In your controller you can use the method

myApp.controller('AngularJSCtrl', function($scope, dataService) {
    $scope.data = null;
    dataService.getData().then(function(response) {
        $scope.data = response;
    });
});

promises are powerful feature of angularjs and it is convenient special if you want to avoid nesting callbacks.

How do I remove my IntelliJ license in 2019.3?

For PHPStorm 2020.3.2 on ubuntu inorder to reset expiration license, you should run following commands:

sudo rm ~/.config/JetBrains/PhpStorm2020.3/options/other.xml 
sudo rm ~/.config/JetBrains/PhpStorm2020.3/eval/*          
sudo rm -rf .java/.userPrefs

How to use OpenFileDialog to select a folder?

Basically you need the FolderBrowserDialog class:

Prompts the user to select a folder. This class cannot be inherited.

Example:

using(var fbd = new FolderBrowserDialog())
{
    DialogResult result = fbd.ShowDialog();

    if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath))
    {
        string[] files = Directory.GetFiles(fbd.SelectedPath);

        System.Windows.Forms.MessageBox.Show("Files found: " + files.Length.ToString(), "Message");
    }
}

If you work in WPF you have to add the reference to System.Windows.Forms.

you also have to add using System.IO for Directory class

nodemon not working: -bash: nodemon: command not found

Make sure you own root directory for npm so you don't get any errors when you install global packages without using sudo.

procedures:- in root directory

sudo chown -R yourUsername /usr/local/lib/node_modules
sudo chown -R yourUsername /usr/local/bin/
sudo chown -R yourUsername /usr/local/share/

So now with

npm i npm -g 

you get no errors and no use of sudo here. but if you still get errors confirm node_modules is owned again

/usr/local/lib/

and make sure you own everything

ls -la

enter image description here now

npm i -g nodemon

will work!

How to open a PDF file in an <iframe>?

Using an iframe to "render" a PDF will not work on all browsers; it depends on how the browser handles PDF files. Some browsers (such as Firefox and Chrome) have a built-in PDF rendered which allows them to display the PDF inline where as some older browsers (perhaps older versions of IE attempt to download the file instead).

Instead, I recommend checking out PDFObject which is a Javascript library to embed PDFs in HTML files. It handles browser compatibility pretty well and will most likely work on IE8.

In your HTML, you could set up a div to display the PDFs:

<div id="pdfRenderer"></div>

Then, you can have Javascript code to embed a PDF in that div:

var pdf = new PDFObject({
  url: "https://something.com/HTC_One_XL_User_Guide.pdf",
  id: "pdfRendered",
  pdfOpenParams: {
    view: "FitH"
  }
}).embed("pdfRenderer");

Removing all unused references from a project in Visual Studio projects

In VB2008, it works this way:

Project>Add References

Then click on the Recent tab where you can see list of references used recently. Locate the one you do not want and delet it. Then you close without adding anything.

CURRENT_DATE/CURDATE() not working as default DATE value

It doesn't work because it's not supported

The DEFAULT clause specifies a default value for a column. With one exception, the default value must be a constant; it cannot be a function or an expression. This means, for example, that you cannot set the default for a date column to be the value of a function such as NOW() or CURRENT_DATE. The exception is that you can specify CURRENT_TIMESTAMP as the default for a TIMESTAMP column

http://dev.mysql.com/doc/refman/5.5/en/create-table.html

Casting int to bool in C/C++

0 values of basic types (1)(2)map to false.

Other values map to true.

This convention was established in original C, via its flow control statements; C didn't have a boolean type at the time.


It's a common error to assume that as function return values, false indicates failure. But in particular from main it's false that indicates success. I've seen this done wrong many times, including in the Windows starter code for the D language (when you have folks like Walter Bright and Andrei Alexandrescu getting it wrong, then it's just dang easy to get wrong), hence this heads-up beware beware.


There's no need to cast to bool for built-in types because that conversion is implicit. However, Visual C++ (Microsoft's C++ compiler) has a tendency to issue a performance warning (!) for this, a pure silly-warning. A cast doesn't suffice to shut it up, but a conversion via double negation, i.e. return !!x, works nicely. One can read !! as a “convert to bool” operator, much as --> can be read as “goes to”. For those who are deeply into readability of operator notation. ;-)


1) C++14 §4.12/1 “A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true. For direct-initialization (8.5), a prvalue of type std::nullptr_t can be converted to a prvalue of type bool; the resulting value is false.”
2) C99 and C11 §6.3.1.2/1 “When any scalar value is converted to _Bool, the result is 0 if the value compares equal to 0; otherwise, the result is 1.”

Saving a high resolution image in R

A simpler way is

ggplot(data=df, aes(x=xvar, y=yvar)) + 
geom_point()

ggsave(path = path, width = width, height = height, device='tiff', dpi=700)

What are the differences between virtual memory and physical memory?

See here: Physical Vs Virtual Memory

Virtual memory is stored on the hard drive and is used when the RAM is filled. Physical memory is limited to the size of the RAM chips installed in the computer. Virtual memory is limited by the size of the hard drive, so virtual memory has the capability for more storage.

Java: Get last element after split

Gathered all possible ways together!!


By using lastIndexOf() & substring() methods of Java.lang.String

// int firstIndex = str.indexOf( separator );
int lastIndexOf = str.lastIndexOf( separator );
String begningPortion = str.substring( 0, lastIndexOf );
String endPortion = str.substring( lastIndexOf + 1 );
System.out.println("First Portion : " + begningPortion );
System.out.println("Last  Portion : " + endPortion );

split()Java SE 1.4. Splits the provided text into an array.

String[] split = str.split( Pattern.quote( separator ) );
String lastOne = split[split.length-1];
System.out.println("Split Array : "+ lastOne);

Java 8 sequential ordered stream from an array.

String firstItem = Stream.of( split )
                         .reduce( (first,last) -> first ).get();
String lastItem = Stream.of( split )
                        .reduce( (first,last) -> last ).get();
System.out.println("First Item : "+ firstItem);
System.out.println("Last  Item : "+ lastItem);

Apache Commons Langjar « org.apache.commons.lang3.StringUtils

String afterLast = StringUtils.substringAfterLast(str, separator);
System.out.println("StringUtils AfterLast : "+ afterLast);

String beforeLast = StringUtils.substringBeforeLast(str, separator);
System.out.println("StringUtils BeforeLast : "+ beforeLast);

String open = "[", close = "]";
String[] groups = StringUtils.substringsBetween("Yash[777]Sam[7]", open, close);
System.out.println("String that is nested in between two Strings "+ groups[0]);

Guava: Google Core Libraries for Java. « com.google.common.base.Splitter

Splitter splitter = Splitter.on( separator ).trimResults();
Iterable<String> iterable = splitter.split( str );
String first_Iterable = Iterables.getFirst(iterable, "");
String last_Iterable = Iterables.getLast( iterable );
System.out.println(" Guava FirstElement : "+ first_Iterable);
System.out.println(" Guava LastElement  : "+ last_Iterable);

Scripting for the Java Platform « Run Javascript on the JVM with Rhino/Nashorn

  • Rhino « Rhino is an open-source implementation of JavaScript written entirely in Java. It is typically embedded into Java applications to provide scripting to end users. It is embedded in J2SE 6 as the default Java scripting engine.

  • Nashorn is a JavaScript engine developed in the Java programming language by Oracle. It is based on the Da Vinci Machine and has been released with Java 8.

Java Scripting Programmer's Guide

public class SplitOperations {
    public static void main(String[] args) {
        String str = "my.file.png.jpeg", separator = ".";
        javascript_Split(str, separator);
    }
    public static void javascript_Split( String str, String separator ) {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("JavaScript");

        // Script Variables « expose java objects as variable to script.
        engine.put("strJS", str);

        // JavaScript code from file
        File file = new File("E:/StringSplit.js");
        // expose File object as variable to script
        engine.put("file", file);

        try {
            engine.eval("print('Script Variables « expose java objects as variable to script.', strJS)");

            // javax.script.Invocable is an optional interface.
            Invocable inv = (Invocable) engine;

            // JavaScript code in a String
            String functions = "function functionName( functionParam ) { print('Hello, ' + functionParam); }";
            engine.eval(functions);
            // invoke the global function named "functionName"
            inv.invokeFunction("functionName", "function Param value!!" );

            // evaluate a script string. The script accesses "file" variable and calls method on it
            engine.eval("print(file.getAbsolutePath())");
            // evaluate JavaScript code from given file - specified by first argument
            engine.eval( new java.io.FileReader( file ) );

            String[] typedArray = (String[]) inv.invokeFunction("splitasJavaArray", str );
            System.out.println("File : Function returns an array : "+ typedArray[1] );

            ScriptObjectMirror scriptObject = (ScriptObjectMirror) inv.invokeFunction("splitasJavaScriptArray", str, separator );
            System.out.println("File : Function return script obj : "+ convert( scriptObject ) );

            Object eval = engine.eval("(function() {return ['a', 'b'];})()");
            Object result = convert(eval);
            System.out.println("Result: {}"+ result);

            // JavaScript code in a String. This code defines a script object 'obj' with one method called 'hello'.
            String objectFunction = "var obj = new Object(); obj.hello = function(name) { print('Hello, ' + name); }";
            engine.eval(objectFunction);
            // get script object on which we want to call the method
            Object object = engine.get("obj");
            inv.invokeMethod(object, "hello", "Yash !!" );

            Object fileObjectFunction = engine.get("objfile");
            inv.invokeMethod(fileObjectFunction, "hello", "Yashwanth !!" );
        } catch (ScriptException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static Object convert(final Object obj) {
        System.out.println("\tJAVASCRIPT OBJECT: {}"+ obj.getClass());
        if (obj instanceof Bindings) {
            try {
                final Class<?> cls = Class.forName("jdk.nashorn.api.scripting.ScriptObjectMirror");
                System.out.println("\tNashorn detected");
                if (cls.isAssignableFrom(obj.getClass())) {
                    final Method isArray = cls.getMethod("isArray");
                    final Object result = isArray.invoke(obj);
                    if (result != null && result.equals(true)) {
                        final Method values = cls.getMethod("values");
                        final Object vals = values.invoke(obj);
                        System.err.println( vals );
                        if (vals instanceof Collection<?>) {
                            final Collection<?> coll = (Collection<?>) vals;
                            Object[] array = coll.toArray(new Object[0]);
                            return array;
                        }
                    }
                }
            } catch (ClassNotFoundException | NoSuchMethodException | SecurityException
                    | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
            }
        }
        if (obj instanceof List<?>) {
            final List<?> list = (List<?>) obj;
            Object[] array = list.toArray(new Object[0]);
            return array;
        }
        return obj;
    }
}

JavaScript file « StringSplit.js

// var str = 'angular.1.5.6.js', separator = ".";
function splitasJavaArray( str ) {
  var result = str.replace(/\.([^.]+)$/, ':$1').split(':');
  print('Regex Split : ', result);
  var JavaArray = Java.to(result, "java.lang.String[]");
  return JavaArray;
  // return result;
}
function splitasJavaScriptArray( str, separator) {
    var arr = str.split( separator ); // Split the string using dot as separator
    var lastVal = arr.pop(); // remove from the end
    var firstVal = arr.shift(); // remove from the front
    var middleVal = arr.join( separator ); // Re-join the remaining substrings

    var mainArr = new Array();
    mainArr.push( firstVal ); // add to the end
    mainArr.push( middleVal );
    mainArr.push( lastVal );

    return mainArr;
}

var objfile = new Object();
objfile.hello = function(name) { print('File : Hello, ' + name); }

How to fetch all Git branches

I wrote a little script to manage cloning a new repo and making local branches for all the remote branches.

You can find the latest version here:

#!/bin/bash

# Clones as usual but creates local tracking branches for all remote branches.
# To use, copy this file into the same directory your git binaries are (git, git-flow, git-subtree, etc)

clone_output=$((git clone "$@" ) 2>&1)
retval=$?
echo $clone_output
if [[ $retval != 0 ]] ; then
    exit 1
fi
pushd $(echo $clone_output | head -1 | sed 's/Cloning into .\(.*\).\.\.\./\1/') > /dev/null 2>&1
this_branch=$(git branch | sed 's/^..//')
for i in $(git branch -r | grep -v HEAD); do
  branch=$(echo $i | perl -pe 's/^.*?\///')
  # this doesn't have to be done for each branch, but that's how I did it.
  remote=$(echo $i | sed 's/\/.*//')
  if [[ "$this_branch" != "$branch" ]]; then
      git branch -t $branch $remote/$branch
  fi
done
popd > /dev/null 2>&1

To use it, just copy it into your git bin directory (for me, that’s C:\Program Files (x86)\Git\bin\git-cloneall), then, on the command line:

git cloneall [standard-clone-options] <url>

It clones as usual, but creates local tracking branches for all remote branches.

onchange equivalent in angular2

We can use Angular event bindings to respond to any DOM event. The syntax is simple. We surround the DOM event name in parentheses and assign a quoted template statement to it. -- reference

Since change is on the list of standard DOM events, we can use it:

(change)="saverange()"

In your particular case, since you're using NgModel, you could break up the two-way binding like this instead:

[ngModel]="range" (ngModelChange)="saverange($event)"

Then

saverange(newValue) {
  this.range = newValue;
  this.Platform.ready().then(() => {
     this.rootRef.child("users").child(this.UserID).child('range').set(this.range)
  })
} 

However, with this approach saverange() is called with every keystroke, so you're probably better off using (change).

How can I create a border around an Android LinearLayout?

Create a one xml file in drawable folder

<stroke
    android:width="2dp"
    android:color="#B40404" />

<padding
    android:bottom="5dp"
    android:left="5dp"
    android:right="5dp"
    android:top="5dp" />

<corners android:radius="4dp" />

Now call this xml to your small layout background

android:background="@drawable/yourxml"

SQL Server - Convert date field to UTC

If you have to convert dates other than today to different timezones you have to deal with daylight savings. I wanted a solution that could be done without worrying about database version, without using stored functions and something that could easily be ported to Oracle.

I think Warren is on the right track with getting the correct dates for daylight time, but to make it more useful for multiple time zone and different rules for countries and even the rule that changed in the US between 2006 and 2007, here a variation on the above solution. Notice that this not only has us time zones, but also central Europe. Central Europe follow the last sunday of april and last sunday of october. You will also notice that the US in 2006 follows the old first sunday in april, last sunday in october rule.

This SQL code may look a little ugly, but just copy and paste it into SQL Server and try it. Notice there are 3 section for years, timezones and rules. If you want another year, just add it to the year union. Same for another time zone or rule.

select yr, zone, standard, daylight, rulename, strule, edrule, yrstart, yrend,
    dateadd(day, (stdowref + stweekadd), stmonthref) dstlow,
    dateadd(day, (eddowref + edweekadd), edmonthref)  dsthigh
from (
  select yrs.yr, z.zone, z.standard, z.daylight, z.rulename, r.strule, r.edrule, 
    yrs.yr + '-01-01 00:00:00' yrstart,
    yrs.yr + '-12-31 23:59:59' yrend,
    yrs.yr + r.stdtpart + ' ' + r.cngtime stmonthref,
    yrs.yr + r.eddtpart + ' ' + r.cngtime edmonthref,
    case when r.strule in ('1', '2', '3') then case when datepart(dw, yrs.yr + r.stdtpart) = '1' then 0 else 8 - datepart(dw, yrs.yr + r.stdtpart) end
    else (datepart(dw, yrs.yr + r.stdtpart) - 1) * -1 end stdowref,
    case when r.edrule in ('1', '2', '3') then case when datepart(dw, yrs.yr + r.eddtpart) = '1' then 0 else 8 - datepart(dw, yrs.yr + r.eddtpart) end
    else (datepart(dw, yrs.yr + r.eddtpart) - 1) * -1 end eddowref,
    datename(dw, yrs.yr + r.stdtpart) stdow,
    datename(dw, yrs.yr + r.eddtpart) eddow,
    case when r.strule in ('1', '2', '3') then (7 * CAST(r.strule AS Integer)) - 7 else 0 end stweekadd,
    case when r.edrule in ('1', '2', '3') then (7 * CAST(r.edrule AS Integer)) - 7 else 0 end edweekadd
from (
    select '2005' yr union select '2006' yr -- old us rules
    UNION select '2007' yr UNION select '2008' yr UNION select '2009' yr UNION select '2010' yr UNION select '2011' yr
    UNION select '2012' yr UNION select '2013' yr UNION select '2014' yr UNION select '2015' yr UNION select '2016' yr
    UNION select '2017' yr UNION select '2018' yr UNION select '2019' yr UNION select '2020' yr UNION select '2021' yr
    UNION select '2022' yr UNION select '2023' yr UNION select '2024' yr UNION select '2025' yr UNION select '2026' yr
) yrs
cross join (
    SELECT 'ET' zone, '-05:00' standard, '-04:00' daylight, 'US' rulename
    UNION SELECT 'CT' zone, '-06:00' standard, '-05:00' daylight, 'US' rulename
    UNION SELECT 'MT' zone, '-07:00' standard, '-06:00' daylight, 'US' rulename
    UNION SELECT 'PT' zone, '-08:00' standard, '-07:00' daylight, 'US' rulename
    UNION SELECT 'CET' zone, '+01:00' standard, '+02:00' daylight, 'EU' rulename
) z
join (
    SELECT 'US' rulename, '2' strule, '-03-01' stdtpart, '1' edrule, '-11-01' eddtpart, 2007 firstyr, 2099 lastyr, '02:00:00' cngtime
    UNION SELECT 'US' rulename, '1' strule, '-04-01' stdtpart, 'L' edrule, '-10-31' eddtpart, 1900 firstyr, 2006 lastyr, '02:00:00' cngtime
    UNION SELECT  'EU' rulename, 'L' strule, '-03-31' stdtpart, 'L' edrule, '-10-31' eddtpart, 1900 firstyr, 2099 lastyr, '01:00:00' cngtime
) r on r.rulename = z.rulename
    and datepart(year, yrs.yr) between firstyr and lastyr
) dstdates

For the rules, use 1, 2, 3 or L for first, second, third or last sunday. The date part gives the month and depending on the rule, the first day of the month or the last day of the month for rule type L.

I put the above query into a view. Now, anytime I want a date with the time zone offset or converted to UTC time, I just join to this view and select get the date in the date format. Instead of datetime, I converted these to datetimeoffset.

select createdon, dst.zone
    , case when createdon >= dstlow and createdon < dsthigh then dst.daylight else dst.standard end pacificoffsettime
    , TODATETIMEOFFSET(createdon, case when createdon >= dstlow and createdon < dsthigh then dst.daylight else dst.standard end) pacifictime
    , SWITCHOFFSET(TODATETIMEOFFSET(createdon, case when createdon >= dstlow and createdon < dsthigh then dst.daylight else dst.standard end), '+00:00')  utctime
from (select '2014-01-01 12:00:00' createdon union select '2014-06-01 12:00:00' createdon) photos
left join US_DAYLIGHT_DATES dst on createdon between yrstart and yrend and zone = 'PT'

How to get input text value on click in ReactJS

There are two ways to go about doing this.

  1. Create a state in the constructor that contains the text input. Attach an onChange event to the input box that updates state each time. Then onClick you could just alert the state object.

  2. handleClick: function() { alert(this.refs.myInput.value); },

Using Mockito, how do I verify a method was a called with a certain argument?

Building off of Mamboking's answer:

ContractsDao mock_contractsDao = mock(ContractsDao.class);
when(mock_contractsDao.save(anyString())).thenReturn("Some result");

m_orderSvc.m_contractsDao = mock_contractsDao;
m_prog = new ProcessOrdersWorker(m_orderSvc, m_opportunitySvc, m_myprojectOrgSvc);
m_prog.work(); 

Addressing your request to verify whether the argument contains a certain value, I could assume you mean that the argument is a String and you want to test whether the String argument contains a substring. For this you could do:

ArgumentCaptor<String> savedCaptor = ArgumentCaptor.forClass(String.class);
verify(mock_contractsDao).save(savedCaptor.capture());
assertTrue(savedCaptor.getValue().contains("substring I want to find");

If that assumption was wrong, and the argument to save() is a collection of some kind, it would be only slightly different:

ArgumentCaptor<Collection<MyType>> savedCaptor = ArgumentCaptor.forClass(Collection.class);
verify(mock_contractsDao).save(savedCaptor.capture());
assertTrue(savedCaptor.getValue().contains(someMyTypeElementToFindInCollection);

You might also check into ArgumentMatchers, if you know how to use Hamcrest matchers.

Is there an opposite to display:none?

You can use display: block

Example :

<!DOCTYPE html>
<html>
<body>

<p id="demo">Lorem Ipsum</p>

<button type="button" 
onclick="document.getElementById('demo').style.display='none'">Click Me!</button>
<button type="button" 
onclick="document.getElementById('demo').style.display='block'">Click Me!</button>

</body>
</html> 

Can you use Microsoft Entity Framework with Oracle?

Update:

Oracle now fully supports the Entity Framework. Oracle Data Provider for .NET Release 11.2.0.3 (ODAC 11.2) Release Notes: http://docs.oracle.com/cd/E20434_01/doc/win.112/e23174/whatsnew.htm#BGGJIEIC

More documentation on Linq to Entities and ADO.NET Entity Framework: http://docs.oracle.com/cd/E20434_01/doc/win.112/e23174/featLINQ.htm#CJACEDJG

Note: ODP.NET also supports Entity SQL.

Find in Files: Search all code in Team Foundation Server

If you install TFS 2008 PowerTools you will get a "Find in Source Control" action in the Team Explorer right click menu.

TFS2008 Power Tools

Reactjs convert html string to jsx

There are now safer methods to accomplish this. The docs have been updated with these methods.

Other Methods

  1. Easiest - Use Unicode, save the file as UTF-8 and set the charset to UTF-8.

    <div>{'First · Second'}</div>

  2. Safer - Use the Unicode number for the entity inside a Javascript string.

    <div>{'First \u00b7 Second'}</div>

    or

    <div>{'First ' + String.fromCharCode(183) + ' Second'}</div>

  3. Or a mixed array with strings and JSX elements.

    <div>{['First ', <span>&middot;</span>, ' Second']}</div>

  4. Last Resort - Insert raw HTML using dangerouslySetInnerHTML.

    <div dangerouslySetInnerHTML={{__html: 'First &middot; Second'}} />

Mysql command not found in OS X 10.7

I installed MAMP and phpmyadmin was working.

But cannot find /usr/local/bin/mysql

This fixed it

sudo ln -s /Applications/MAMP/Library/bin/mysql /usr/local/bin/mysql

Convert LocalDateTime to LocalDateTime in UTC

Question?

Looking at the answers and the question, it seems the question has been modified significantly. So to answer the current question:

Convert LocalDateTime to LocalDateTime in UTC.

Timezone?

LocalDateTime does not store any information about the time-zone, it just basically holds the values of year, month, day, hour, minute, second, and smaller units. So an important question is: What is the timezone of the original LocalDateTime? It might as well be UTC already, therefore no conversion has to be made.

System Default Timezone

Considering that you asked the question anyway, you probably meant that the original time is in your system-default timezone and you want to convert it to UTC. Because usually a LocalDateTime object is created by using LocalDateTime.now() which returns the current time in the system-default timezone. In this case, the conversion would be the following:

LocalDateTime convertToUtc(LocalDateTime time) {
    return time.atZone(ZoneId.systemDefault()).withZoneSameInstant(ZoneOffset.UTC).toLocalDateTime();
}

An example of the conversion process:

2019-02-25 11:39 // [time] original LocalDateTime without a timezone
2019-02-25 11:39 GMT+1 // [atZone] converted to ZonedDateTime (system timezone is Madrid)
2019-02-25 10:39 GMT // [withZoneSameInstant] converted to UTC, still as ZonedDateTime
2019-02-25 10:39 // [toLocalDateTime] losing the timezone information

Explicit Timezone

In any other case, when you explicitly specify the timezone of the time to convert, the conversion would be the following:

LocalDateTime convertToUtc(LocalDateTime time, ZoneId zone) {
    return time.atZone(zone).withZoneSameInstant(ZoneOffset.UTC).toLocalDateTime();
}

An example of the conversion process:

2019-02-25 11:39 // [time] original LocalDateTime without a timezone
2019-02-25 11:39 GMT+2 // [atZone] converted to ZonedDateTime (zone is Europe/Tallinn)
2019-02-25 09:39 GMT // [withZoneSameInstant] converted to UTC, still as ZonedDateTime
2019-02-25 09:39 // [toLocalDateTime] losing the timezone information

The atZone() Method

The result of the atZone() method depends on the time passed as its argument, because it considers all the rules of the timezone, including Daylight Saving Time (DST). In the examples, the time was 25th February, in Europe this means winter time (no DST).

If we were to use a different date, let's say 25th August from last year, the result would be different, considering DST:

2018-08-25 11:39 // [time] original LocalDateTime without a timezone
2018-08-25 11:39 GMT+3 // [atZone] converted to ZonedDateTime (zone is Europe/Tallinn)
2018-08-25 08:39 GMT // [withZoneSameInstant] converted to UTC, still as ZonedDateTime
2018-08-25 08:39 // [toLocalDateTime] losing the timezone information

The GMT time does not change. Therefore the offsets in the other timezones are adjusted. In this example, the summer time of Estonia is GMT+3, and winter time GMT+2.

Also, if you specify a time within the transition of changing clocks back one hour. E.g. October 28th, 2018 03:30 for Estonia, this can mean two different times:

2018-10-28 03:30 GMT+3 // summer time [UTC 2018-10-28 00:30]
2018-10-28 04:00 GMT+3 // clocks are turned back 1 hour [UTC 2018-10-28 01:00]
2018-10-28 03:00 GMT+2 // same as above [UTC 2018-10-28 01:00]
2018-10-28 03:30 GMT+2 // winter time [UTC 2018-10-28 01:30]

Without specifying the offset manually (GMT+2 or GMT+3), the time 03:30 for the timezone Europe/Tallinn can mean two different UTC times, and two different offsets.

Summary

As you can see, the end result depends on the timezone of the time passed as an argument. Because the timezone cannot be extracted from the LocalDateTime object, you have to know yourself which timezone it is coming from in order to convert it to UTC.

number_format() with MySQL

Antonio's answer

CONCAT(REPLACE(FORMAT(number,0),',','.'),',',SUBSTRING_INDEX(FORMAT(number,2),'.',-1))

is wrong; it may produce incorrect results!

For example, if "number" is 12345.67, the resulting string would be:

'12.346,67'

instead of

'12.345,67'

because FORMAT(number,0) rounds "number" up if fractional part is greater or equal than 0.5 (as it is in my example)!

What you COULD use is

CONCAT(REPLACE(FORMAT(FLOOR(number),0),',','.'),',',SUBSTRING_INDEX(FORMAT(number,2),'.',-1))

if your MySQL/MariaDB's FORMAT doesn't support "locale_name" (see MindStalker's post - Thx 4 that, pal). Note the FLOOR function I've added.

Pandas count(distinct) equivalent

Here is another method, much simple, lets say your dataframe name is daat and column name is YEARMONTH

daat.YEARMONTH.value_counts()

How to use java.Set

The first thing you need to study is the java.util.Set API.

Here's a small example of how to use its methods:

    Set<Integer> numbers = new TreeSet<Integer>();

    numbers.add(2);
    numbers.add(5);

    System.out.println(numbers); // "[2, 5]"
    System.out.println(numbers.contains(7)); // "false"

    System.out.println(numbers.add(5)); // "false"
    System.out.println(numbers.size()); // "2"

    int sum = 0;
    for (int n : numbers) {
        sum += n;
    }
    System.out.println("Sum = " + sum); // "Sum = 7"

    numbers.addAll(Arrays.asList(1,2,3,4,5));
    System.out.println(numbers); // "[1, 2, 3, 4, 5]"

    numbers.removeAll(Arrays.asList(4,5,6,7));
    System.out.println(numbers); // "[1, 2, 3]"

    numbers.retainAll(Arrays.asList(2,3,4,5));
    System.out.println(numbers); // "[2, 3]"

Once you're familiar with the API, you can use it to contain more interesting objects. If you haven't familiarized yourself with the equals and hashCode contract, already, now is a good time to start.

In a nutshell:

  • @Override both or none; never just one. (very important, because it must satisfied property: a.equals(b) == true --> a.hashCode() == b.hashCode()
    • Be careful with writing boolean equals(Thing other) instead; this is not a proper @Override.
  • For non-null references x, y, z, equals must be:
    • reflexive: x.equals(x).
    • symmetric: x.equals(y) if and only if y.equals(x)
    • transitive: if x.equals(y) && y.equals(z), then x.equals(z)
    • consistent: x.equals(y) must not change unless the objects have mutated
    • x.equals(null) == false
  • The general contract for hashCode is:
    • consistent: return the same number unless mutation happened
    • consistent with equals: if x.equals(y), then x.hashCode() == y.hashCode()
      • strictly speaking, object inequality does not require hash code inequality
      • but hash code inequality necessarily requires object inequality
  • What counts as mutation should be consistent between equals and hashCode.

Next, you may want to impose an ordering of your objects. You can do this by making your type implements Comparable, or by providing a separate Comparator.

Having either makes it easy to sort your objects (Arrays.sort, Collections.sort(List)). It also allows you to use SortedSet, such as TreeSet.


Further readings on stackoverflow:

var.replace is not a function

probable issues:

  • variable is NUMBER (instead of string);
    num=35; num.replace(3,'three'); =====> ERROR
    num=35; num.toString().replace(3,'three'); =====> CORRECT !!!!!!
    num='35'; num.replace(3,'three'); =====> CORRECT !!!!!!
  • variable is object (instead of string);
  • variable is not defined;

validation of input text field in html using javascript

<form name="myForm" id="myForm" method="post" onsubmit="return validateForm();">
    First Name: <input type="text" id="name" /> <br />
    <span id="nameErrMsg" class="error"></span> <br />
    <!-- ... all your other stuff ... -->
</form>
  <p>
    1.word should be atleast 5 letter<br>
    2.No space should be encountered<br>
    3.No numbers and special characters allowed<br>
    4.letters can be repeated upto 3(eg: aa is allowed aaa is not allowed)
  </p>
  <button id="validateTestButton" value="Validate now" onclick="validateForm();">Validate now</button>


validateForm = function () {
    return checkName();
}

function checkName() {
    var x = document.myForm;
    var input = x.name.value;
    var errMsgHolder = document.getElementById('nameErrMsg');
    if (input.length < 5) {
        errMsgHolder.innerHTML =
            'Please enter a name with at least 5 letters';
        return false;
    } else if (!(/^\S{3,}$/.test(input))) {
        errMsgHolder.innerHTML =
            'Name cannot contain whitespace';
        return false;
    }else if(!(/^[a-zA-Z]+$/.test(input)))
    {
        errMsgHolder.innerHTML=
                'Only alphabets allowed'
    }
    else if(!(/^(?:(\w)(?!\1\1))+$/.test(input)))
    {
        errMsgHolder.innerHTML=
                'per 3 alphabets allowed'
    }
    else {
        errMsgHolder.innerHTML = '';
        return undefined;
    }       

}

.error {
color: #E00000;
 }

how to use getSharedPreferences in android

//Set Preference
SharedPreferences myPrefs = getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor;  
prefsEditor = myPrefs.edit();  
//strVersionName->Any value to be stored  
prefsEditor.putString("STOREDVALUE", strVersionName);  
prefsEditor.commit();

//Get Preferenece  
SharedPreferences myPrefs;    
myPrefs = getSharedPreferences("myPrefs", MODE_WORLD_READABLE);  
String StoredValue=myPrefs.getString("STOREDVALUE", "");

Try this..

What does "select 1 from" do?

The statement SELECT 1 FROM SomeTable just returns a column containing the value 1 for each row in your table. If you add another column in, e.g. SELECT 1, cust_name FROM SomeTable then it makes it a little clearer:

            cust_name
----------- ---------------
1           Village Toys
1           Kids Place
1           Fun4All
1           Fun4All
1           The Toy Store

Gets last digit of a number

Just return (number % 10); i.e. take the modulus. This will be much faster than parsing in and out of a string.

If number can be negative then use (Math.abs(number) % 10);

How to insert an element after another element in JavaScript without using a library?

a robust implementation of insertAfter.

// source: https://github.com/jserz/domPlus/blob/master/src/insertAfter()/insertAfter.js
Node.prototype.insertAfter = Node.prototype.insertAfter || function (newNode, referenceNode) {
  function isNode(node) {
    return node instanceof Node;
  }

  if(arguments.length < 2){
    throw(new TypeError("Failed to execute 'insertAfter' on 'Node': 2 arguments required, but only "+ arguments.length +" present."));
  }

  if(isNode(newNode)){
    if(referenceNode === null || referenceNode === undefined){
      return this.insertBefore(newNode, referenceNode);
    }

    if(isNode(referenceNode)){
      return this.insertBefore(newNode, referenceNode.nextSibling);
    }

    throw(new TypeError("Failed to execute 'insertAfter' on 'Node': parameter 2 is not of type 'Node'."));
  }

  throw(new TypeError("Failed to execute 'insertAfter' on 'Node': parameter 1 is not of type 'Node'."));
};

jQuery $("#radioButton").change(...) not firing during de-selection

Looks like the change() function is only called when you check a radio button, not when you uncheck it. The solution I used is to bind the change event to every radio button:

$("#r1, #r2, #r3").change(function () {

Or you could give all the radio buttons the same name:

$("input[name=someRadioGroup]:radio").change(function () {

Here's a working jsfiddle example (updated from Chris Porter's comment.)

Per @Ray's comment, you should avoid using names with . in them. Those names work in jQuery 1.7.2 but not in other versions (jsfiddle example.).

How to install Visual C++ Build tools?

You can check Announcing the official release of the Visual C++ Build Tools 2015 and from this blog, we can know that the Build Tools are the same C++ tools that you get with Visual Studio 2015 but they come in a scriptable standalone installer that only lays down the tools you need to build C++ projects. The Build Tools give you a way to install the tools you need on your build machines without the IDE you don’t need.

Because these components are the same as the ones installed by the Visual Studio 2015 Update 2 setup, you cannot install the Visual C++ Build Tools on a machine that already has Visual Studio 2015 installed. Therefore, it asks you to uninstall your existing VS 2015 when you tried to install the Visual C++ build tools using the standalone installer. Since you already have the VS 2015, you can go to Control Panel—Programs and Features and right click the VS 2015 item and Change-Modify, then check the option of those components that relates to the Visual C++ Build Tools, like Visual C++, Windows SDK… then install them. After the installation is successful, you can build the C++ projects.

How to subtract a day from a date?

Subtract datetime.timedelta(days=1)

How to convert JTextField to String and String to JTextField?

The JTextField offers a getText() and a setText() method - those are for getting and setting the content of the text field.

Calling constructors in c++ without new

I assume with the second line you actually mean:

Thing *thing = new Thing("uiae");

which would be the standard way of creating new dynamic objects (necessary for dynamic binding and polymorphism) and storing their address to a pointer. Your code does what JaredPar described, namely creating two objects (one passed a const char*, the other passed a const Thing&), and then calling the destructor (~Thing()) on the first object (the const char* one).

By contrast, this:

Thing thing("uiae");

creates a static object which is destroyed automatically upon exiting the current scope.

How to run Spyder in virtual environment?

Here is a quick way to do it in 2021 using the Anaconda Navigator. This is the most reliable way to do it, unless you want to create environments programmatically which I don't think is the case for most users:

  1. Open Anaconda Navigator.
  2. Click on Environments > Create and give a name to your environment. Be sure to change Python/R Kernel version if needed.

enter image description here

  1. Go "Home" and click on "Install" under the Spyder box.

enter image description here

  1. Click "Launch/Run"

There are still a few minor bugs when setting up your environment, most of them should be solved by restarting the Navigator.

If you find a bug, please help us posting it in the Anaconda Issues bug-tracker too! If you run into trouble creating the environment or if the environment was not correctly created you can double check what got installed: Clicking the "Environments" opens a management window showing installed packages. Search and select Spyder-related packages and then click on "Apply" to install them.

enter image description here

Dynamic require in RequireJS, getting "Module name has not been loaded yet for context" error?

The limitation relates to the simplified CommonJS syntax vs. the normal callback syntax:

Loading a module is inherently an asynchronous process due to the unknown timing of downloading it. However, RequireJS in emulation of the server-side CommonJS spec tries to give you a simplified syntax. When you do something like this:

var foomodule = require('foo');
// do something with fooModule

What's happening behind the scenes is that RequireJS is looking at the body of your function code and parsing out that you need 'foo' and loading it prior to your function execution. However, when a variable or anything other than a simple string, such as your example...

var module = require(path); // Call RequireJS require

...then Require is unable to parse this out and automatically convert it. The solution is to convert to the callback syntax;

var moduleName = 'foo';
require([moduleName], function(fooModule){
    // do something with fooModule
})

Given the above, here is one possible rewrite of your 2nd example to use the standard syntax:

define(['dyn_modules'], function (dynModules) {
    require(dynModules, function(){
        // use arguments since you don't know how many modules you're getting in the callback
        for (var i = 0; i < arguments.length; i++){
            var mymodule = arguments[i];
            // do something with mymodule...
        }
    });

});

EDIT: From your own answer, I see you're using underscore/lodash, so using _.values and _.object can simplify the looping through arguments array as above.

How do you recursively unzip archives in a directory and its subdirectories from the Unix command-line?

I realise this is very old, but it was among the first hits on Google when I was looking for a solution to something similar, so I'll post what I did here. My scenario is slightly different as I basically just wanted to fully explode a jar, along with all jars contained within it, so I wrote the following bash functions:

function explode {
    local target="$1"
    echo "Exploding $target."
    if [ -f "$target" ] ; then
        explodeFile "$target"
    elif [ -d "$target" ] ; then
        while [ "$(find "$target" -type f -regextype posix-egrep -iregex ".*\.(zip|jar|ear|war|sar)")" != "" ] ; do
            find "$target" -type f -regextype posix-egrep -iregex ".*\.(zip|jar|ear|war|sar)" -exec bash -c 'source "<file-where-this-function-is-stored>" ; explode "{}"' \;
        done
    else
        echo "Could not find $target."
    fi
}

function explodeFile {
    local target="$1"
    echo "Exploding file $target."
    mv "$target" "$target.tmp"
    unzip -q "$target.tmp" -d "$target"
    rm "$target.tmp"
}

Note the <file-where-this-function-is-stored> which is needed if you're storing this in a file that is not read for a non-interactive shell as I happened to be. If you're storing the functions in a file loaded on non-interactive shells (e.g., .bashrc I believe) you can drop the whole source statement. Hopefully this will help someone.

A little warning - explodeFile also deletes the ziped file, you can of course change that by commenting out the last line.

Webclient / HttpWebRequest with Basic Authentication returns 404 not found for valid URL

Try changing the Web Client request authentication part to:

NetworkCredential myCreds = new NetworkCredential(userName, passWord);
client.Credentials = myCreds;

Then make your call, seems to work fine for me.

Android open camera from button

you can use the following code

         Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);

                pic = new File(Environment.getExternalStorageDirectory(),
                        mApp.getPreference().getString(Common.u_id, "") + ".jpg");

                picUri = Uri.fromFile(pic);

                cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, picUri);

                cameraIntent.putExtra("return-data", true);
                startActivityForResult(cameraIntent, PHOTO);

Importing a Maven project into Eclipse from Git

Import without installing any additional connectors for Mylyn:

  1. Open Git Repositories view (Window->Show view->Git Repositories)
  2. Press Clone a Git Repository button and proceed with all steps
  3. In newly created repository expand Working Directory, right click on folder with your project and select Import Projects. Then either choose Import existing projects, or select Import as general project. If needed after importing right click on your project and select Configure->Convert to Maven Project (and Maven->Update Project).

Changing upload_max_filesize on PHP

I've faced the same problem , but I found out that not all the configuration settings could be set using ini_set() function , check this Where a configuration setting may be set

How to create a pulse effect using -webkit-animation - outward rings

Or if you want a ripple pulse effect, you could use this:

http://jsfiddle.net/Fy8vD/3041/

.gps_ring {
     border: 2px solid #fff;
     -webkit-border-radius: 50%;
     height: 18px;
     width: 18px;
     position: absolute;
     left:20px;
    top:214px;
    -webkit-animation: pulsate 1s ease-out;
    -webkit-animation-iteration-count: infinite; 
    opacity: 0.0;
}
.gps_ring:before {
    content:"";
    display:block;
    border: 2px solid #fff;
    -webkit-border-radius: 50%;
    height: 30px;
    width: 30px;
    position: absolute;
    left:-8px;
    top:-8px;
    -webkit-animation: pulsate 1s ease-out;
    -webkit-animation-iteration-count: infinite; 
    -webkit-animation-delay: 0.1s;
    opacity: 0.0;
}
.gps_ring:after {
    content:"";
    display:block;
    border:2px solid #fff;
    -webkit-border-radius: 50%;
    height: 50px;
    width: 50px;
    position: absolute;
    left:-18px;
    top:-18px;
    -webkit-animation: pulsate 1s ease-out;
    -webkit-animation-iteration-count: infinite; 
    -webkit-animation-delay: 0.2s;
    opacity: 0.0;
}
@-webkit-keyframes pulsate {
    0% {-webkit-transform: scale(0.1, 0.1); opacity: 0.0;}
    50% {opacity: 1.0;}
    100% {-webkit-transform: scale(1.2, 1.2); opacity: 0.0;}
}

How to elegantly check if a number is within a range?

static class ExtensionMethods
{
    internal static bool IsBetween(this double number,double bound1, double bound2)
    {
        return Math.Min(bound1, bound2) <= number && number <= Math.Max(bound2, bound1);
    }

    internal static bool IsBetween(this int number, double bound1, double bound2)
    {
        return Math.Min(bound1, bound2) <= number && number <= Math.Max(bound2, bound1);
    }
}

Usage

double numberToBeChecked = 7;

var result = numberToBeChecked.IsBetween(100,122);

var result = 5.IsBetween(100,120);

var result = 8.0.IsBetween(1.2,9.6);

Error creating bean with name

It looks like your Spring component scan Base is missing UserServiceImpl

<context:component-scan base-package="org.assessme.com.controller." />

Node.js quick file server (static files over HTTP)

For the benefit of searchers, I liked Jakub g's answer, but wanted a little error handling. Obviously it's best to handle errors properly, but this should help prevent a site stopping if an error occurs. Code below:

var http = require('http');
var express = require('express');

process.on('uncaughtException', function(err) {
  console.log(err);
});

var server = express();

server.use(express.static(__dirname));

var port = 10001;
server.listen(port, function() { 
    console.log('listening on port ' + port);     
    //var err = new Error('This error won't break the application...')
    //throw err
});

How to check if an element is visible with WebDriver

    try{
        if( driver.findElement(By.xpath("//div***")).isDisplayed()){
          System.out.println("Element is Visible");
        }
}
catch(NoSuchElementException e){
   else{
     System.out.println("Element is InVisible");
        }
}

Why do python lists have pop() but not push()

Because "append" existed long before "pop" was thought of. Python 0.9.1 supported list.append in early 1991. By comparison, here's part of a discussion on comp.lang.python about adding pop in 1997. Guido wrote:

To implement a stack, one would need to add a list.pop() primitive (and no, I'm not against this particular one on the basis of any principle). list.push() could be added for symmetry with list.pop() but I'm not a big fan of multiple names for the same operation -- sooner or later you're going to read code that uses the other one, so you need to learn both, which is more cognitive load.

You can also see he discusses the idea of if push/pop/put/pull should be at element [0] or after element [-1] where he posts a reference to Icon's list:

I stil think that all this is best left out of the list object implementation -- if you need a stack, or a queue, with particular semantics, write a little class that uses a lists

In other words, for stacks implemented directly as Python lists, which already supports fast append(), and del list[-1], it makes sense that list.pop() work by default on the last element. Even if other languages do it differently.

Implicit here is that most people need to append to a list, but many fewer have occasion to treat lists as stacks, which is why list.append came in so much earlier.

MySql : Grant read only options?

Note for MySQL 8 it's different

You need to do it in two steps:

CREATE USER 'readonly_user'@'localhost' IDENTIFIED BY 'some_strong_password';
GRANT SELECT, SHOW VIEW ON *.* TO 'readonly_user'@'localhost';
flush privileges;

How to add a list item to an existing unordered list?

You should append to the container, not the last element:

$("#content ul").append('<li><a href="/user/messages"><span class="tab">Message Center</span></a></li>');

The append() function should've probably been called add() in jQuery because it sometimes confuses people. You would think it appends something after the given element, while it actually adds it to the element.

How do I parse command line arguments in Bash?

Assume we create a shell script named test_args.sh as follow

#!/bin/sh
until [ $# -eq 0 ]
do
  name=${1:1}; shift;
  if [[ -z "$1" || $1 == -* ]] ; then eval "export $name=true"; else eval "export $name=$1"; shift; fi  
done
echo "year=$year month=$month day=$day flag=$flag"

After we run the following command:

sh test_args.sh  -year 2017 -flag  -month 12 -day 22 

The output would be:

year=2017 month=12 day=22 flag=true

Matplotlib scatter plot with different text at each data point

In case anyone is trying to apply the above solutions to a .scatter() instead of a .subplot(),

I tried running the following code

y = [2.56422, 3.77284, 3.52623, 3.51468, 3.02199]
z = [0.15, 0.3, 0.45, 0.6, 0.75]
n = [58, 651, 393, 203, 123]

fig, ax = plt.scatter(z, y)

for i, txt in enumerate(n):
    ax.annotate(txt, (z[i], y[i]))

But ran into errors stating "cannot unpack non-iterable PathCollection object", with the error specifically pointing at codeline fig, ax = plt.scatter(z, y)

I eventually solved the error using the following code

plt.scatter(z, y)

for i, txt in enumerate(n):
    plt.annotate(txt, (z[i], y[i]))

I didn't expect there to be a difference between .scatter() and .subplot() I should have known better.

Which is preferred: Nullable<T>.HasValue or Nullable<T> != null?

In VB.Net. Do NOT use "IsNot Nothing" when you can use ".HasValue". I just solved an "Operation could destabilize the runtime" Medium trust error by replacing "IsNot Nothing" with ".HasValue" In one spot. I don't really understand why, but something is happening differently in the compiler. I would assume that "!= null" in C# may have the same issue.