Programs & Examples On #Out of memory

An error or exception which is thrown when a program makes a request for memory that cannot be satisfied.

How to solve java.lang.OutOfMemoryError trouble in Android

android:largeHeap="true" didn't fix the error

In my case, I got this error after I added an icon/image to Drawable folder by converting SVG to vector. Simply, go to the icon xml file and set small numbers for the width and height

android:width="24dp"
android:height="24dp"
android:viewportWidth="3033"
android:viewportHeight="3033"

Exception of type 'System.OutOfMemoryException' was thrown.

Running in Debug Mode

When you're developing and debugging an application, you will typically run with the debug attribute in the web.config file set to true and your DLLs compiled in debug mode. However, before you deploy your application to test or to production, you should compile your components in release mode and set the debug attribute to false.

ASP.NET works differently on many levels when running in debug mode. In fact, when you are running in debug mode, the GC will allow your objects to remain alive longer (until the end of the scope) so you will always see higher memory usage when running in debug mode.

Another often unrealized side-effect of running in debug mode is that client scripts served via the webresource.axd and scriptresource.axd handlers will not be cached. That means that each client request will have to download any scripts (such as ASP.NET AJAX scripts) instead of taking advantage of client-side caching. This can lead to a substantial performance hit.

Source: http://blogs.iis.net/webtopics/archive/2009/05/22/troubleshooting-system-outofmemoryexceptions-in-asp-net.aspx

Error java.lang.OutOfMemoryError: GC overhead limit exceeded

increase javaMaxHeapsize in your build.gradle(Module:app) file

dexOptions {
    javaMaxHeapSize "1g"
}

to (Add this line in gradle)

 dexOptions {
        javaMaxHeapSize "4g"
    }

C# : Out of Memory exception

Two points:

  1. If you are running a 32 bit Windows, you won't have all the 4GB accessible, only 2GB.
  2. Don't forget that the underlying implementation of List is an array. If your memory is heavily fragmented, there may not be enough contiguous space to allocate your List, even though in total you have plenty of free memory.

What is a StackOverflowError?

Stack overflow means exactly that: a stack overflows. Usually there's a one stack in the program that contains local-scope variables and addresses where to return when execution of a routine ends. That stack tends to be a fixed memory range somewhere in the memory, therefore it's limited how much it can contain values.

If the stack is empty you can't pop, if you do you'll get stack underflow error.

If the stack is full you can't push, if you do you'll get stack overflow error.

So stack overflow appears where you allocate too much into the stack. For instance, in the mentioned recursion.

Some implementations optimize out some forms of recursions. Tail recursion in particular. Tail recursive routines are form of routines where the recursive call appears as a final thing what the routine does. Such routine call gets simply reduced into a jump.

Some implementations go so far as implement their own stacks for recursion, therefore they allow the recursion to continue until the system runs out of memory.

Easiest thing you could try would be to increase your stack size if you can. If you can't do that though, the second best thing would be to look whether there's something that clearly causes the stack overflow. Try it by printing something before and after the call into routine. This helps you to find out the failing routine.

Node.js heap out of memory

Upgrade node to the latest version. I was on node 6.6 with this error and upgraded to 8.9.4 and the problem went away.

Allowed memory size of X bytes exhausted

ini_set('memory_limit', '128M'); 

or

php.ini  =>  memory_limit = 128M

or

php_value memory_limit 128M

Generate an integer that is not among four billion given ones

  • The simplest approach is to find the minimum number in the file, and return 1 less than that. This uses O(1) storage, and O(n) time for a file of n numbers. However, it will fail if number range is limited, which could make min-1 not-a-number.

  • The simple and straightforward method of using a bitmap has already been mentioned. That method uses O(n) time and storage.

  • A 2-pass method with 2^16 counting-buckets has also been mentioned. It reads 2*n integers, so uses O(n) time and O(1) storage, but it cannot handle datasets with more than 2^16 numbers. However, it's easily extended to (eg) 2^60 64-bit integers by running 4 passes instead of 2, and easily adapted to using tiny memory by using only as many bins as fit in memory and increasing the number of passes correspondingly, in which case run time is no longer O(n) but instead is O(n*log n).

  • The method of XOR'ing all the numbers together, mentioned so far by rfrankel and at length by ircmaxell answers the question asked in stackoverflow#35185, as ltn100 pointed out. It uses O(1) storage and O(n) run time. If for the moment we assume 32-bit integers, XOR has a 7% probability of producing a distinct number. Rationale: given ~ 4G distinct numbers XOR'd together, and ca. 300M not in file, the number of set bits in each bit position has equal chance of being odd or even. Thus, 2^32 numbers have equal likelihood of arising as the XOR result, of which 93% are already in file. Note that if the numbers in file aren't all distinct, the XOR method's probability of success rises.

"java.lang.OutOfMemoryError: PermGen space" in Maven build

We face this error when permanent generation heap is full and some of us we use command prompt to build our maven project in windows. since we need to increase heap size, we could set our environment variable @ControlPanel/System and Security/System and there you click on Change setting and select Advanced and set Environment variable as below

  • Variable-name : MAVEN_OPTS
  • Variable-value : -XX:MaxPermSize=128m

.NET Out Of Memory Exception - Used 1.3GB but have 16GB installed

If you have 32-bit Windows, this method is not working without following settings.

  1. Run prompt cmd.exe (important : Run As Administrator)
  2. type bcdedit.exe and run
  3. Look at the "increaseuserva" params and there is no then write following statement
  4. bcdedit /set increaseuserva 3072
  5. and again step 2 and check params

We added this settings and this block started.

if exist "$(DevEnvDir)..\tools\vsvars32.bat" (
   call "$(DevEnvDir)..\tools\vsvars32.bat"
   editbin /largeaddressaware "$(TargetPath)"
)

More info - command increaseuserva: https://docs.microsoft.com/en-us/windows-hardware/drivers/devtest/bcdedit--set

Spark java.lang.OutOfMemoryError: Java heap space

Broadly speaking, spark Executor JVM memory can be divided into two parts. Spark memory and User memory. This is controlled by property spark.memory.fraction - the value is between 0 and 1. When working with images or doing memory intensive processing in spark applications, consider decreasing the spark.memory.fraction. This will make more memory available to your application work. Spark can spill, so it will still work with less memory share.

The second part of the problem is division of work. If possible, partition your data into smaller chunks. Smaller data possibly needs less memory. But if that is not possible, you are sacrifice compute for memory. Typically a single executor will be running multiple cores. Total memory of executors must be enough to handle memory requirements of all concurrent tasks. If increasing executor memory is not a option, you can decrease the cores per executor so that each task gets more memory to work with. Test with 1 core executors which have largest possible memory you can give and then keep increasing cores until you find the best core count.

Android Studio - How to increase Allocated Heap Size

I found on on Windows 7/8 (64-bit), as of Android Studio 1.1.0:

[INSTALL_DIR]\bin\studio64.exe.vmoptions be used (if it exists), otherwise it would always fall back to %USERPROFILE%.\AndroidStudio\studio[64].exe.vmoptions

If you want the settings managed from %USERPROFILE%.\AndroidStudio\studio[64].exe.vmoptions, just delete the one in the installation directory.

java.lang.OutOfMemoryError: bitmap size exceeds VM budget - Android

One of the most common errors that I found developing Android Apps is the “java.lang.OutOfMemoryError: Bitmap Size Exceeds VM Budget” error. I found this error frequently on activities using lots of bitmaps after changing orientation: the Activity is destroyed, created again and the layouts are “inflated” from the XML consuming the VM memory available for bitmaps.

Bitmaps on the previous activity layout are not properly de-allocated by the garbage collector because they have crossed references to their activity. After many experiments I found a quite good solution for this problem.

First, set the “id” attribute on the parent view of your XML layout:

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent"
     android:id="@+id/RootView"
     >
     ...

Then, on the onDestroy() method of your Activity, call the unbindDrawables() method passing a reference to the parent View and then do a System.gc().

    @Override
    protected void onDestroy() {
    super.onDestroy();

    unbindDrawables(findViewById(R.id.RootView));
    System.gc();
    }

    private void unbindDrawables(View view) {
        if (view.getBackground() != null) {
        view.getBackground().setCallback(null);
        }
        if (view instanceof ViewGroup) {
            for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
            unbindDrawables(((ViewGroup) view).getChildAt(i));
            }
        ((ViewGroup) view).removeAllViews();
        }
    }

This unbindDrawables() method explores the view tree recursively and:

  1. Removes callbacks on all the background drawables
  2. Removes children on every viewgroup

"java.lang.OutOfMemoryError : unable to create new native Thread"

If your Job is failing because of OutOfMemmory on nodes you can tweek your number of max maps and reducers and the JVM opts for each. mapred.child.java.opts (the default is 200Xmx) usually has to be increased based on your data nodes specific hardware.

This link might be helpful... pls check

java.lang.OutOfMemoryError: Java heap space in Maven

To temporarily work around this problem, I found the following to be the quickest way:

export JAVA_TOOL_OPTIONS="-Xmx1024m -Xms1024m"

How do you add swap to an EC2 instance?

Try swapspace http://pqxx.org/development/swapspace/

Most distros have it packaged.

On EC2 you might want to change "swappath" to /mnt or high-iops disk.

How to increase heap size for jBoss server

Look in your JBoss bin folder for the file run.bat (run.sh on Unix)

look for the line set JAVA_OPTS, (or just JAVA_OPTS on Unix) at the end of that line add -Xmx512m. Change the number to the amount of memory you want to allocate to JBoss.

If you are using a custom script to start your jboss instance, you can add the set JAVA_OPTS option there as well.

Understanding the Linux oom-killer's logs

This webpage have an explanation and a solution.

The solution is:

To fix this problem the behavior of the kernel has to be changed, so it will no longer overcommit the memory for application requests. Finally I have included those mentioned values into the /etc/sysctl.conf file, so they get automatically applied on start-up:

vm.overcommit_memory = 2

vm.overcommit_ratio = 80

Maven Out of Memory Build Failure

This happens in big projects on Windows when cygwin or other linux emulator is used(git bash). By some coincidence, both does not work on my project, what is an big open source project. In a sh script, a couple of mvn commands are called. The memory size grows to heap size bigger that specified in Xmx and most of the time in a case second windows process is started. This is making the memory consumption even higher.

The solution in this case is to use batch file and reduced Xmx size and then the maven operations are successful. If there is interest I can reveal more details.

Dealing with "java.lang.OutOfMemoryError: PermGen space" error

I tried several answers and the only thing what finally did the job was this configuration for the compiler plugin in the pom:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>2.3.2</version>
    <configuration>
        <fork>true</fork>
        <meminitial>128m</meminitial>
        <maxmem>512m</maxmem>
        <source>1.6</source>
        <target>1.6</target>
        <!-- prevent PermGen space out of memory exception -->
        <!-- <argLine>-Xmx512m -XX:MaxPermSize=512m</argLine> -->
    </configuration>
</plugin>

hope this one helps.

'System.OutOfMemoryException' was thrown when there is still plenty of memory free

I had a similar problem, it was due to a StringBuilder.ToString();

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space

There is a another best/effective way to solve this error,

for example, let's take a loop which counts till 10 thousand, here you may get the error Out of memory, do to solve it you can give the computer time to recover.

So, you can sleep for 400-500ms before you're loop counts the next number :

new Thread(new Runnable() {
            public void run() {
                try {
                    sleep(550); // 550 ms (milli seconds)
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

By doing this, will make you're program slower but you don't get any error till the heap space is full again, so by waiting some ms, you can prevent that error.

You can apply this method other than loop.

Hope it helped you, :D

How to deal with "java.lang.OutOfMemoryError: Java heap space" error?

In android studio add/change this line at the end of gradle.properties (Global Properties):

...
org.gradle.jvmargs=-XX\:MaxHeapSize\=1024m -Xmx1024m 

if it doesn't work you can retry with bigger than 1024 heap size.

java.lang.OutOfMemoryError: Java heap space

  1. Local variables are located on the stack. Heap space is occupied by objects.

  2. You can use the -Xmx option.

  3. Basically heap space is used up everytime you allocate a new object with new and freed some time after the object is no longer referenced. So make sure that you don't keep references to objects that you no longer need.

Strange out of memory issue while loading an image to a Bitmap object

I've made a small improvement to Fedor's code. It basically does the same, but without the (in my opinion) ugly while loop and it always results in a power of two. Kudos to Fedor for making the original solution, I was stuck until I found his, and then I was able to make this one :)

 private Bitmap decodeFile(File f){
    Bitmap b = null;

        //Decode image size
    BitmapFactory.Options o = new BitmapFactory.Options();
    o.inJustDecodeBounds = true;

    FileInputStream fis = new FileInputStream(f);
    BitmapFactory.decodeStream(fis, null, o);
    fis.close();

    int scale = 1;
    if (o.outHeight > IMAGE_MAX_SIZE || o.outWidth > IMAGE_MAX_SIZE) {
        scale = (int)Math.pow(2, (int) Math.ceil(Math.log(IMAGE_MAX_SIZE / 
           (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
    }

    //Decode with inSampleSize
    BitmapFactory.Options o2 = new BitmapFactory.Options();
    o2.inSampleSize = scale;
    fis = new FileInputStream(f);
    b = BitmapFactory.decodeStream(fis, null, o2);
    fis.close();

    return b;
}

How to use Visual Studio Code as Default Editor for Git

I opened up my .gitconfig and amended it with:

[core]
    editor = 'C:/Users/miqid/AppData/Local/Code/app-0.1.0/Code.exe'

That did it for me (I'm on Windows 8).

However, I noticed that after I tried an arbitrary git commit that in my Git Bash console I see the following message:

[9168:0504/160114:INFO:renderer_main.cc(212)] Renderer process started

Unsure of what the ramifications of this might be.

How to run eclipse in clean mode? what happens if we do so?

For Windows users: You can do as RTA said or through command line do this: Navigate to the locaiton of the eclipse executable then run:

 eclipse.lnk -clean

First check the name of your executable using the command 'dir' on its path

How do I add a Maven dependency in Eclipse?

In fact when you open the pom.xml, you should see 5 tabs in the bottom. Click the pom.xml, and you can type whatever dependencies you want.

enter image description here

jQuery find element by data attribute value

I searched for a the same solution with a variable instead of the String.
I hope i can help someone with my solution :)

var numb = "3";
$(`#myid[data-tab-id=${numb}]`);

error C2039: 'string' : is not a member of 'std', header file problem

Take care not to include

#include <string.h> 

but only

#include <string>

It took me 1 hour to find this in my code.

Hope this can help

How is a CRC32 checksum calculated?

Then there is always Rosetta Code, which shows crc32 implemented in dozens of computer languages. https://rosettacode.org/wiki/CRC-32 and has links to many explanations and implementations.

What is Hive: Return Code 2 from org.apache.hadoop.hive.ql.exec.MapRedTask

That's not the real error, here's how to find it:

Go to the hadoop jobtracker web-dashboard, find the hive mapreduce jobs that failed and look at the logs of the failed tasks. That will show you the real error.

The console output errors are useless, largely beause it doesn't have a view of the individual jobs/tasks to pull the real errors (there could be errors in multiple tasks)

Hope that helps.

Using :after to clear floating elements

Write like this:

.wrapper:after {
    content: '';
    display: block;
    clear: both;
}

Check this http://jsfiddle.net/EyNnk/1/

ld: framework not found Pods

I cleared this error by deleting the red .framework files that were located in a folder Frameworks in the project navigator. I think this also automatically deleted corresponding red entries in the Linked Frameworks and Libraries section of the General settings.

I have been cleaning / reinstalling pods in order to fix another issue. Perhaps these red framework files and entries were just leftover from a previous pod install?

JS regex: replace all digits in string

Use

s.replace(/\d/g, "X")

which will replace all occurrences. The g means global match and thus will not stop matching after the first occurrence.

Or to stay with your RegExp constructor:

s.replace(new RegExp("\\d", "g"), "X")

How to fix "unable to write 'random state' " in openssl

I did not find where the .rnd file is so I ran the cmd as administrator and it worked like a charm.

Best Java obfuscator?

We've had much better luck encrypting the jars rather than obfuscating. We use Classguard.

Check whether a cell contains a substring

Check out the FIND() function in Excel.

Syntax:

FIND( substring, string, [start_position])

Returns #VALUE! if it doesn't find the substring.

What is the difference between user variables and system variables?

Environment variable (can access anywhere/ dynamic object) is a type of variable. They are of 2 types system environment variables and user environment variables.

System variables having a predefined type and structure. That are used for system function. Values that produced by the system are stored in the system variable. They generally indicated by using capital letters Example: HOME,PATH,USER

User environment variables are the variables that determined by the user,and are represented by using small letters.

css selector to match an element without attribute x

:not selector:

input:not([type]), input[type='text'], input[type='password'] {
    /* style here */
}

Support: in Internet Explorer 9 and higher

How to output numbers with leading zeros in JavaScript?

Just for fun (I had some time to kill), a more sophisticated implementation which caches the zero-string:

pad.zeros = new Array(5).join('0');
function pad(num, len) {
    var str = String(num),
        diff = len - str.length;
    if(diff <= 0) return str;
    if(diff > pad.zeros.length)
        pad.zeros = new Array(diff + 1).join('0');
    return pad.zeros.substr(0, diff) + str;
}

If the padding count is large and the function is called often enough, it actually outperforms the other methods...

Detect viewport orientation, if orientation is Portrait display alert message advising user of instructions

$(window).on("orientationchange",function( event ){
    alert(screen.orientation.type)
});

Clean out Eclipse workspace metadata

The only way I know to deal with this is to create a new workspace, import projects from the polluted workspace, reconstructing all my settings (a major pain) and then delete the old workspace. Is there an easier way to deal with this?

For synchronizing or restoring all our settings we use Workspace Mechanic. Once all the settings are recorded its one click and all settings are restored... You can also setup a server which provides those settings for all users.

NoClassDefFoundError - Eclipse and Android

If you change your order and export in your project build path, this error will not occur. The other way of achieving it is through .classpath in your project folder.

Copying files to a container with Docker Compose

Given

    volumes:
      - /dir/on/host:/var/www/html

if /dir/on/host doesn't exist, it is created on the host and the empty content is mounted in the container at /var/www/html. Whatever content you had before in /var/www/html inside the container is inaccessible, until you unmount the volume; the new mount is hiding the old content.

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

I think you just have incorrect casing in the format string. According to the documentation this should work for you: MM/DD/YYYY

moment.js documentation

How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause()

Try using a callback like this with the catch block.

document.getElementById("audio").play().catch(function() {
    // do something
});

How to change package name in flutter?

On Visual Studio code

Edit > Replace in Files

vs code replace in files

On Android studio

1. Right click on your project > Replace in path

replace in path

2. Write your old package and new package > Replace all

replace all screenshot

I need to round a float to two decimal places in Java

Try looking at the BigDecimal Class. It is the go to class for currency and support accurate rounding.

Import Certificate to Trusted Root but not to Personal [Command Line]

Look at the documentation of certutil.exe and -addstore option.

I tried

certutil -addstore "Root" "c:\cacert.cer"

and it worked well (meaning The certificate landed in Trusted Root of LocalMachine store).

EDIT:

If there are multiple certificates in a pfx file (key + corresponding certificate and a CA certificate) then this command worked well for me:

certutil -importpfx c:\somepfx.pfx

EDIT2:

To import CA certificate to Intermediate Certification Authorities store run following command

certutil -addstore "CA" "c:\intermediate_cacert.cer"

How can I set the PATH variable for javac so I can manually compile my .java works?

First thing I wann ans to this imp question: "Why we require PATH To be set?"

Answer : You need to set PATH to compile Java source code, create JAVA CLASS FILES and allow Operating System to load classes at runtime.

Now you will understand why after setting "javac" you can manually compile by just saying "Class_name.java"

Modify the PATH of Windows Environmental Variable by appending the location till bin directory where all exe file(for eg. java,javac) are present.

Example : ;C:\Program Files\Java\jre7\bin.

How to convert a Bitmap to Drawable in android?

Try this it converts a Bitmap type image to Drawable

Drawable d = new BitmapDrawable(getResources(), bitmap);

command/usr/bin/codesign failed with exit code 1- code sign error

I was having the issue after select the deny when it asks for permission

After some search I got it fixed by restarting the system.

How to change dot size in gnuplot

The pointsize command scales the size of points, but does not affect the size of dots.

In other words, plot ... with points ps 2 will generate points of twice the normal size, but for plot ... with dots ps 2 the "ps 2" part is ignored.

You could use circular points (pt 7), which look just like dots.

How do I vertically center text with CSS?

This works perfectly.

You have to use table style for the div and center align for the content.

How to trap on UIViewAlertForUnsatisfiableConstraints?

You'll want to add a Symbolic Breakpoint. Apple provides an excellent guide on how to do this.

  1. Open the Breakpoint Navigator cmd+7 (cmd+8 in Xcode 9)
  2. Click the Add button in the lower left
  3. Select Add Symbolic Breakpoint...
  4. Where it says Symbol just type in UIViewAlertForUnsatisfiableConstraints

You can also treat it like any other breakpoint, turning it on and off, adding actions, or log messages.

Where is body in a nodejs http.get response?

Edit: replying to self 6 years later

The await keyword is the best way to get a response from an HTTP request, avoiding callbacks and .then()

You'll also need to use an HTTP client that returns Promises. http.get() still returns a Request object, so that won't work.

  • fetch is a low level client, that is both available from npm and will be in future versions of node
  • superagent is a mature HTTP clients that features more reasonable defaults including simpler query string encoding, properly using mime types, JSON by default, and other common HTTP client features.
  • axois is also quite popular and has similar advantages to superagent

await will wait until the Promise has a value - in this case, an HTTP response!

const superagent = require('superagent');

(async function(){
  const response = await superagent.get('https://www.google.com')
  console.log(response.text)
})();

Using await, control simply passes onto the next line once the promise returned by superagent.get() has a value.

Python Pandas replicate rows in dataframe

You can put df_try inside a list and then do what you have in mind:

>>> df.append([df_try]*5,ignore_index=True)

    Store  Dept       Date  Weekly_Sales IsHoliday
0       1     1 2010-02-05      24924.50     False
1       1     1 2010-02-12      46039.49      True
2       1     1 2010-02-19      41595.55     False
3       1     1 2010-02-26      19403.54     False
4       1     1 2010-03-05      21827.90     False
5       1     1 2010-03-12      21043.39     False
6       1     1 2010-03-19      22136.64     False
7       1     1 2010-03-26      26229.21     False
8       1     1 2010-04-02      57258.43     False
9       1     1 2010-02-12      46039.49      True
10      1     1 2010-02-12      46039.49      True
11      1     1 2010-02-12      46039.49      True
12      1     1 2010-02-12      46039.49      True
13      1     1 2010-02-12      46039.49      True

How to detect the OS from a Bash script?

I recommend to use this complete bash code

lowercase(){
    echo "$1" | sed "y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/"
}

OS=`lowercase \`uname\``
KERNEL=`uname -r`
MACH=`uname -m`

if [ "{$OS}" == "windowsnt" ]; then
    OS=windows
elif [ "{$OS}" == "darwin" ]; then
    OS=mac
else
    OS=`uname`
    if [ "${OS}" = "SunOS" ] ; then
        OS=Solaris
        ARCH=`uname -p`
        OSSTR="${OS} ${REV}(${ARCH} `uname -v`)"
    elif [ "${OS}" = "AIX" ] ; then
        OSSTR="${OS} `oslevel` (`oslevel -r`)"
    elif [ "${OS}" = "Linux" ] ; then
        if [ -f /etc/redhat-release ] ; then
            DistroBasedOn='RedHat'
            DIST=`cat /etc/redhat-release |sed s/\ release.*//`
            PSUEDONAME=`cat /etc/redhat-release | sed s/.*\(// | sed s/\)//`
            REV=`cat /etc/redhat-release | sed s/.*release\ // | sed s/\ .*//`
        elif [ -f /etc/SuSE-release ] ; then
            DistroBasedOn='SuSe'
            PSUEDONAME=`cat /etc/SuSE-release | tr "\n" ' '| sed s/VERSION.*//`
            REV=`cat /etc/SuSE-release | tr "\n" ' ' | sed s/.*=\ //`
        elif [ -f /etc/mandrake-release ] ; then
            DistroBasedOn='Mandrake'
            PSUEDONAME=`cat /etc/mandrake-release | sed s/.*\(// | sed s/\)//`
            REV=`cat /etc/mandrake-release | sed s/.*release\ // | sed s/\ .*//`
        elif [ -f /etc/debian_version ] ; then
            DistroBasedOn='Debian'
            DIST=`cat /etc/lsb-release | grep '^DISTRIB_ID' | awk -F=  '{ print $2 }'`
            PSUEDONAME=`cat /etc/lsb-release | grep '^DISTRIB_CODENAME' | awk -F=  '{ print $2 }'`
            REV=`cat /etc/lsb-release | grep '^DISTRIB_RELEASE' | awk -F=  '{ print $2 }'`
        fi
        if [ -f /etc/UnitedLinux-release ] ; then
            DIST="${DIST}[`cat /etc/UnitedLinux-release | tr "\n" ' ' | sed s/VERSION.*//`]"
        fi
        OS=`lowercase $OS`
        DistroBasedOn=`lowercase $DistroBasedOn`
        readonly OS
        readonly DIST
        readonly DistroBasedOn
        readonly PSUEDONAME
        readonly REV
        readonly KERNEL
        readonly MACH
    fi

fi
echo $OS
echo $KERNEL
echo $MACH

more examples examples here: https://github.com/coto/server-easy-install/blob/master/lib/core.sh

How to set HTML Auto Indent format on Sublime Text 3?

This was bugging me too, since this was a standard feature in Sublime Text 2, but somehow automatic indentation no longer worked in Sublime Text 3 for HTML files.

My solution was to find the Miscellaneous.tmPreferences file from Sublime Text 2 (found under %AppData%/Roaming/Sublime Text 2/Packages/HTML) and copy those settings to the same file for ST3.

Now package handling has been made more difficult for ST3, but luckily you can just add the files to your %AppData%/Roaming/Sublime Text 3/Packages folder and they overwrite default settings in the install directory. Just save this file as "%AppData%/Roaming/Sublime Text 3/Packages/HTML/Miscellaneous.tmPreferences" and auto indent works again like it did in ST2.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>name</key>
    <string>Miscellaneous</string>
    <key>scope</key>
    <string>text.html</string>
    <key>settings</key>
    <dict>
        <key>decreaseIndentPattern</key>
            <string>(?x)
            ^\s*
            (&lt;/(?!html)
              [A-Za-z0-9]+\b[^&gt;]*&gt;
            |--&gt;
            |&lt;\?(php)?\s+(else(if)?|end(if|for(each)?|while))
            |\}
            )</string>
        <key>batchDecreaseIndentPattern</key>
            <string>(?x)
            ^\s*
            (&lt;/(?!html)
              [A-Za-z0-9]+\b[^&gt;]*&gt;
            |--&gt;
            |&lt;\?(php)?\s+(else(if)?|end(if|for(each)?|while))
            |\}
            )</string>
        <key>increaseIndentPattern</key>
            <string>(?x)
            ^\s*
            &lt;(?!\?|area|base|br|col|frame|hr|html|img|input|link|meta|param|[^&gt;]*/&gt;)
              ([A-Za-z0-9]+)(?=\s|&gt;)\b[^&gt;]*&gt;(?!.*&lt;/\1&gt;)
            |&lt;!--(?!.*--&gt;)
            |&lt;\?php.+?\b(if|else(?:if)?|for(?:each)?|while)\b.*:(?!.*end\1)
            |\{[^}"']*$
            </string>
        <key>batchIncreaseIndentPattern</key>
            <string>(?x)
            ^\s*
            &lt;(?!\?|area|base|br|col|frame|hr|html|img|input|link|meta|param|[^&gt;]*/&gt;)
              ([A-Za-z0-9]+)(?=\s|&gt;)\b[^&gt;]*&gt;(?!.*&lt;/\1&gt;)
            |&lt;!--(?!.*--&gt;)
            |&lt;\?php.+?\b(if|else(?:if)?|for(?:each)?|while)\b.*:(?!.*end\1)
            |\{[^}"']*$
            </string>
        <key>bracketIndentNextLinePattern</key>
         <string>&lt;!DOCTYPE(?!.*&gt;)</string>
    </dict>
</dict>
</plist>

Loading and parsing a JSON file with multiple JSON objects

You have a JSON Lines format text file. You need to parse your file line by line:

import json

data = []
with open('file') as f:
    for line in f:
        data.append(json.loads(line))

Each line contains valid JSON, but as a whole, it is not a valid JSON value as there is no top-level list or object definition.

Note that because the file contains JSON per line, you are saved the headaches of trying to parse it all in one go or to figure out a streaming JSON parser. You can now opt to process each line separately before moving on to the next, saving memory in the process. You probably don't want to append each result to one list and then process everything if your file is really big.

If you have a file containing individual JSON objects with delimiters in-between, use How do I use the 'json' module to read in one JSON object at a time? to parse out individual objects using a buffered method.

How to make a form close when pressing the escape key?

If you have a cancel button on your form, you can set the Form.CancelButton property to that button and then pressing escape will effectively 'click the button'.

If you don't have such a button, check out the Form.KeyPreview property.

Vue JS mounted()

You can also move mounted out of the Vue instance and make it a function in the top-level scope. This is also a useful trick for server side rendering in Vue.

function init() {
  // Use `this` normally
}

new Vue({
  methods:{
    init
  },
  mounted(){
    init.call(this)
  }
})

A better way to check if a path exists or not in PowerShell

if (Test-Path C:\DockerVol\SelfCertSSL) {
    write-host "Folder already exists."
} else {
   New-Item -Path "C:\DockerVol\" -Name "SelfCertSSL" -ItemType "directory"
}

assign headers based on existing row in dataframe in R

The cleanest way is use a function of janitor package that is built for exactly this purpose.

janitor::row_to_names(DF,1)

If you want to use any other row than the first one, pass it in the second parameter.

How to correctly write async method?

To get the behavior you want you need to wait for the process to finish before you exit Main(). To be able to tell when your process is done you need to return a Task instead of a void from your function, you should never return void from a async function unless you are working with events.

A re-written version of your program that works correctly would be

class Program {     static void Main(string[] args)     {         Debug.WriteLine("Calling DoDownload");         var downloadTask = DoDownloadAsync();         Debug.WriteLine("DoDownload done");         downloadTask.Wait(); //Waits for the background task to complete before finishing.      }      private static async Task DoDownloadAsync()     {         WebClient w = new WebClient();          string txt = await w.DownloadStringTaskAsync("http://www.google.com/");         Debug.WriteLine(txt);     } } 

Because you can not await in Main() I had to do the Wait() function instead. If this was a application that had a SynchronizationContext I would do await downloadTask; instead and make the function this was being called from async.

Spring MVC Missing URI template variable

I got this error for a stupid mistake, the variable name in the @PathVariable wasn't matching the one in the @RequestMapping

For example

@RequestMapping(value = "/whatever/{**contentId**}", method = RequestMethod.POST)
public … method(@PathVariable Integer **contentID**){
}

It may help others

How to solve npm install throwing fsevents warning on non-MAC OS?

If you want to hide this warn, you just need to install fsevents as a optional dependency. Just execute:

npm i fsevents@latest -f --save-optional

..And the warn will no longer be a bother.

Typescript Date Type?

The answer is super simple, the type is Date:

const d: Date = new Date(); // but the type can also be inferred from "new Date()" already

It is the same as with every other object instance :)

Cancel split window in Vim

I understand you intention well, I use buffers exclusively too, and occasionally do split if needed.

below is excerpt of my .vimrc

" disable macro, since not used in 90+% use cases
map q <Nop>
" q,  close/hide current window, or quit vim if no other window
nnoremap q :if winnr('$') > 1 \|hide\|else\|silent! exec 'q'\|endif<CR>
" qo, close all other window    -- 'o' stands for 'only'
nnoremap qo :only<CR>
set hidden
set timeout
set timeoutlen=200   " let vim wait less for your typing!

Which fits my workflow quite well

If q was pressed

  • hide current window if multiple window open, else try to quit vim.

if qo was pressed,

  • close all other window, no effect if only one window.

Of course, you can wrap that messy part into a function, eg

func! Hide_cur_window_or_quit_vim()
    if winnr('$') > 1
        hide
    else
        silent! exec 'q'
    endif
endfunc
nnoremap q :call Hide_cur_window_or_quit_vim()<CR>

Sidenote: I remap q, since I do not use macro for editing, instead use :s, :g, :v, and external text processing command if needed, eg, :'{,'}!awk 'some_programm', or use :norm! normal-command-here.

How to get Spinner selected item value to string?

I think you want the selected item of the spinner when button is clicked..

Try getSelectedItem():

spinner.getSelectedItem()

Automatically plot different colored lines

You could use a colormap such as HSV to generate a set of colors. For example:

cc=hsv(12);
figure; 
hold on;
for i=1:12
    plot([0 1],[0 i],'color',cc(i,:));
end

MATLAB has 13 different named colormaps ('doc colormap' lists them all).

Another option for plotting lines in different colors is to use the LineStyleOrder property; see Defining the Color of Lines for Plotting in the MATLAB documentation for more information.

Where does this come from: -*- coding: utf-8 -*-

This way of specifying the encoding of a Python file comes from PEP 0263 - Defining Python Source Code Encodings.

It is also recognized by GNU Emacs (see Python Language Reference, 2.1.4 Encoding declarations), though I don't know if it was the first program to use that syntax.

Case insensitive regular expression without re.compile?

#'re.IGNORECASE' for case insensitive results short form re.I
#'re.match' returns the first match located from the start of the string. 
#'re.search' returns location of the where the match is found 
#'re.compile' creates a regex object that can be used for multiple matches

 >>> s = r'TeSt'   
 >>> print (re.match(s, r'test123', re.I))
 <_sre.SRE_Match object; span=(0, 4), match='test'>
 # OR
 >>> pattern = re.compile(s, re.I)
 >>> print(pattern.match(r'test123'))
 <_sre.SRE_Match object; span=(0, 4), match='test'>

How to get ° character in a string in python?

This is the most coder-friendly version of specifying a unicode character:

degree_sign= u'\N{DEGREE SIGN}'

Note: must be a capital N in the \N construct to avoid confusion with the '\n' newline character. The character name inside the curly braces can be any case.

It's easier to remember the name of a character than its unicode index. It's also more readable, ergo debugging-friendly. The character substitution happens at compile time: the .py[co] file will contain a constant for u'°':

>>> import dis
>>> c= compile('u"\N{DEGREE SIGN}"', '', 'eval')
>>> dis.dis(c)
  1           0 LOAD_CONST               0 (u'\xb0')
              3 RETURN_VALUE
>>> c.co_consts
(u'\xb0',)
>>> c= compile('u"\N{DEGREE SIGN}-\N{EMPTY SET}"', '', 'eval')
>>> c.co_consts
(u'\xb0-\u2205',)
>>> print c.co_consts[0]
°-Ø

How to send an email from JavaScript

I know I am wayyy too late to write an answer for this question but nevertheless I think this will be use for anybody who is thinking of sending emails out via javascript.

The first way I would suggest is using a callback to do this on the server. If you really want it to be handled using javascript folowing is what I recommend.

The easiest way I found was using smtpJs. A free library which can be used to send emails.

1.Include the script like below

<script src="https://smtpjs.com/v3/smtp.js"></script>

2. You can either send an email like this

_x000D_
_x000D_
Email.send({_x000D_
    Host : "smtp.yourisp.com",_x000D_
    Username : "username",_x000D_
    Password : "password",_x000D_
    To : '[email protected]',_x000D_
    From : "[email protected]",_x000D_
    Subject : "This is the subject",_x000D_
    Body : "And this is the body"_x000D_
    }).then(_x000D_
      message => alert(message)_x000D_
    );
_x000D_
_x000D_
_x000D_

Which is not advisable as it will display your password on the client side.Thus you can do the following which encrypt your SMTP credentials, and lock it to a single domain, and pass a secure token instead of the credentials instead.

_x000D_
_x000D_
Email.send({_x000D_
    SecureToken : "C973D7AD-F097-4B95-91F4-40ABC5567812",_x000D_
    To : '[email protected]',_x000D_
    From : "[email protected]",_x000D_
    Subject : "This is the subject",_x000D_
    Body : "And this is the body"_x000D_
}).then(_x000D_
  message => alert(message)_x000D_
);
_x000D_
_x000D_
_x000D_

Finally if you do not have a SMTP server you use an smtp relay service such as Elastic Email

Also here is the link to the official SmtpJS.com website where you can find all the example you need and the place where you can create your secure token.

I hope someone find this details useful. Happy coding.

How to get user name using Windows authentication in asp.net?

These are the different variables you have access to and their values, depending on the IIS configuration.

Scenario 1: Anonymous Authentication in IIS with impersonation off.

HttpContext.Current.Request.LogonUserIdentity.Name    SERVER1\IUSR_SERVER1 
HttpContext.Current.Request.IsAuthenticated           False                    
HttpContext.Current.User.Identity.Name                –                        
System.Environment.UserName                           ASPNET                   
Security.Principal.WindowsIdentity.GetCurrent().Name  SERVER1\ASPNET

Scenario 2: Windows Authentication in IIS, impersonation off.

HttpContext.Current.Request.LogonUserIdentity.Name    MYDOMAIN\USER1   
HttpContext.Current.Request.IsAuthenticated           True             
HttpContext.Current.User.Identity.Name                MYDOMAIN\USER1   
System.Environment.UserName                           ASPNET           
Security.Principal.WindowsIdentity.GetCurrent().Name  SERVER1\ASPNET

Scenario 3: Anonymous Authentication in IIS, impersonation on

HttpContext.Current.Request.LogonUserIdentity.Name    SERVER1\IUSR_SERVER1 
HttpContext.Current.Request.IsAuthenticated           False                    
HttpContext.Current.User.Identity.Name                –                        
System.Environment.UserName                           IUSR_SERVER1           
Security.Principal.WindowsIdentity.GetCurrent().Name  SERVER1\IUSR_SERVER1 

Scenario 4: Windows Authentication in IIS, impersonation on

HttpContext.Current.Request.LogonUserIdentity.Name    MYDOMAIN\USER1
HttpContext.Current.Request.IsAuthenticated           True          
HttpContext.Current.User.Identity.Name                MYDOMAIN\USER1
System.Environment.UserName                           USER1         
Security.Principal.WindowsIdentity.GetCurrent().Name  MYDOMAIN\USER1

Legend
SERVER1\ASPNET: Identity of the running process on server.
SERVER1\IUSR_SERVER1: Anonymous guest user defined in IIS.
MYDOMAIN\USER1: The user of the remote client.

Source

Python Prime number checker

You need to stop iterating once you know a number isn't prime. Add a break once you find prime to exit the while loop.

Making only minimal changes to your code to make it work:

a=2
num=13
while num > a :
  if num%a==0 & a!=num:
    print('not prime')
    break
  i += 1
else: # loop not exited via break
  print('prime')

Your algorithm is equivalent to:

for a in range(a, num):
    if a % num == 0:
        print('not prime')
        break
else: # loop not exited via break
    print('prime')

If you throw it into a function you can dispense with break and for-else:

def is_prime(n):
    for i in range(3, n):
        if n % i == 0:
            return False
    return True

Even if you are going to brute-force for prime like this you only need to iterate up to the square root of n. Also, you can skip testing the even numbers after two.

With these suggestions:

import math
def is_prime(n):
    if n % 2 == 0 and n > 2: 
        return False
    for i in range(3, int(math.sqrt(n)) + 1, 2):
        if n % i == 0:
            return False
    return True

Note that this code does not properly handle 0, 1, and negative numbers.

We make this simpler by using all with a generator expression to replace the for-loop.

import math
def is_prime(n):
    if n % 2 == 0 and n > 2: 
        return False
    return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2))

How to spyOn a value property (rather than a method) with Jasmine

In February 2017, they merged a PR adding this feature, they released in April 2017.

so to spy on getters/setters you use: const spy = spyOnProperty(myObj, 'myGetterName', 'get'); where myObj is your instance, 'myGetterName' is the name of that one defined in your class as get myGetterName() {} and the third param is the type get or set.

You can use the same assertions that you already use with the spies created with spyOn.

So you can for example:

const spy = spyOnProperty(myObj, 'myGetterName', 'get'); // to stub and return nothing. Just spy and stub.
const spy = spyOnProperty(myObj, 'myGetterName', 'get').and.returnValue(1); // to stub and return 1 or any value as needed.
const spy = spyOnProperty(myObj, 'myGetterName', 'get').and.callThrough(); // Call the real thing.

Here's the line in the github source code where this method is available if you are interested.

https://github.com/jasmine/jasmine/blob/7f8f2b5e7a7af70d7f6b629331eb6fe0a7cb9279/src/core/requireInterface.js#L199

Answering the original question, with jasmine 2.6.1, you would:

const spy = spyOnProperty(myObj, 'valueA', 'get').andReturn(1);
expect(myObj.valueA).toBe(1);
expect(spy).toHaveBeenCalled();

Send private messages to friends

There isn't any graph api for this, you need to use facebook xmpp chat api to send the message, good news is: I have made a php class which is too easy to use,call a function and message will be sent, its open source, check it out: facebook message api php the description says its a closed source but the it was made open source later, see the first comment, you can clone from github. It's a open source now.

The source was not found, but some or all event logs could not be searched

Inaccessible logs: Security

A new event source needs to have a unique name across all logs including Security (which needs admin privilege when it's being read).

So your app will need admin privilege to create a source. But that's probably an overkill.

I wrote this powershell script to create the event source at will. Save it as *.ps1 and run it with any privilege and it will elevate itself.

# CHECK OR RUN AS ADMIN

If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{   
    $arguments = "& '" + $myinvocation.mycommand.definition + "'"
    Start-Process powershell -Verb runAs -ArgumentList $arguments
    Break
}

# CHECK FOR EXISTENCE OR CREATE

$source = "My Service Event Source";
$logname = "Application";

if ([System.Diagnostics.EventLog]::SourceExists($source) -eq $false) {
    [System.Diagnostics.EventLog]::CreateEventSource($source, $logname);
    Write-Host $source -f white -nonewline; Write-Host " successfully added." -f green;
}
else
{
    Write-Host $source -f white -nonewline; Write-Host " already exists.";
}

# DONE

Write-Host -NoNewLine 'Press any key to continue...';
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown');

Which is fastest? SELECT SQL_CALC_FOUND_ROWS FROM `table`, or SELECT COUNT(*)

It depends. See the MySQL Performance Blog post on this subject: To SQL_CALC_FOUND_ROWS or not to SQL_CALC_FOUND_ROWS?

Just a quick summary: Peter says that it depends on your indexes and other factors. Many of the comments to the post seem to say that SQL_CALC_FOUND_ROWS is almost always slower - sometimes up to 10x slower - than running two queries.

What is the point of WORKDIR on Dockerfile?

You can think of WORKDIR like a cd inside the container (it affects commands that come later in the Dockerfile, like the RUN command). If you removed WORKDIR in your example above, RUN npm install wouldn't work because you would not be in the /usr/src/app directory inside your container.

I don't see how this would be related to where you put your Dockerfile (since your Dockerfile location on the host machine has nothing to do with the pwd inside the container). You can put the Dockerfile wherever you'd like in your project. However, the first argument to COPY is a relative path, so if you move your Dockerfile you may need to update those COPY commands.

psql: FATAL: role "postgres" does not exist

First you need create a user:

sudo -u postgres createuser --superuser $USER

After you create a database:

sudo -u postgres createdb $USER

Change $USER to your system username.

You can see the the complete solution here.

MySQLi prepared statements error reporting

Each method of mysqli can fail. You should test each return value. If one fails, think about whether it makes sense to continue with an object that is not in the state you expect it to be. (Potentially not in a "safe" state, but I think that's not an issue here.)

Since only the error message for the last operation is stored per connection/statement you might lose information about what caused the error if you continue after something went wrong. You might want to use that information to let the script decide whether to try again (only a temporary issue), change something or to bail out completely (and report a bug). And it makes debugging a lot easier.

$stmt = $mysqli->prepare("INSERT INTO testtable VALUES (?,?,?)");
// prepare() can fail because of syntax errors, missing privileges, ....
if ( false===$stmt ) {
  // and since all the following operations need a valid/ready statement object
  // it doesn't make sense to go on
  // you might want to use a more sophisticated mechanism than die()
  // but's it's only an example
  die('prepare() failed: ' . htmlspecialchars($mysqli->error));
}

$rc = $stmt->bind_param('iii', $x, $y, $z);
// bind_param() can fail because the number of parameter doesn't match the placeholders in the statement
// or there's a type conflict(?), or ....
if ( false===$rc ) {
  // again execute() is useless if you can't bind the parameters. Bail out somehow.
  die('bind_param() failed: ' . htmlspecialchars($stmt->error));
}

$rc = $stmt->execute();
// execute() can fail for various reasons. And may it be as stupid as someone tripping over the network cable
// 2006 "server gone away" is always an option
if ( false===$rc ) {
  die('execute() failed: ' . htmlspecialchars($stmt->error));
}

$stmt->close();

Just a few notes six years later...

The mysqli extension is perfectly capable of reporting operations that result in an (mysqli) error code other than 0 via exceptions, see mysqli_driver::$report_mode.
die() is really, really crude and I wouldn't use it even for examples like this one anymore.
So please, only take away the fact that each and every (mysql) operation can fail for a number of reasons; even if the exact same thing went well a thousand times before....

How to pad a string to a fixed length with spaces in Python?

First check to see if the string's length needs to be shortened, then add spaces until it is as long as the field length.

fieldLength = 15
string1 = string1[0:15] # If it needs to be shortened, shorten it
while len(string1) < fieldLength:
    rand += " "

VBA - Range.Row.Count

This works for me especially in pivots table filtering when I want the count of cells with data on a filtered column. Reduce k accordingly (k - 1) if you have a header row for filtering:

k = Sheets("Sheet1").Range("$A:$A").SpecialCells(xlCellTypeVisible).SpecialCells(xlCellTypeConstants).Count

If '<selector>' is an Angular component, then verify that it is part of this module

In my case I had a component in a Shared module.

The component was loading and worked well but typescript was highlighting the html tag with red line and showed this error message.

Inside this component, I noticed I didn't import a rxjs operator.

import {map} from 'rxjs/operators';

When I added this import the error message disappeared.

Check all imports inside the component.

Hope it helps someone.

Proper way to empty a C-String

I'm a beginner but...Up to my knowledge,the best way is

strncpy(dest_string,"",strlen(dest_string));

How can I autoplay a video using the new embed code style for Youtube?

Just add ?autoplay=1 after url in embed code, example :

<iframe width="420" height="315" src="http://www.youtube.com/embed/
oHg5SJYRHA0" frameborder="0"></iframe>

Change it to:

<iframe width="420" height="315" src="http://www.youtube.com/embed/
oHg5SJYRHA0?autoplay=1" frameborder="0"></iframe>

MongoDB query with an 'or' condition

db.Lead.find(

{"name": {'$regex' : '.*' + "Ravi" + '.*'}},
{
"$or": [{
    'added_by':"[email protected]"
}, {
    'added_by':"[email protected]"
}]
}

);

Page loaded over HTTPS but requested an insecure XMLHttpRequest endpoint

I had the same issue for my angular project, then I make it work in Chrome by changing the setting. Go to Chrome setting -->site setting -->Insecure content --> click add button of allow, then add your domain name [*.]XXXX.biz

Now problem will be solved.

Jackson - How to process (deserialize) nested JSON?

Your data is problematic in that you have inner wrapper objects in your array. Presumably your Vendor object is designed to handle id, name, company_id, but each of those multiple objects are also wrapped in an object with a single property vendor.

I'm assuming that you're using the Jackson Data Binding model.

If so then there are two things to consider:

The first is using a special Jackson config property. Jackson - since 1.9 I believe, this may not be available if you're using an old version of Jackson - provides UNWRAP_ROOT_VALUE. It's designed for cases where your results are wrapped in a top-level single-property object that you want to discard.

So, play around with:

objectMapper.configure(SerializationConfig.Feature.UNWRAP_ROOT_VALUE, true);

The second is using wrapper objects. Even after discarding the outer wrapper object you still have the problem of your Vendor objects being wrapped in a single-property object. Use a wrapper to get around this:

class VendorWrapper
{
    Vendor vendor;

    // gettors, settors for vendor if you need them
}

Similarly, instead of using UNWRAP_ROOT_VALUES, you could also define a wrapper class to handle the outer object. Assuming that you have correct Vendor, VendorWrapper object, you can define:

class VendorsWrapper
{
    List<VendorWrapper> vendors = new ArrayList<VendorWrapper>();

    // gettors, settors for vendors if you need them
}

// in your deserialization code:
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readValue(jsonInput, VendorsWrapper.class); 

The object tree for VendorsWrapper is analogous to your JSON:

VendorsWrapper:
    vendors:
    [
        VendorWrapper
            vendor: Vendor,
        VendorWrapper:
            vendor: Vendor,
        ...
    ]

Finally, you might use the Jackson Tree Model to parse this into JsonNodes, discarding the outer node, and for each JsonNode in the ArrayNode, calling:

mapper.readValue(node.get("vendor").getTextValue(), Vendor.class);

That might result in less code, but it seems no less clumsy than using two wrappers.

Entity Framework throws exception - Invalid object name 'dbo.BaseCs'

For what it is worth, I wanted to mention that in my case, the problem was coming from an AFTER INSERT Trigger!

These are not super visible so you might be searching for a while!

How do I create a URL shortener?

Did you omit O, 0, and i on purpose?

I just created a PHP class based on Ryan's solution.

<?php

    $shorty = new App_Shorty();

    echo 'ID: ' . 1000;
    echo '<br/> Short link: ' . $shorty->encode(1000);
    echo '<br/> Decoded Short Link: ' . $shorty->decode($shorty->encode(1000));


    /**
     * A nice shorting class based on Ryan Charmley's suggestion see the link on Stack Overflow below.
     * @author Svetoslav Marinov (Slavi) | http://WebWeb.ca
     * @see http://stackoverflow.com/questions/742013/how-to-code-a-url-shortener/10386945#10386945
     */
    class App_Shorty {
        /**
         * Explicitly omitted: i, o, 1, 0 because they are confusing. Also use only lowercase ... as
         * dictating this over the phone might be tough.
         * @var string
         */
        private $dictionary = "abcdfghjklmnpqrstvwxyz23456789";
        private $dictionary_array = array();

        public function __construct() {
            $this->dictionary_array = str_split($this->dictionary);
        }

        /**
         * Gets ID and converts it into a string.
         * @param int $id
         */
        public function encode($id) {
            $str_id = '';
            $base = count($this->dictionary_array);

            while ($id > 0) {
                $rem = $id % $base;
                $id = ($id - $rem) / $base;
                $str_id .= $this->dictionary_array[$rem];
            }

            return $str_id;
        }

        /**
         * Converts /abc into an integer ID
         * @param string
         * @return int $id
         */
        public function decode($str_id) {
            $id = 0;
            $id_ar = str_split($str_id);
            $base = count($this->dictionary_array);

            for ($i = count($id_ar); $i > 0; $i--) {
                $id += array_search($id_ar[$i - 1], $this->dictionary_array) * pow($base, $i - 1);
            }
            return $id;
        }
    }
?>

How do I wrap text in a pre tag?

Try using

<pre style="white-space:normal;">. 

Or better throw CSS.

Reading string from input with space character?

The correct answer is this:

#include <stdio.h>

int main(void)
{
    char name[100];

    printf("Enter your name: ");
    // pay attention to the space in front of the %
    //that do all the trick
    scanf(" %[^\n]s", name);
    printf("Your Name is: %s", name);

    return 0;
}

That space in front of % is very important, because if you have in your program another few scanf let's say you have 1 scanf of an integer value and another scanf with a double value... when you reach the scanf for your char (string name) that command will be skipped and you can't enter value for it... but if you put that space in front of % will be ok everything and not skip nothing.

Assign result of dynamic sql to variable

Most of these answers use sp_executesql as the solution to this problem. I have found that there are some limitations when using sp_executesql, which I will not go into, but I wanted to offer an alternative using EXEC(). I am using SQL Server 2008 and I know that some of the objects I am using in this script are not available in earlier versions of SQL Server so be wary.

DECLARE @CountResults TABLE (CountReturned INT)
DECLARE 
    @SqlStatement VARCHAR(8000) = 'SELECT COUNT(*) FROM table'
    , @Count INT

INSERT @CountResults
EXEC(@SqlStatement)

SET @Count = (SELECT CountReturned FROM @CountResults)
SELECT @Count

How to define static property in TypeScript interface

@duncan's solution above specifying new() for the static type works also with interfaces:

interface MyType {
    instanceMethod();
}

interface MyTypeStatic {
    new():MyType;
    staticMethod();
}

Instagram how to get my user id from username?

Working solution ~2018

I've found that, providing you have an access token, you can perform the following request in your browser:

https://api.instagram.com/v1/users/self?access_token=[VALUE]

In fact, access token contain the User ID (the first segment of the token):

<user-id>.1677aaa.aaa042540a2345d29d11110545e2499

You can get an access token by using this tool provided by Pixel Union.

The difference between "require(x)" and "import x"

I will make it simple,

  • Import and Export are ES6 features(Next gen JS).
  • Require is old school method of importing code from other files

Major difference is in require, entire JS file is called or imported. Even if you don't need some part of it.

var myObject = require('./otherFile.js'); //This JS file will be imported fully.

Whereas in import you can extract only objects/functions/variables which are required.

import { getDate }from './utils.js'; 
//Here I am only pulling getDate method from the file instead of importing full file

Another major difference is you can use require anywhere in the program where as import should always be at the top of file

adding directory to sys.path /PYTHONPATH

When running a Python script from Powershell under Windows, this should work:

$pathToSourceRoot = "C:/Users/Steve/YourCode"
$env:PYTHONPATH = "$($pathToSourceRoot);$($pathToSourceRoot)/subdirs_if_required"

# Now run the actual script
python your_script.py

How to upgrade docker-compose to latest version

First, remove the old version:

If installed via apt-get

sudo apt-get remove docker-compose

If installed via curl

sudo rm /usr/local/bin/docker-compose

If installed via pip

pip uninstall docker-compose

Then find the newest version on the release page at GitHub or by curling the API if you have jq installed (thanks to dragon788 and frbl for this improvement):

VERSION=$(curl --silent https://api.github.com/repos/docker/compose/releases/latest | jq .name -r)

Finally, download to your favorite $PATH-accessible location and set permissions:

DESTINATION=/usr/local/bin/docker-compose
sudo curl -L https://github.com/docker/compose/releases/download/${VERSION}/docker-compose-$(uname -s)-$(uname -m) -o $DESTINATION
sudo chmod 755 $DESTINATION

Simple PHP Pagination script

 <?php
// Custom PHP MySQL Pagination Tutorial and Script
// You have to put your mysql connection data and alter the SQL queries(both queries)

mysql_connect("DATABASE_Host_Here","DATABASE_Username_Here","DATABASE_Password_Here") or die (mysql_error());
mysql_select_db("DATABASE_Name_Here") or die (mysql_error());
//////////////  QUERY THE MEMBER DATA INITIALLY LIKE YOU NORMALLY WOULD
$sql = mysql_query("SELECT id, firstname, country FROM myTable ORDER BY id ASC");
//////////////////////////////////// Pagination Logic ////////////////////////////////////////////////////////////////////////
$nr = mysql_num_rows($sql); // Get total of Num rows from the database query
if (isset($_GET['pn'])) { // Get pn from URL vars if it is present
    $pn = preg_replace('#[^0-9]#i', '', $_GET['pn']); // filter everything but numbers for security(new)
    //$pn = ereg_replace("[^0-9]", "", $_GET['pn']); // filter everything but numbers for security(deprecated)
} else { // If the pn URL variable is not present force it to be value of page number 1
    $pn = 1;
}
//This is where we set how many database items to show on each page
$itemsPerPage = 10;
// Get the value of the last page in the pagination result set
$lastPage = ceil($nr / $itemsPerPage);
// Be sure URL variable $pn(page number) is no lower than page 1 and no higher than $lastpage
if ($pn < 1) { // If it is less than 1
    $pn = 1; // force if to be 1
} else if ($pn > $lastPage) { // if it is greater than $lastpage
    $pn = $lastPage; // force it to be $lastpage's value
}
// This creates the numbers to click in between the next and back buttons
// This section is explained well in the video that accompanies this script
$centerPages = "";
$sub1 = $pn - 1;
$sub2 = $pn - 2;
$add1 = $pn + 1;
$add2 = $pn + 2;
if ($pn == 1) {
    $centerPages .= '&nbsp; <span class="pagNumActive">' . $pn . '</span> &nbsp;';
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> &nbsp;';
} else if ($pn == $lastPage) {
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> &nbsp;';
    $centerPages .= '&nbsp; <span class="pagNumActive">' . $pn . '</span> &nbsp;';
} else if ($pn > 2 && $pn < ($lastPage - 1)) {
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub2 . '">' . $sub2 . '</a> &nbsp;';
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> &nbsp;';
    $centerPages .= '&nbsp; <span class="pagNumActive">' . $pn . '</span> &nbsp;';
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> &nbsp;';
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add2 . '">' . $add2 . '</a> &nbsp;';
} else if ($pn > 1 && $pn < $lastPage) {
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> &nbsp;';
    $centerPages .= '&nbsp; <span class="pagNumActive">' . $pn . '</span> &nbsp;';
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> &nbsp;';
}
// This line sets the "LIMIT" range... the 2 values we place to choose a range of rows from database in our query
$limit = 'LIMIT ' .($pn - 1) * $itemsPerPage .',' .$itemsPerPage;
// Now we are going to run the same query as above but this time add $limit onto the end of the SQL syntax
// $sql2 is what we will use to fuel our while loop statement below
$sql2 = mysql_query("SELECT id, firstname, country FROM myTable ORDER BY id ASC $limit");
//////////////////////////////// END Pagination Logic ////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////// Pagination Display Setup /////////////////////////////////////////////////////////////////////
$paginationDisplay = ""; // Initialize the pagination output variable
// This code runs only if the last page variable is ot equal to 1, if it is only 1 page we require no paginated links to display
if ($lastPage != "1"){
    // This shows the user what page they are on, and the total number of pages
    $paginationDisplay .= 'Page <strong>' . $pn . '</strong> of ' . $lastPage. '&nbsp;  &nbsp;  &nbsp; ';
    // If we are not on page 1 we can place the Back button
    if ($pn != 1) {
        $previous = $pn - 1;
        $paginationDisplay .=  '&nbsp;  <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $previous . '"> Back</a> ';
    }
    // Lay in the clickable numbers display here between the Back and Next links
    $paginationDisplay .= '<span class="paginationNumbers">' . $centerPages . '</span>';
    // If we are not on the very last page we can place the Next button
    if ($pn != $lastPage) {
        $nextPage = $pn + 1;
        $paginationDisplay .=  '&nbsp;  <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $nextPage . '"> Next</a> ';
    }
}
///////////////////////////////////// END Pagination Display Setup ///////////////////////////////////////////////////////////////////////////
// Build the Output Section Here
$outputList = '';
while($row = mysql_fetch_array($sql2)){

    $id = $row["id"];
    $firstname = $row["firstname"];
    $country = $row["country"];

    $outputList .= '<h1>' . $firstname . '</h1><h2>' . $country . ' </h2><hr />';

} // close while loop
?>
<html>
<head>
<title>Simple Pagination</title>
</head>
<body>
   <div style="margin-left:64px; margin-right:64px;">
     <h2>Total Items: <?php echo $nr; ?></h2>
   </div>
      <div style="margin-left:58px; margin-right:58px; padding:6px; background-color:#FFF; border:#999 1px solid;"><?php echo $paginationDisplay; ?></div>
      <div style="margin-left:64px; margin-right:64px;"><?php print "$outputList"; ?></div>
      <div style="margin-left:58px; margin-right:58px; padding:6px; background-color:#FFF; border:#999 1px solid;"><?php echo $paginationDisplay; ?></div>
</body>
</html> 

How can I have linebreaks in my long LaTeX equations?

This worked for me while using mathtools package.

\documentclass{article}
\usepackage{mathtools}
\begin{document}
    \begin{equation}
        \begin{multlined}
            first term \\
            second term                 
        \end{multlined}
    \end{equation}
\end{document}

How do I remove a library from the arduino environment?

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

"File -> Preferences"

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

WHERE clause on SQL Server "Text" data type

You can use LIKE instead of =. Without any wildcards this will have the same effect.

DECLARE @Village TABLE
        (CastleType TEXT)

INSERT INTO @Village
VALUES
  (
    'foo'
  )

SELECT *
FROM   @Village
WHERE  [CastleType] LIKE 'foo' 

text is deprecated. Changing to varchar(max) will be easier to work with.

Also how large is the data likely to be? If you are going to be doing equality comparisons you will ideally want to index this column. This isn't possible if you declare the column as anything wider than 900 bytes though you can add a computed checksum or hash column that can be used to speed this type of query up.

How to send a POST request in Go?

I know this is old but this answer came up in search results. For the next guy - the proposed and accepted answer works, however the code initially submitted in the question is lower-level than it needs to be. Nobody got time for that.

//one-line post request/response...
response, err := http.PostForm(APIURL, url.Values{
    "ln": {c.ln},
    "ip": {c.ip},
    "ua": {c.ua}})

//okay, moving on...
if err != nil {
  //handle postform error
}

defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)

if err != nil {
  //handle read response error
}

fmt.Printf("%s\n", string(body))

https://golang.org/pkg/net/http/#pkg-overview

How to create a new text file using Python

f = open("Path/To/Your/File.txt", "w")   # 'r' for reading and 'w' for writing
f.write("Hello World from " + f.name)    # Write inside file 
f.close()                                # Close file 

# Method 2shush
with open("Path/To/Your/File.txt", "w") as f:   # Opens file and casts as f 
    f.write("Hello World form " + f.name)       # Writing
# File closed automatically

How to add a new row to datagridview programmatically

Adding a new row in a DGV with no rows with Add() raises SelectionChanged event before you can insert any data (or bind an object in Tag property).

Create a clone row from RowTemplate is safer imho:

//assuming that you created columns (via code or designer) in myDGV
DataGridViewRow row = (DataGridViewRow) myDGV.RowTemplate.Clone();
row.CreateCells(myDGV, "cell1", "cell2", "cell3");

myDGV.Rows.Add(row);

How to merge a transparent png image with another image using PIL

Had a similar question and had difficulty finding an answer. The following function allows you to paste an image with a transparency parameter over another image at a specific offset.

import Image

def trans_paste(fg_img,bg_img,alpha=1.0,box=(0,0)):
    fg_img_trans = Image.new("RGBA",fg_img.size)
    fg_img_trans = Image.blend(fg_img_trans,fg_img,alpha)
    bg_img.paste(fg_img_trans,box,fg_img_trans)
    return bg_img

bg_img = Image.open("bg.png")
fg_img = Image.open("fg.png")
p = trans_paste(fg_img,bg_img,.7,(250,100))
p.show()

Quick-and-dirty way to ensure only one instance of a shell script is running at a time

I use a simple approach that handles stale lock files.

Note that some of the above solutions that store the pid, ignore the fact that the pid can wrap around. So - just checking if there is a valid process with the stored pid is not enough, especially for long running scripts.

I use noclobber to make sure only one script can open and write to the lock file at one time. Further, I store enough information to uniquely identify a process in the lockfile. I define the set of data to uniquely identify a process to be pid,ppid,lstart.

When a new script starts up, if it fails to create the lock file, it then verifies that the process that created the lock file is still around. If not, we assume the original process died an ungraceful death, and left a stale lock file. The new script then takes ownership of the lock file, and all is well the world, again.

Should work with multiple shells across multiple platforms. Fast, portable and simple.

#!/usr/bin/env sh
# Author: rouble

LOCKFILE=/var/tmp/lockfile #customize this line

trap release INT TERM EXIT

# Creates a lockfile. Sets global variable $ACQUIRED to true on success.
# 
# Returns 0 if it is successfully able to create lockfile.
acquire () {
    set -C #Shell noclobber option. If file exists, > will fail.
    UUID=`ps -eo pid,ppid,lstart $$ | tail -1`
    if (echo "$UUID" > "$LOCKFILE") 2>/dev/null; then
        ACQUIRED="TRUE"
        return 0
    else
        if [ -e $LOCKFILE ]; then 
            # We may be dealing with a stale lock file.
            # Bring out the magnifying glass. 
            CURRENT_UUID_FROM_LOCKFILE=`cat $LOCKFILE`
            CURRENT_PID_FROM_LOCKFILE=`cat $LOCKFILE | cut -f 1 -d " "`
            CURRENT_UUID_FROM_PS=`ps -eo pid,ppid,lstart $CURRENT_PID_FROM_LOCKFILE | tail -1`
            if [ "$CURRENT_UUID_FROM_LOCKFILE" == "$CURRENT_UUID_FROM_PS" ]; then 
                echo "Script already running with following identification: $CURRENT_UUID_FROM_LOCKFILE" >&2
                return 1
            else
                # The process that created this lock file died an ungraceful death. 
                # Take ownership of the lock file.
                echo "The process $CURRENT_UUID_FROM_LOCKFILE is no longer around. Taking ownership of $LOCKFILE"
                release "FORCE"
                if (echo "$UUID" > "$LOCKFILE") 2>/dev/null; then
                    ACQUIRED="TRUE"
                    return 0
                else
                    echo "Cannot write to $LOCKFILE. Error." >&2
                    return 1
                fi
            fi
        else
            echo "Do you have write permissons to $LOCKFILE ?" >&2
            return 1
        fi
    fi
}

# Removes the lock file only if this script created it ($ACQUIRED is set), 
# OR, if we are removing a stale lock file (first parameter is "FORCE") 
release () {
    #Destroy lock file. Take no prisoners.
    if [ "$ACQUIRED" ] || [ "$1" == "FORCE" ]; then
        rm -f $LOCKFILE
    fi
}

# Test code
# int main( int argc, const char* argv[] )
echo "Acquring lock."
acquire
if [ $? -eq 0 ]; then 
    echo "Acquired lock."
    read -p "Press [Enter] key to release lock..."
    release
    echo "Released lock."
else
    echo "Unable to acquire lock."
fi

How to call two methods on button's onclick method in HTML or JavaScript?

The modern event handling method:

element.addEventListener('click', startDragDrop, false);
element.addEventListener('click', spyOnUser, false);

The first argument is the event, the second is the function and the third specifies whether to allow event bubbling.

From QuirksMode:

W3C’s DOM Level 2 Event specification pays careful attention to the problems of the traditional model. It offers a simple way to register as many event handlers as you like for the same event on one element.

The key to the W3C event registration model is the method addEventListener(). You give it three arguments: the event type, the function to be executed and a boolean (true or false) that I’ll explain later on. To register our well known doSomething() function to the onclick of an element you do:

Full details here: http://www.quirksmode.org/js/events_advanced.html

Using jQuery

if you're using jQuery, there is a nice API for event handling:

$('#myElement').bind('click', function() { doStuff(); });
$('#myElement').bind('click', function() { doMoreStuff(); });
$('#myElement').bind('click', doEvenMoreStuff);

Full details here: http://api.jquery.com/category/events/

NLTK and Stopwords Fail #lookuperror

import nltk

nltk.download()

  • A GUI pops up and in that go the Corpora section, select the required corpus.
  • Verified Result

How do function pointers in C work?

Since function pointers are often typed callbacks, you might want to have a look at type safe callbacks. The same applies to entry points, etc of functions that are not callbacks.

C is quite fickle and forgiving at the same time :)

Create Elasticsearch curl query for not null and not empty("")

We are using Elasticsearch version 1.6 and I used this query from a co-worker to cover not null and not empty for a field:

{
  "query": {
    "filtered": {
      "query": {
        "match_all": {}
      },
      "filter": {
        "bool": {
          "must": [
            {
              "exists": {
                "field": "myfieldName"
              }
            },
            {
              "not": {
                "filter": {
                  "term": {
                    "myfieldName": ""
                  }
                }
              }
            }
          ]
        }
      }
    }
  }
}

SQL - Create view from multiple tables

Are you using MySQL or PostgreSQL?

You want to use JOIN syntax, not UNION. For example, using INNER JOIN:

CREATE VIEW V AS
SELECT POP.country, POP.year, POP.pop, FOOD.food, INCOME.income
FROM POP
INNER JOIN FOOD ON (POP.country=FOOD.country) AND (POP.year=FOOD.year)
INNER JOIN INCOME ON (POP.country=INCOME.country) AND (POP.year=INCOME.year)

However, this will only show results when each country and year are present in all three tables. If this is not what you want, look into left outer joins (using the same link above).

Apache and IIS side by side (both listening to port 80) on windows2003

That's not quite true. E.g. for HTTP Windows supports URL based port sharing, allowing multiple processes to use the same IP address and Port.

HTML5 Email Validation

I know you are not after the Javascript solution however there are some things such as the customized validation message that, from my experience, can only be done using JS.

Also, by using JS, you can dynamically add the validation to all input fields of type email within your site instead of having to modify every single input field.

var validations ={
    email: [/^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/, 'Please enter a valid email address']
};
$(document).ready(function(){
    // Check all the input fields of type email. This function will handle all the email addresses validations
    $("input[type=email]").change( function(){
        // Set the regular expression to validate the email 
        validation = new RegExp(validations['email'][0]);
        // validate the email value against the regular expression
        if (!validation.test(this.value)){
            // If the validation fails then we show the custom error message
            this.setCustomValidity(validations['email'][1]);
            return false;
        } else {
            // This is really important. If the validation is successful you need to reset the custom error message
            this.setCustomValidity('');
        }
    });
})

Remove certain characters from a string

UPDATE yourtable 
SET field_or_column =REPLACE ('current string','findpattern', 'replacepattern') 
WHERE 1

How to install packages offline?

For Pip 8.1.2 you can use pip download -r requ.txt to download packages to your local machine.

Creating a Facebook share button with customized url, title and image

Unfortunately, it appears that we can't post shares for individual topics or articles within a page. It appears Facebook just wants us to share entire pages (based on url only).

There's also their new share dialog, but even though they claim it can do all of what the old sharer.php could do, that doesn't appear to be true.

And here's Facebooks 'best practices' for sharing.

String.contains in Java

The obvious answer to this is "that's what the JLS says."

Thinking about why that is, consider that this behavior can be useful in certain cases. Let's say you want to check a string against a set of other strings, but the number of other strings can vary.

So you have something like this:

for(String s : myStrings) {
   check(aString.contains(s));
}

where some s's are empty strings.

If the empty string is interpreted as "no input," and if your purpose here is ensure that aString contains all the "inputs" in myStrings, then it is misleading for the empty string to return false. All strings contain it because it is nothing. To say they didn't contain it would imply that the empty string had some substance that was not captured in the string, which is false.

How do I embed a mp4 movie into my html?

You should look into Video For Everyone:

Video for Everybody is very simply a chunk of HTML code that embeds a video into a website using the HTML5 element which offers native playback in Firefox 3.5 and Safari 3 & 4 and an increasing number of other browsers.

The video is played by the browser itself. It loads quickly and doesn’t threaten to crash your browser.

In other browsers that do not support , it falls back to QuickTime.

If QuickTime is not installed, Adobe Flash is used. You can host locally or embed any Flash file, such as a YouTube video.

The only downside, is that you have to have 2/3 versions of the same video stored, but you can serve to every existing device/browser that supports video (i.e.: the iPhone).

<video width="640" height="360" poster="__POSTER__.jpg" controls="controls">
    <source src="__VIDEO__.mp4" type="video/mp4" />
    <source src="__VIDEO__.webm" type="video/webm" />
    <source src="__VIDEO__.ogv" type="video/ogg" /><!--[if gt IE 6]>
    <object width="640" height="375" classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B"><!
    [endif]--><!--[if !IE]><!-->
    <object width="640" height="375" type="video/quicktime" data="__VIDEO__.mp4"><!--<![endif]-->
    <param name="src" value="__VIDEO__.mp4" />
    <param name="autoplay" value="false" />
    <param name="showlogo" value="false" />
    <object width="640" height="380" type="application/x-shockwave-flash"
        data="__FLASH__.swf?image=__POSTER__.jpg&amp;file=__VIDEO__.mp4">
        <param name="movie" value="__FLASH__.swf?image=__POSTER__.jpg&amp;file=__VIDEO__.mp4" />
        <img src="__POSTER__.jpg" width="640" height="360" />
        <p>
            <strong>No video playback capabilities detected.</strong>
            Why not try to download the file instead?<br />
            <a href="__VIDEO__.mp4">MPEG4 / H.264 “.mp4” (Windows / Mac)</a> |
            <a href="__VIDEO__.ogv">Ogg Theora &amp; Vorbis “.ogv” (Linux)</a>
        </p>
    </object><!--[if gt IE 6]><!-->
    </object><!--<![endif]-->
</video>

There is an updated version that is a bit more readable:

<!-- "Video For Everybody" v0.4.1 by Kroc Camen of Camen Design <camendesign.com/code/video_for_everybody>
     =================================================================================================================== -->
<!-- first try HTML5 playback: if serving as XML, expand `controls` to `controls="controls"` and autoplay likewise       -->
<!-- warning: playback does not work on iPad/iPhone if you include the poster attribute! fixed in iOS4.0                 -->
<video width="640" height="360" controls preload="none">
    <!-- MP4 must be first for iPad! -->
    <source src="__VIDEO__.MP4" type="video/mp4" /><!-- WebKit video    -->
    <source src="__VIDEO__.webm" type="video/webm" /><!-- Chrome / Newest versions of Firefox and Opera -->
    <source src="__VIDEO__.OGV" type="video/ogg" /><!-- Firefox / Opera -->
    <!-- fallback to Flash: -->
    <object width="640" height="384" type="application/x-shockwave-flash" data="__FLASH__.SWF">
        <!-- Firefox uses the `data` attribute above, IE/Safari uses the param below -->
        <param name="movie" value="__FLASH__.SWF" />
        <param name="flashvars" value="image=__POSTER__.JPG&amp;file=__VIDEO__.MP4" />
        <!-- fallback image. note the title field below, put the title of the video there -->
        <img src="__VIDEO__.JPG" width="640" height="360" alt="__TITLE__"
             title="No video playback capabilities, please download the video below" />
    </object>
</video>
<!-- you *must* offer a download link as they may be able to play the file locally. customise this bit all you want -->
<p> <strong>Download Video:</strong>
    Closed Format:  <a href="__VIDEO__.MP4">"MP4"</a>
    Open Format:    <a href="__VIDEO__.OGV">"OGG"</a>
</p>

How do I copy a version of a single file from one git branch to another?

I ended up at this question on a similar search. In my case I was looking to extract a file from another branch into current working directory that was different from the file's original location. Answer:

git show TREEISH:path/to/file > path/to/local/file

Printing prime numbers from 1 through 100

Finding primes up to a 100 is especially nice and easy:

    printf("2 3 ");                        // first two primes are 2 and 3
    int m5 = 25, m7 = 49, i = 5, d = 4;
    for( ; i < 25; i += (d=6-d) )
    {
        printf("%d ", i);                  // all 6-coprimes below 5*5 are prime
    }
    for( ; i < 49; i += (d=6-d) )
    {
        if( i != m5) printf("%d ", i);
        if( m5 <= i ) m5 += 10;            // no multiples of 5 below 7*7 allowed!
    }
    for( ; i < 100; i += (d=6-d) )         // from 49 to 100,
    {
        if( i != m5 && i != m7) printf("%d ", i);
        if( m5 <= i ) m5 += 10;            //   sieve by multiples of 5,
        if( m7 <= i ) m7 += 14;            //                       and 7, too
    }

The square root of 100 is 10, and so this rendition of the sieve of Eratosthenes with the 2-3 wheel uses the multiples of just the primes above 3 that are not greater than 10 -- viz. 5 and 7 alone! -- to sieve the 6-coprimes below 100 in an incremental fashion.

Generating a random & unique 8 character string using MySQL

This function generates a Random string based on your input length and allowed characters like this:

SELECT str_rand(8, '23456789abcdefghijkmnpqrstuvwxyz');

function code:

DROP FUNCTION IF EXISTS str_rand;

DELIMITER //

CREATE FUNCTION str_rand(
    u_count INT UNSIGNED,
    v_chars TEXT
)
RETURNS TEXT
NOT DETERMINISTIC
NO SQL
SQL SECURITY INVOKER
COMMENT ''
BEGIN
    DECLARE v_retval TEXT DEFAULT '';
    DECLARE u_pos    INT UNSIGNED;
    DECLARE u        INT UNSIGNED;

    SET u = LENGTH(v_chars);
    WHILE u_count > 0
    DO
      SET u_pos = 1 + FLOOR(RAND() * u);
      SET v_retval = CONCAT(v_retval, MID(v_chars, u_pos, 1));
      SET u_count = u_count - 1;
    END WHILE;

    RETURN v_retval;
END;
//
DELIMITER ;

This code is based on shuffle string function sends by "Ross Smith II"

Print Combining Strings and Numbers

In Python 3.6

a, b=1, 2 

print ("Value of variable a is: ", a, "and Value of variable b is :", b)

print(f"Value of a is: {a}")

Remote debugging Tomcat with Eclipse

Let me share the simple way to enable the remote debugging mode in tomcat7 with eclipse (Windows).

Step 1: open bin/startup.bat file
Step 2: add the below lines for debugging with JDPA option (it should starting line of the file )

    set JPDA_ADDRESS=8000  
    set JPDA_TRANSPORT=dt_socket  

Step 3: in the same file .. go to end of the file modify this line -

    call "%EXECUTABLE%" jpda start %CMD_LINE_ARGS%  
    instead of line  
    call "%EXECUTABLE%" start %CMD_LINE_ARGS%  

step 4: then just run bin>startup.bat (so now your tomcat server ran in remote mode with port 8000).

step 5: after that lets connect your source project by eclipse IDE with remote client.

step6: In the Eclipse IDE go to "debug Configuration"

step7:click "remote java application" and on that click "New"

step8. in the "connect" tab set the parameter value

   project= your source project  
   connection Type: standard (socket attached)   
   host: localhost  
   port:8000  

step9: click apply and debug.

so finally your eclipse remote client is connected with the running tomcat server (debug mode).

Hope this approach might be help you.

Regards..

What is the use of DesiredCapabilities in Selenium WebDriver?

When you run selenium WebDriver, the WebDriver opens a remote server in your computer's local host. Now, this server, called the Selenium Server, is used to interpret your code into actions to run or "drive" the instance of a real browser known as either chromebrowser, ie broser, ff browser, etc.

So, the Selenium Server can interact with different browser properties and hence it has many "capabilities".

Now what capabilities do you desire? Consider a scenario where you are validating if files have been downloaded properly in your app but, however, you do not have a desktop automation tool. In the case where you click the download link and a desktop pop up shows up to ask where to save and/or if you want to download. Your next route to bypass that would be to suppress that pop up. How? Desired Capabilities.

There are other such examples. In summary, Selenium Server can do a lot, use Desired Capabilities to tailor it to your need.

How to add parameters to an external data query in Excel which can't be displayed graphically?

If you have Excel 2007 you can write VBA to alter the connections (i.e. the external data queries) in a workbook and update the CommandText property. If you simply add ? where you want a parameter, then next time you refresh the data it'll prompt for the values for the connections! magic. When you look at the properties of the Connection the Parameters button will now be active and useable as normal.

E.g. I'd write a macro, step through it in the debugger, and make it set the CommandText appropriately. Once you've done this you can remove the macro - it's just a means to update the query.

Sub UpdateQuery
    Dim cn As WorkbookConnection
    Dim odbcCn As ODBCConnection, oledbCn As OLEDBConnection
    For Each cn In ThisWorkbook.Connections
        If cn.Type = xlConnectionTypeODBC Then
            Set odbcCn = cn.ODBCConnection

            ' If you do have multiple connections you would want to modify  
            ' the line below each time you run through the loop.
            odbcCn.CommandText = "select blah from someTable where blah like ?"

        ElseIf cn.Type = xlConnectionTypeOLEDB Then
            Set oledbCn = cn.OLEDBConnection
            oledbCn.CommandText = "select blah from someTable where blah like ?" 
        End If
    Next
End Sub

Evaluating a mathematical expression in a string

I think I would use eval(), but would first check to make sure the string is a valid mathematical expression, as opposed to something malicious. You could use a regex for the validation.

eval() also takes additional arguments which you can use to restrict the namespace it operates in for greater security.

How many bits or bytes are there in a character?

It depends what is the character and what encoding it is in:

  • An ASCII character in 8-bit ASCII encoding is 8 bits (1 byte), though it can fit in 7 bits.

  • An ISO-8895-1 character in ISO-8859-1 encoding is 8 bits (1 byte).

  • A Unicode character in UTF-8 encoding is between 8 bits (1 byte) and 32 bits (4 bytes).

  • A Unicode character in UTF-16 encoding is between 16 (2 bytes) and 32 bits (4 bytes), though most of the common characters take 16 bits. This is the encoding used by Windows internally.

  • A Unicode character in UTF-32 encoding is always 32 bits (4 bytes).

  • An ASCII character in UTF-8 is 8 bits (1 byte), and in UTF-16 - 16 bits.

  • The additional (non-ASCII) characters in ISO-8895-1 (0xA0-0xFF) would take 16 bits in UTF-8 and UTF-16.

That would mean that there are between 0.03125 and 0.125 characters in a bit.

How to open a second activity on click of button in android app

just follow this step (i am not writing code just Bcoz you may do copy and paste and cant learn)..

  1. first at all you need to declare a button which you have in layout

  2. Give reference to that button by finding its id (using findviewById) in oncreate

  3. setlistener for button (like setonclick listener)

  4. last handle the click event (means start new activity by using intent as you know already)

  5. Dont forget to add activity in manifest file

BTW this is just simple i would like to suggest you that just start from simple tutorials available on net will be better for you..

Best luck for Android

how to query for a list<String> in jdbctemplate

You can't use placeholders for column names, table names, data type names, or basically anything that isn't data.

Rendering JSON in controller

What exactly do you want to know? ActiveRecord has methods that serialize records into JSON. For instance, open up your rails console and enter ModelName.all.to_json and you will see JSON output. render :json essentially calls to_json and returns the result to the browser with the correct headers. This is useful for AJAX calls in JavaScript where you want to return JavaScript objects to use. Additionally, you can use the callback option to specify the name of the callback you would like to call via JSONP.

For instance, lets say we have a User model that looks like this: {name: 'Max', email:' [email protected]'}

We also have a controller that looks like this:

class UsersController < ApplicationController
    def show
        @user = User.find(params[:id])
        render json: @user
    end
end

Now, if we do an AJAX call using jQuery like this:

$.ajax({
    type: "GET",
    url: "/users/5",
    dataType: "json",
    success: function(data){
        alert(data.name) // Will alert Max
    }        
});

As you can see, we managed to get the User with id 5 from our rails app and use it in our JavaScript code because it was returned as a JSON object. The callback option just calls a JavaScript function of the named passed with the JSON object as the first and only argument.

To give an example of the callback option, take a look at the following:

class UsersController < ApplicationController
    def show
        @user = User.find(params[:id])
        render json: @user, callback: "testFunction"
    end
end

Now we can crate a JSONP request as follows:

function testFunction(data) {
    alert(data.name); // Will alert Max
};

var script = document.createElement("script");
script.src = "/users/5";

document.getElementsByTagName("head")[0].appendChild(script);

The motivation for using such a callback is typically to circumvent the browser protections that limit cross origin resource sharing (CORS). JSONP isn't used that much anymore, however, because other techniques exist for circumventing CORS that are safer and easier.

How to remove the querystring and get only the url?

You can use the parse_url build in function like that:

$baseUrl = $_SERVER['SERVER_NAME'] . parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

Angular.js: How does $eval work and why is it different from vanilla eval?

From the test,

it('should allow passing locals to the expression', inject(function($rootScope) {
  expect($rootScope.$eval('a+1', {a: 2})).toBe(3);

  $rootScope.$eval(function(scope, locals) {
    scope.c = locals.b + 4;
  }, {b: 3});
  expect($rootScope.c).toBe(7);
}));

We also can pass locals for evaluation expression.

Get difference between two dates in months using Java

You can use Joda time library for Java. It would be much easier to calculate time-diff between dates with it.

Sample snippet for time-diff:

Days d = Days.daysBetween(startDate, endDate);
int days = d.getDays();

Insert a new row into DataTable

You can do this, I am using

DataTable 1.10.5

using this code:

var versionNo = $.fn.dataTable.version;
alert(versionNo);

This is how I insert new record on my DataTable using row.add (My table has 10 columns), which can also includes HTML tag elements:

function fncInsertNew() {
            var table = $('#tblRecord').DataTable();

            table.row.add([
                    "Tiger Nixon",
                    "System Architect",
                    "$3,120",
                    "2011/04/25",
                    "Edinburgh",
                    "5421",
                    "Tiger Nixon",
                    "System Architect",
                    "$3,120",
                    "<p>Hello</p>"
            ]).draw();
        }

For multiple inserts at the same time, use rows.add instead:

var table = $('#tblRecord').DataTable();

table.rows.add( [ {
        "Tiger Nixon",
        "System Architect",
        "$3,120",
        "2011/04/25",
        "Edinburgh",
        "5421"
    }, {
        "Garrett Winters",
        "Director",
        "$5,300",
        "2011/07/25",
        "Edinburgh",
        "8422"
    }]).draw();

how to draw directed graphs using networkx in python?

You need to use a directed graph instead of a graph, i.e.

G = nx.DiGraph()

Then, create a list of the edge colors you want to use and pass those to nx.draw (as shown by @Marius).

Putting this all together, I get the image below. Still not quite the other picture you show (I don't know where your edge weights are coming from), but much closer! If you want more control of how your output graph looks (e.g. get arrowheads that look like arrows), I'd check out NetworkX with Graphviz.

enter image description here

Forcing to download a file using PHP

Or you can do this using HTML5. Simply with

<a href="example.csv" download>download not open it</a>

Drawing Isometric game worlds

Coobird's answer is the correct, complete one. However, I combined his hints with those from another site to create code that works in my app (iOS/Objective-C), which I wanted to share with anyone who comes here looking for such a thing. Please, if you like/up-vote this answer, do the same for the originals; all I did was "stand on the shoulders of giants."

As for sort-order, my technique is a modified painter's algorithm: each object has (a) an altitude of the base (I call "level") and (b) an X/Y for the "base" or "foot" of the image (examples: avatar's base is at his feet; tree's base is at it's roots; airplane's base is center-image, etc.) Then I just sort lowest to highest level, then lowest (highest on-screen) to highest base-Y, then lowest (left-most) to highest base-X. This renders the tiles the way one would expect.

Code to convert screen (point) to tile (cell) and back:

typedef struct ASIntCell {  // like CGPoint, but with int-s vice float-s
    int x;
    int y;
} ASIntCell;

// Cell-math helper here:
//      http://gamedevelopment.tutsplus.com/tutorials/creating-isometric-worlds-a-primer-for-game-developers--gamedev-6511
// Although we had to rotate the coordinates because...
// X increases NE (not SE)
// Y increases SE (not SW)
+ (ASIntCell) cellForPoint: (CGPoint) point
{
    const float halfHeight = rfcRowHeight / 2.;

    ASIntCell cell;
    cell.x = ((point.x / rfcColWidth) - ((point.y - halfHeight) / rfcRowHeight));
    cell.y = ((point.x / rfcColWidth) + ((point.y + halfHeight) / rfcRowHeight));

    return cell;
}


// Cell-math helper here:
//      http://stackoverflow.com/questions/892811/drawing-isometric-game-worlds/893063
// X increases NE,
// Y increases SE
+ (CGPoint) centerForCell: (ASIntCell) cell
{
    CGPoint result;

    result.x = (cell.x * rfcColWidth  / 2) + (cell.y * rfcColWidth  / 2);
    result.y = (cell.y * rfcRowHeight / 2) - (cell.x * rfcRowHeight / 2);

    return result;
}

Group By Multiple Columns

Though this question is asking about group by class properties, if you want to group by multiple columns against a ADO object (like a DataTable), you have to assign your "new" items to variables:

EnumerableRowCollection<DataRow> ClientProfiles = CurrentProfiles.AsEnumerable()
                        .Where(x => CheckProfileTypes.Contains(x.Field<object>(ProfileTypeField).ToString()));
// do other stuff, then check for dups...
                    var Dups = ClientProfiles.AsParallel()
                        .GroupBy(x => new { InterfaceID = x.Field<object>(InterfaceField).ToString(), ProfileType = x.Field<object>(ProfileTypeField).ToString() })
                        .Where(z => z.Count() > 1)
                        .Select(z => z);

Jupyter notebook not running code. Stuck on In [*]

From my experience, it usually means one of the prior cells is keeping the kernel busy. When you hit run on the intended cell and [*] appears, from there, try to scroll up to the prior cell which is also advertising a [*]. Then goto kernel->interrupt, and lastly, try running the cell again.

How to run a PowerShell script

If your script is named with the .ps1 extension and you're in a PowerShell window, you just run ./myscript.ps1 (assuming the file is in your working directory).

This is true for me anyway on Windows 10 with PowerShell version 5.1 anyway, and I don't think I've done anything to make it possible.

How can I reset or revert a file to a specific revision?

In order to go to a previous commit version of the file, get the commit number, say eb917a1 then

git checkout eb917a1 YourFileName

If you just need to go back to the last commited version

git reset HEAD YourFileName
git checkout YourFileName

This will simply take you to the last committed state of the file

What are the "standard unambiguous date" formats for string-to-date conversion in R?

Converting the date without specifying the current format can bring this error to you easily.

Here is an example:

sdate <- "2015.10.10"

Convert without specifying the Format:

date <- as.Date(sdate4) # ==> This will generate the same error"""Error in charToDate(x): character string is not in a standard unambiguous format""".

Convert with specified Format:

date <- as.Date(sdate4, format = "%Y.%m.%d") # ==> Error Free Date Conversion.

How can I add a help method to a shell script?

For a quick single option solution, use if

If you only have a single option to check and it will always be the first option ($1) then the simplest solution is an if with a test ([). For example:

if [ "$1" == "-h" ] ; then
    echo "Usage: `basename $0` [-h]"
    exit 0
fi

Note that for posix compatibility = will work as well as ==.

Why quote $1?

The reason the $1 needs to be enclosed in quotes is that if there is no $1 then the shell will try to run if [ == "-h" ] and fail because == has only been given a single argument when it was expecting two:

$ [ == "-h" ]
bash: [: ==: unary operator expected

For anything more complex use getopt or getopts

As suggested by others, if you have more than a single simple option, or need your option to accept an argument, then you should definitely go for the extra complexity of using getopts.

As a quick reference, I like The 60 second getopts tutorial.

You may also want to consider the getopt program instead of the built in shell getopts. It allows the use of long options, and options after non option arguments (e.g. foo a b c --verbose rather than just foo -v a b c). This Stackoverflow answer explains how to use GNU getopt.

jeffbyrnes mentioned that the original link died but thankfully the way back machine had archived it.

'^M' character at end of lines

The easiest way is to use vi. I know that sounds terrible but its simple and already installed on most UNIX environments. The ^M is a new line from Windows/DOS environment.

from the command prompt: $ vi filename

Then press ":" to get to command mode.

Search and Replace all Globally is :%s/^M//g "Press and hold control then press V then M" which will replace ^M with nothing.

Then to write and quit enter ":wq" Done!

How to reverse a singly linked list using only two pointers?

To swap two variables without the use of a temporary variable,

a = a xor b
b = a xor b
a = a xor b

fastest way is to write it in one line

a = a ^ b ^ (b=a)

Similarly,

using two swaps

swap(a,b)
swap(b,c)

solution using xor

a = a^b^c
b = a^b^c
c = a^b^c
a = a^b^c

solution in one line

c = a ^ b ^ c ^ (a=b) ^ (b=c)
b = a ^ b ^ c ^ (c=a) ^ (a=b)
a = a ^ b ^ c ^ (b=c) ^ (c=a)

The same logic is used to reverse a linked list.

typedef struct List
{
 int info;
 struct List *next;
}List;


List* reverseList(List *head)
{
 p=head;
 q=p->next;
 p->next=NULL;
 while(q)
 {
    q = (List*) ((int)p ^ (int)q ^ (int)q->next ^ (int)(q->next=p) ^ (int)(p=q));
 }
 head = p;
 return head;
}  

Good examples using java.util.logging

Should declare logger like this:

private final static Logger LOGGER = Logger.getLogger(MyClass.class.getName());

so if you refactor your class name it follows.

I wrote an article about java logger with examples here.

Safely turning a JSON string into an object

I'm not sure about other ways to do it but here's how you do it in Prototype (JSON tutorial).

new Ajax.Request('/some_url', {
  method:'get',
  requestHeaders: {Accept: 'application/json'},
  onSuccess: function(transport){
    var json = transport.responseText.evalJSON(true);
  }
});

Calling evalJSON() with true as the argument sanitizes the incoming string.

Linux c++ error: undefined reference to 'dlopen'

I was using CMake to compile my project and I've found the same problem.

The solution described here works like a charm, simply add ${CMAKE_DL_LIBS} to the target_link_libraries() call

Redirect from a view to another view

That's not how ASP.NET MVC is supposed to be used. You do not redirect from views. You redirect from the corresponding controller action:

public ActionResult SomeAction()
{
    ...
    return RedirectToAction("SomeAction", "SomeController");
}

Now since I see that in your example you are attempting to redirect to the LogOn action, you don't really need to do this redirect manually, but simply decorate the controller action that requires authentication with the [Authorize] attribute:

[Authorize]
public ActionResult SomeProtectedAction()
{
    ...
}

Now when some anonymous user attempts to access this controller action, the Forms Authentication module will automatically intercept the request much before it hits the action and redirect the user to the LogOn action that you have specified in your web.config (loginUrl).

How to send a simple string between two programs using pipes?

dup2( STDIN_FILENO, newfd )

And read:

char reading[ 1025 ];
int fdin = 0, r_control;
if( dup2( STDIN_FILENO, fdin ) < 0 ){
    perror( "dup2(  )" );
    exit( errno );
}
memset( reading, '\0', 1025 );
while( ( r_control = read( fdin, reading, 1024 ) ) > 0 ){
    printf( "<%s>", reading );
    memset( reading, '\0', 1025 );
}
if( r_control < 0 )
    perror( "read(  )" );    
close( fdin );    

But, I think that fcntl can be a better solution

echo "salut" | code

Getting data from Yahoo Finance

Since Yahoo Finances API was disabled, I found Alpha Vantage API

This a stock query sample that I'm using with Excel's Power Query:

https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=15min&outputsize=full&apikey=demo

Duplicate symbols for architecture x86_64 under Xcode

I also have this fault today.That's because I defined a const value in a .m file.But I defined another .m file that also included this const value.That's means it has two same const values.So this error appears. And my solution is adding a keyword "static" before the const value.such as:

static CGFloat const btnConunt = 9;

And then I build the project it won't report this error.

How do I increase modal width in Angular UI Bootstrap?

When we open a modal it accept size as a paramenter:

Possible values for it size: sm, md, lg

$scope.openModal = function (size) {
var modal = $modal.open({
      size: size,
      templateUrl: "/app/user/welcome.html",
      ...... 
      });
}

HTML:

<button type="button" 
    class="btn btn-default" 
    ng-click="openModal('sm')">Small Modal</button>

<button type="button" 
    class="btn btn-default" 
    ng-click="openModal('md')">Medium Modal</button>

<button type="button" 
    class="btn btn-default" 
    ng-click="openModal('lg')">Large Modal</button>

If you want any specific size, add style on model HTML:

<style>.modal-dialog {width: 500px;} </style>

Importing from a relative path in Python

EDIT Nov 2014 (3 years later):

Python 2.6 and 3.x supports proper relative imports, where you can avoid doing anything hacky. With this method, you know you are getting a relative import rather than an absolute import. The '..' means, go to the directory above me:

from ..Common import Common

As a caveat, this will only work if you run your python as a module, from outside of the package. For example:

python -m Proj

Original hacky way

This method is still commonly used in some situations, where you aren't actually ever 'installing' your package. For example, it's popular with Django users.

You can add Common/ to your sys.path (the list of paths python looks at to import things):

import sys, os
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'Common'))
import Common

os.path.dirname(__file__) just gives you the directory that your current python file is in, and then we navigate to 'Common/' the directory and import 'Common' the module.

How to write :hover condition for a:before and a:after?

Try to use .card-listing:hover::after hover and after using :: it wil work

Why is the <center> tag deprecated in HTML?

HTML is intended for structuring data, not controlling layout. CSS is intended to control layout. You'll also find that many designers frown on using <table> for layouts for this very same reason.

How to put a jar in classpath in Eclipse?

Right click your project in eclipse, build path -> add external jars.

How do I access call log for android?

If we use Kotlin it is shorter. Example of class which responds for provide call logs:

import android.content.Context
import android.database.Cursor
import android.provider.CallLog.Calls.*

class CallsLoader {

    fun getCallLogs(context: Context): List<List<String?>> {
        val c = context.applicationContext
        val projection = arrayOf(CACHED_NAME, NUMBER, TYPE, DATE, DURATION)

        val cursor = c.contentResolver.query(
             CONTENT_URI,
             projection,
             null,
             null,
             null,
             null
          )

         return cursorToMatrix(cursor)
     }

    private fun cursorToMatrix(cursor: Cursor?): List<List<String?>> {
        val matrix = mutableListOf<List<String?>>()
        cursor?.use {
             while (it.moveToNext()) {
                 val list = listOf(
                    it.getStringFromColumn(CACHED_NAME),
                    it.getStringFromColumn(NUMBER),
                    it.getStringFromColumn(TYPE),
                    it.getStringFromColumn(DATE),
                    it.getStringFromColumn(DURATION)
                 )

                 matrix.add(list.toList())
             }
          }

          return matrix
      }

     private fun Cursor.getStringFromColumn(columnName: String) =
        getString(getColumnIndex(columnName))
}

We can also convert cursor to map:

fun getCallLogs(context: Context): Map<String, Array<String?>> {
    val c = context.applicationContext
    val projection = arrayOf(CACHED_NAME, NUMBER, TYPE, DATE, DURATION)

    val cursor = c.contentResolver.query(
        CONTENT_URI,
        projection,
        null,
        null,
        null,
        null
    )

    return cursorToMap(cursor)
}

private fun cursorToMap(cursor: Cursor?): Map<String, Array<String?>> {
    val arraySize = cursor?.count ?: 0
    val map = mapOf(
        CACHED_NAME to Array<String?>(arraySize) { "" },
        NUMBER to Array<String?>(arraySize) { "" },
        TYPE to Array<String?>(arraySize) { "" },
        DATE to Array<String?>(arraySize) { "" },
        DURATION to Array<String?>(arraySize) { "" }
    )

    cursor?.use {
        for (i in 0 until arraySize) {
            it.moveToNext()

            map[CACHED_NAME]?.set(i, it.getStringFromColumn(CACHED_NAME))
            map[NUMBER]?.set(i, it.getStringFromColumn(NUMBER))
            map[TYPE]?.set(i, it.getStringFromColumn(TYPE))
            map[DATE]?.set(i, it.getStringFromColumn(DATE))
            map[DURATION]?.set(i, it.getStringFromColumn(DURATION))
        }
    }

    return map
}

How To Create Table with Identity Column

Unique key allows max 2 NULL values. Explaination:

create table teppp
(
id int identity(1,1) primary key,
name varchar(10 )unique,
addresss varchar(10)
)

insert into teppp ( name,addresss) values ('','address1')
insert into teppp ( name,addresss) values ('NULL','address2')
insert into teppp ( addresss) values ('address3')

select * from teppp
null string , address1
NULL,address2
NULL,address3

If you try inserting same values as below:

insert into teppp ( name,addresss) values ('','address4')
insert into teppp ( name,addresss) values ('NULL','address5')
insert into teppp ( addresss) values ('address6')

Every time you will get error like:

Violation of UNIQUE KEY constraint 'UQ__teppp__72E12F1B2E1BDC42'. Cannot insert duplicate key in object 'dbo.teppp'.
The statement has been terminated.

How to do the Recursive SELECT query in MySQL?

If you want to be able to have a SELECT without problems of the parent id having to be lower than child id, a function could be used. It supports also multiple children (as a tree should do) and the tree can have multiple heads. It also ensure to break if a loop exists in the data.

I wanted to use dynamic SQL to be able to pass the table/columns names, but functions in MySQL don't support this.

DELIMITER $$

CREATE FUNCTION `isSubElement`(pParentId INT, pId INT) RETURNS int(11)
DETERMINISTIC    
READS SQL DATA
BEGIN
DECLARE isChild,curId,curParent,lastParent int;
SET isChild = 0;
SET curId = pId;
SET curParent = -1;
SET lastParent = -2;

WHILE lastParent <> curParent AND curParent <> 0 AND curId <> -1 AND curParent <> pId AND isChild = 0 DO
    SET lastParent = curParent;
    SELECT ParentId from `test` where id=curId limit 1 into curParent;

    IF curParent = pParentId THEN
        SET isChild = 1;
    END IF;
    SET curId = curParent;
END WHILE;

RETURN isChild;
END$$

Here, the table test has to be modified to the real table name and the columns (ParentId,Id) may have to be adjusted for your real names.

Usage :

SET @wantedSubTreeId = 3;
SELECT * FROM test WHERE isSubElement(@wantedSubTreeId,id) = 1 OR ID = @wantedSubTreeId;

Result :

3   7   k
5   3   d
9   3   f
1   5   a

SQL for test creation :

CREATE TABLE IF NOT EXISTS `test` (
  `Id` int(11) NOT NULL,
  `ParentId` int(11) DEFAULT NULL,
  `Name` varchar(300) NOT NULL,
  PRIMARY KEY (`Id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1;

insert into test (id, parentid, name) values(3,7,'k');
insert into test (id, parentid, name) values(5,3,'d');
insert into test (id, parentid, name) values(9,3,'f');
insert into test (id, parentid, name) values(1,5,'a');
insert into test (id, parentid, name) values(6,2,'o');
insert into test (id, parentid, name) values(2,8,'c');

EDIT : Here is a fiddle to test it yourself. It forced me to change the delimiter using the predefined one, but it works.

Placing Unicode character in CSS content value

Why don't you just save/serve the CSS file as UTF-8?

nav a:hover:after {
    content: "?";
}

If that's not good enough, and you want to keep it all-ASCII:

nav a:hover:after {
    content: "\2193";
}

The general format for a Unicode character inside a string is \000000 to \FFFFFF – a backslash followed by six hexadecimal digits. You can leave out leading 0 digits when the Unicode character is the last character in the string or when you add a space after the Unicode character. See the spec below for full details.


Relevant part of the CSS2 spec:

Third, backslash escapes allow authors to refer to characters they cannot easily put in a document. In this case, the backslash is followed by at most six hexadecimal digits (0..9A..F), which stand for the ISO 10646 ([ISO10646]) character with that number, which must not be zero. (It is undefined in CSS 2.1 what happens if a style sheet does contain a character with Unicode codepoint zero.) If a character in the range [0-9a-fA-F] follows the hexadecimal number, the end of the number needs to be made clear. There are two ways to do that:

  1. with a space (or other white space character): "\26 B" ("&B"). In this case, user agents should treat a "CR/LF" pair (U+000D/U+000A) as a single white space character.
  2. by providing exactly 6 hexadecimal digits: "\000026B" ("&B")

In fact, these two methods may be combined. Only one white space character is ignored after a hexadecimal escape. Note that this means that a "real" space after the escape sequence must be doubled.

If the number is outside the range allowed by Unicode (e.g., "\110000" is above the maximum 10FFFF allowed in current Unicode), the UA may replace the escape with the "replacement character" (U+FFFD). If the character is to be displayed, the UA should show a visible symbol, such as a "missing character" glyph (cf. 15.2, point 5).

  • Note: Backslash escapes are always considered to be part of an identifier or a string (i.e., "\7B" is not punctuation, even though "{" is, and "\32" is allowed at the start of a class name, even though "2" is not).
    The identifier "te\st" is exactly the same identifier as "test".

Comprehensive list: Unicode Character 'DOWNWARDS ARROW' (U+2193).

Convert InputStream to BufferedReader

InputStream is;
InputStreamReader r = new InputStreamReader(is);
BufferedReader br = new BufferedReader(r);

How can I see function arguments in IPython Notebook Server 3?

Adding screen shots(examples) and some more context for the answer of @Thomas G.

if its not working please make sure if you have executed code properly. In this case make sure import pandas as pd is ran properly before checking below shortcut.

Place the cursor in middle of parenthesis () before you use shortcut.

shift + tab

Display short document and few params

enter image description here

shift + tab + tab

Expands document with scroll bar

enter image description here

shift + tab + tab + tab

Provides document with a Tooltip: "will linger for 10secs while you type". which means it allows you write params and waits for 10secs.

enter image description here

shift + tab + tab + tab + tab

It opens a small window in bottom with option(top righ corner of small window) to open full documentation in new browser tab.

enter image description here

How to determine whether an object has a given property in JavaScript

Why not simply:

if (typeof myObject.myProperty == "undefined") alert("myProperty is not defined!");

Or if you expect a specific type:

if (typeof myObject.myProperty != "string") alert("myProperty has wrong type or does not exist!");

javascript createElement(), style problem

yourElement.setAttribute("style", "background-color:red; font-size:2em;");

Or you could write the element as pure HTML and use .innerHTML = [raw html code]... that's very ugly though.

In answer to your first question, first you use var myElement = createElement(...);, then you do document.body.appendChild(myElement);.

Why, Fatal error: Class 'PHPUnit_Framework_TestCase' not found in ...?

For me, it was because I ran

$ phpunit .

instead of

$ phpunit

when I already had a configured phpunit.xml file in the working directory.

Bulk insert with SQLAlchemy ORM

Piere's answer is correct but one issue is that bulk_save_objects by default does not return the primary keys of the objects, if that is of concern to you. Set return_defaults to True to get this behavior.

The documentation is here.

foos = [Foo(bar='a',), Foo(bar='b'), Foo(bar='c')]
session.bulk_save_objects(foos, return_defaults=True)
for foo in foos:
    assert foo.id is not None
session.commit()

How can I pipe stderr, and not stdout?

Combining the best of these answers, if you do:

command 2> >(grep -v something 1>&2)

...then all stdout is preserved as stdout and all stderr is preserved as stderr, but you won't see any lines in stderr containing the string "something".

This has the unique advantage of not reversing or discarding stdout and stderr, nor smushing them together, nor using any temporary files.

How to add image in Flutter

their is no need to create asset directory and under it images directory and then you put image. Better is to just create Images directory inside your project where pubspec.yaml exist and put images inside it and access that images just like as shown in tutorial/documention

assets: - images/lake.jpg // inside pubspec.yaml

How can I count the occurrences of a list item?

Use Counter if you are using Python 2.7 or 3.x and you want the number of occurrences for each element:

>>> from collections import Counter
>>> z = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']
>>> Counter(z)
Counter({'blue': 3, 'red': 2, 'yellow': 1})

Identify duplicates in a List

This also works:

public static Set<Integer> findDuplicates(List<Integer> input) {
    List<Integer> copy = new ArrayList<Integer>(input);
    for (Integer value : new HashSet<Integer>(input)) {
        copy.remove(value);
    }
    return new HashSet<Integer>(copy);
}

Iterating over and deleting from Hashtable in Java

You can use Enumeration:

Hashtable<Integer, String> table = ...

Enumeration<Integer> enumKey = table.keys();
while(enumKey.hasMoreElements()) {
    Integer key = enumKey.nextElement();
    String val = table.get(key);
    if(key==0 && val.equals("0"))
        table.remove(key);
}

check if a std::vector contains a certain object?

Checking if v contains the element x:

#include <algorithm>

if(std::find(v.begin(), v.end(), x) != v.end()) {
    /* v contains x */
} else {
    /* v does not contain x */
}

Checking if v contains elements (is non-empty):

if(!v.empty()){
    /* v is non-empty */
} else {
    /* v is empty */
}

How to set cookies in laravel 5 independently inside controller

If you want to set cookie and get it outside of request, Laravel is not your friend.

Laravel cookies are part of Request, so if you want to do this outside of Request object, use good 'ole PHP setcookie(..) and $_COOKIE to get it.

Generate an integer that is not among four billion given ones

Since the problem does not specify that we have to find the smallest possible number that is not in the file we could just generate a number that is longer than the input file itself. :)

Connecting an input stream to an outputstream

You can use a circular buffer :

Code

// buffer all data in a circular buffer of infinite size
CircularByteBuffer cbb = new CircularByteBuffer(CircularByteBuffer.INFINITE_SIZE);
class1.putDataOnOutputStream(cbb.getOutputStream());
class2.processDataFromInputStream(cbb.getInputStream());


Maven dependency

<dependency>
    <groupId>org.ostermiller</groupId>
    <artifactId>utils</artifactId>
    <version>1.07.00</version>
</dependency>


Mode details

http://ostermiller.org/utils/CircularBuffer.html

cleanest way to skip a foreach if array is empty

Best practice is to define variable as an array at the very top of your code.

foreach((array)$myArr as $oneItem) { .. }

will also work but you will duplicate this (array) conversion everytime you need to loop through the array.

since it's important not to duplicate even a word of your code, you do better to define it as an empty array at top.

Java - How to find the redirected url of a url?

Simply call getUrl() on URLConnection instance after calling getInputStream():

URLConnection con = new URL( url ).openConnection();
System.out.println( "orignal url: " + con.getURL() );
con.connect();
System.out.println( "connected url: " + con.getURL() );
InputStream is = con.getInputStream();
System.out.println( "redirected url: " + con.getURL() );
is.close();

If you need to know whether the redirection happened before actually getting it's contents, here is the sample code:

HttpURLConnection con = (HttpURLConnection)(new URL( url ).openConnection());
con.setInstanceFollowRedirects( false );
con.connect();
int responseCode = con.getResponseCode();
System.out.println( responseCode );
String location = con.getHeaderField( "Location" );
System.out.println( location );

how to get the one entry from hashmap without iterating

If you really want the API you suggested, you could subclass HashMap and keep track of the keys in a List for example. Don't see the point in this really, but it gives you what you want. If you explain the intended use case, maybe we can come up with a better solution.

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SuppressWarnings("unchecked")
public class IndexedMap extends HashMap {

    private List<Object> keyIndex;

    public IndexedMap() {
        keyIndex = new ArrayList<Object>();
    }

    /**
     * Returns the key at the specified position in this Map's keyIndex.
     * 
     * @param index
     *            index of the element to return
     * @return the element at the specified position in this list
     * @throws IndexOutOfBoundsException
     *             if the index is out of range (index < 0 || index >= size())
     */
    public Object get(int index) {
        return keyIndex.get(index);
    }

    @Override
    public Object put(Object key, Object value) {

        addKeyToIndex(key);
        return super.put(key, value);
    }

    @Override
    public void putAll(Map source) {

        for (Object key : source.keySet()) {
            addKeyToIndex(key);
        }
        super.putAll(source);
    }

    private void addKeyToIndex(Object key) {

        if (!keyIndex.contains(key)) {
            keyIndex.add(key);
        }
    }

    @Override
    public Object remove(Object key) {

        keyIndex.remove(key);
        return super.remove(key);
    }
}

EDIT: I deliberately did not delve into the generics side of this...

Regular Expression: Any character that is NOT a letter or number

This regular expression matches anything that isn't a letter, digit, or an underscore (_) character.

\W

For example in JavaScript:

"(,,@,£,() asdf 345345".replace(/\W/g, ' '); // Output: "          asdf 345345"

Error: org.testng.TestNGException: Cannot find class in classpath: EmpClass

In my case I imported maven project as Default existing project in eclipse.After that I imported as maven project.That worked for me.

Using Mockito to mock classes with generic parameters

With JUnit5 I think the best way is to @ExtendWith(MockitoExtension.class) with @Mock in the method parameter or the field.

The following example demonstrates that with Hamcrest matchers.

package com.vogella.junit5;                                                                    
                                                                                               
import static org.hamcrest.MatcherAssert.assertThat;                                           
import static org.hamcrest.Matchers.hasItem;                                                   
import static org.mockito.Mockito.verify;                                                      
                                                                                               
import java.util.Arrays;                                                                       
import java.util.List;                                                                         
                                                                                               
import org.junit.jupiter.api.Test;                                                             
import org.junit.jupiter.api.extension.ExtendWith;                                             
import org.mockito.ArgumentCaptor;                                                             
import org.mockito.Captor;                                                                     
import org.mockito.Mock;                                                                       
import org.mockito.junit.jupiter.MockitoExtension;                                             
                                                                                               
@ExtendWith(MockitoExtension.class)                                                            
public class MockitoArgumentCaptureTest {                                                      
                                                                                               
                                                                                               
    @Captor                                                                                    
    private ArgumentCaptor<List<String>> captor;                                               
                                                                                               
    @Test                                                                                      
    public final void shouldContainCertainListItem(@Mock List<String> mockedList) {            
        var asList = Arrays.asList("someElement_test", "someElement");                         
        mockedList.addAll(asList);                                                             
                                                                                               
        verify(mockedList).addAll(captor.capture());                                           
        List<String> capturedArgument = captor.getValue();                                     
        assertThat(capturedArgument, hasItem("someElement"));                                  
    }                                                                                          
}                                                                                              
                                                                                              

See https://www.vogella.com/tutorials/Mockito/article.html for the required Maven/Gradle dependencies.

Greater than and less than in one statement

java is not python.

you can't do anything like this

if(0 < i < 5) or if(i in range(0,6))

you mentioned the easiest way :

int i = getFilesSize();
if(0 < i && i < 5){
    //operations

}

of

   if(0 < i){
       if(i < 5){
          //operations
       }
     }

How to fetch FetchType.LAZY associations with JPA and Hibernate in a Spring Controller

You can do the same like this:

@Override
public FaqQuestions getFaqQuestionById(Long questionId) {
    session = sessionFactory.openSession();
    tx = session.beginTransaction();
    FaqQuestions faqQuestions = null;
    try {
        faqQuestions = (FaqQuestions) session.get(FaqQuestions.class,
                questionId);
        Hibernate.initialize(faqQuestions.getFaqAnswers());

        tx.commit();
        faqQuestions.getFaqAnswers().size();
    } finally {
        session.close();
    }
    return faqQuestions;
}

Just use faqQuestions.getFaqAnswers().size()nin your controller and you will get the size if lazily intialised list, without fetching the list itself.

How can I dynamically set the position of view in Android?

For anything below Honeycomb (API Level 11) you'll have to use setLayoutParams(...).

If you can limit your support to Honeycomb and up you can use the setX(...), setY(...), setLeft(...), setTop(...), etc.

How to import data from one sheet to another

Saw this thread while looking for something else and I know it is super old, but I wanted to add my 2 cents.

NEVER USE VLOOKUP. It's one of the worst performing formulas in excel. Use index match instead. It even works without sorting data, unless you have a -1 or 1 in the end of the match formula (explained more below)

Here is a link with the appropriate formulas.

The Sheet 2 formula would be this: =IF(A2="","",INDEX(Sheet1!B:B,MATCH($A2,Sheet1!$A:$A,0)))

  • IF(A2="","", means if A2 is blank, return a blank value
  • INDEX(Sheet1!B:B, is saying INDEX B:B where B:B is the data you want to return. IE the name column.
  • Match(A2, is saying to Match A2 which is the ID you want to return the Name for.
  • Sheet1!A:A, is saying you want to match A2 to the ID column in the previous sheet
  • ,0)) is specifying you want an exact value. 0 means return an exact match to A2, -1 means return smallest value greater than or equal to A2, 1 means return the largest value that is less than or equal to A2. Keep in mind -1 and 1 have to be sorted.

More information on the Index/Match formula

Other fun facts: $ means absolute in a formula. So if you specify $B$1 when filling a formula down or over keeps that same value. If you over $B1, the B remains the same across the formula, but if you fill down, the 1 increases with the row count. Likewise, if you used B$1, filling to the right will increment the B, but keep the reference of row 1.

I also included the use of indirect in the second section. What indirect does is allow you to use the text of another cell in a formula. Since I created a named range sheet1!A:A = ID, sheet1!B:B = Name, and sheet1!C:C=Price, I can use the column name to have the exact same formula, but it uses the column heading to change the search criteria.

Good luck! Hope this helps.

Error: fix the version conflict (google-services plugin)

Initially, the firebase database was pointing to 11.8.0 .after changing all the related jars to 11.0.4 this issue is resolved at changes the SDK level.

compile 'com.google.firebase:firebase-database:11.0.4'
compile 'com.google.firebase:firebase-messaging:11.0.4'

How to change status bar color to match app in Lollipop? [Android]

To change status bar color use setStatusBarColor(int color). According the javadoc, we also need set some flags on the window.

Working snippet of code:

Window window = activity.getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.setStatusBarColor(ContextCompat.getColor(activity, R.color.example_color));


Keep in mind according Material Design guidelines status bar color and action bar color should be different:

  • ActionBar should use primary 500 color
  • StatusBar should use primary 700 color

Look at the screenshot below:

enter image description here

How do I declare a global variable in VBA?

This is a question about scope.

If you only want the variables to last the lifetime of the function, use Dim (short for Dimension) inside the function or sub to declare the variables:

Function AddSomeNumbers() As Integer
    Dim intA As Integer
    Dim intB As Integer
    intA = 2
    intB = 3
    AddSomeNumbers = intA + intB
End Function
'intA and intB are no longer available since the function ended

A global variable (as SLaks pointed out) is declared outside of the function using the Public keyword. This variable will be available during the life of your running application. In the case of Excel, this means the variables will be available as long as that particular Excel workbook is open.

Public intA As Integer
Private intB As Integer

Function AddSomeNumbers() As Integer
    intA = 2
    intB = 3
    AddSomeNumbers = intA + intB
End Function
'intA and intB are still both available.  However, because intA is public,  '
'it can also be referenced from code in other modules. Because intB is private,'
'it will be hidden from other modules.

You can also have variables that are only accessible within a particular module (or class) by declaring them with the Private keyword.

If you're building a big application and feel a need to use global variables, I would recommend creating a separate module just for your global variables. This should help you keep track of them in one place.

Failed to resolve: com.google.firebase:firebase-core:9.0.0

dependencies {
    compile 'com.google.android.gms:play-services-maps:11.8.0'
    compile 'com.google.android.gms:play-services-auth:11.8.0'
    compile 'com.google.android.gms:play-services-ads:11.8.0'
    compile 'com.google.firebase:firebase-storage:11.8.0'

}
apply plugin: 'com.google.gms.google-services'


// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {


        maven { url 'https://maven.fabric.io/public' }

        jcenter()
        google()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'
        classpath 'com.google.gms:google-services:3.1.1'


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

allprojects {
    repositories {
        jcenter()
        google()
    }
}

How to fix Ora-01427 single-row subquery returns more than one row in select?

The only subquery appears to be this - try adding a ROWNUM limit to the where to be sure:

(SELECT C.I_WORKDATE
         FROM T_COMPENSATION C
         WHERE C.I_COMPENSATEDDATE = A.I_REQDATE AND ROWNUM <= 1
         AND C.I_EMPID = A.I_EMPID)

You do need to investigate why this isn't unique, however - e.g. the employee might have had more than one C.I_COMPENSATEDDATE on the matched date.

For performance reasons, you should also see if the lookup subquery can be rearranged into an inner / left join, i.e.

 SELECT 
    ...
    REPLACE(TO_CHAR(C.I_WORKDATE, 'DD-Mon-YYYY'),
            ' ',
            '') AS WORKDATE,
    ...
 INNER JOIN T_EMPLOYEE_MS E
    ...
     LEFT OUTER JOIN T_COMPENSATION C
          ON C.I_COMPENSATEDDATE = A.I_REQDATE
          AND C.I_EMPID = A.I_EMPID
    ...

Printing Even and Odd using two Threads in Java

I have done it this way, while printing using two threads we cannot predict the sequence which thread
would get executed first so to overcome this situation we have to synchronize the shared resource,in
my case the print function which two threads are trying to access.

class Printoddeven{

    public synchronized void print(String msg) {
        try {
            if(msg.equals("Even")) {
                for(int i=0;i<=10;i+=2) {
                    System.out.println(msg+" "+i);
                    Thread.sleep(2000);
                    notify();
                    wait();
                }
            } else {
                for(int i=1;i<=10;i+=2) {
                    System.out.println(msg+" "+i);
                    Thread.sleep(2000);
                    notify();
                    wait();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

class PrintOdd extends Thread{
    Printoddeven oddeven;
    public PrintOdd(Printoddeven oddeven){
        this.oddeven=oddeven;
    }

    public void run(){
        oddeven.print("ODD");
    }
}

class PrintEven extends Thread{
    Printoddeven oddeven;
    public PrintEven(Printoddeven oddeven){
        this.oddeven=oddeven;
    }

    public void run(){
        oddeven.print("Even");
    }
}



public class mainclass 
{
    public static void main(String[] args) {
        Printoddeven obj = new Printoddeven();//only one object  
        PrintEven t1=new PrintEven(obj);  
        PrintOdd t2=new PrintOdd(obj);  
        t1.start();  
        t2.start();  
    }
}

What is the best way to determine a session variable is null or empty in C#?

The 'as' notation in c# 3.0 is very clean. Since all session variables are nullable objects, this lets you grab the value and put it into your own typed variable without worry of throwing an exception. Most objects can be handled this way.

string mySessionVar = Session["mySessionVar"] as string;

My concept is that you should pull your Session variables into local variables and then handle them appropriately. Always assume your Session variables could be null and never cast them into a non-nullable type.

If you need a non-nullable typed variable you can then use TryParse to get that.

int mySessionInt;
if (!int.TryParse(mySessionVar, out mySessionInt)){
   // handle the case where your session variable did not parse into the expected type 
   // e.g. mySessionInt = 0;
}

Fastest way to convert JavaScript NodeList to Array?

Some optimizations:

  • save the NodeList's length in a variable
  • explicitly set the new array's length before setting.
  • access the indices, rather than pushing or unshifting.

Code (jsPerf):

var arr = [];
for (var i = 0, ref = arr.length = nl.length; i < ref; i++) {
 arr[i] = nl[i];
}

What characters are valid in a URL?

All the gory details can be found in the current RFC on the topic: RFC 3986 (Uniform Resource Identifier (URI): Generic Syntax)

Based on this related answer, you are looking at a list that looks like: A-Z, a-z, 0-9, -, ., _, ~, :, /, ?, #, [, ], @, !, $, &, ', (, ), *, +, ,, ;, %, and =. Everything else must be url-encoded. Also, some of these characters can only exist in very specific spots in a URI and outside of those spots must be url-encoded (e.g. % can only be used in conjunction with url encoding as in %20), the RFC has all of these specifics.

New Intent() starts new instance with Android: launchMode="singleTop"

You can return to the same existing instance of Activity with android:launchMode="singleInstance"

in the manifest. When you return to A from B, may be needed finish() to destroy B.

Loop timer in JavaScript

It should be:

function moveItem() {
  jQuery(".stripTransmitter ul li a").trigger('click');
}
setInterval(moveItem,2000);

setInterval(f, t) calls the the argument function, f, once every t milliseconds.

Correct way to integrate jQuery plugins in AngularJS

Yes, you are correct. If you are using a jQuery plugin, do not put the code in the controller. Instead create a directive and put the code that you would normally have inside the link function of the directive.

There are a couple of points in the documentation that you could take a look at. You can find them here:
Common Pitfalls

Using controllers correctly

Ensure that when you are referencing the script in your view, you refer it last - after the angularjs library, controllers, services and filters are referenced.

EDIT: Rather than using $(element), you can make use of angular.element(element) when using AngularJS with jQuery

Angular.js directive dynamic templateURL

I have an example about this.

<!DOCTYPE html>
<html ng-app="app">

  <head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  </head>

  <body>
    <div class="container-fluid body-content" ng-controller="formView">
        <div class="row">
            <div class="col-md-12">
                <h4>Register Form</h4>
                <form class="form-horizontal" ng-submit="" name="f" novalidate>
                    <div ng-repeat="item in elements" class="form-group">
                        <label>{{item.Label}}</label>
                        <element type="{{item.Type}}" model="item"></element>
                    </div>
                    <input ng-show="f.$valid" type="submit" id="submit" value="Submit" class="" />
                </form>
            </div>
        </div>
    </div>
    <script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.min.js"></script>
    <script src="app.js"></script>
  </body>

</html>

angular.module('app', [])
    .controller('formView', function ($scope) {
        $scope.elements = [{
            "Id":1,
            "Type":"textbox",
            "FormId":24,
            "Label":"Name",
            "PlaceHolder":"Place Holder Text",
            "Max":20,
            "Required":false,
            "Options":null,
            "SelectedOption":null
          },
          {
            "Id":2,
            "Type":"textarea",
            "FormId":24,
            "Label":"AD2",
            "PlaceHolder":"Place Holder Text",
            "Max":20,
            "Required":true,
            "Options":null,
            "SelectedOption":null
        }];
    })
    .directive('element', function () {
        return {
            restrict: 'E',
            link: function (scope, element, attrs) {
                scope.contentUrl = attrs.type + '.html';
                attrs.$observe("ver", function (v) {
                    scope.contentUrl = v + '.html';
                });
            },
            template: '<div ng-include="contentUrl"></div>'
        }
    })

How do I debug error ECONNRESET in Node.js?

I solved the problem by simply connecting to a different network. That is one of the possible problems.

As discussed above, ECONNRESET means that the TCP conversation abruptly closed its end of the connection.

Your internet connection might be blocking you from connecting to some servers. In my case, I was trying to connect to mLab ( cloud database service that hosts MongoDB databases). And my ISP is blocking it.

Set custom HTML5 required field validation message

Use the attribute "title" in every input tag and write a message on it

How to create file execute mode permissions in Git on Windows?

There's no need to do this in two commits, you can add the file and mark it executable in a single commit:

C:\Temp\TestRepo>touch foo.sh

C:\Temp\TestRepo>git add foo.sh

C:\Temp\TestRepo>git ls-files --stage
100644 e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 0       foo.sh

As you note, after adding, the mode is 0644 (ie, not executable). However, we can mark it as executable before committing:

C:\Temp\TestRepo>git update-index --chmod=+x foo.sh

C:\Temp\TestRepo>git ls-files --stage
100755 e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 0       foo.sh

And now the file is mode 0755 (executable).

C:\Temp\TestRepo>git commit -m"Executable!"
[master (root-commit) 1f7a57a] Executable!
 1 file changed, 0 insertions(+), 0 deletions(-)
 create mode 100755 foo.sh

And now we have a single commit with a single executable file.

getting the difference between date in days in java

Calendar start = Calendar.getInstance();
Calendar end = Calendar.getInstance();
start.set(2010, 7, 23);
end.set(2010, 8, 26);
Date startDate = start.getTime();
Date endDate = end.getTime();
long startTime = startDate.getTime();
long endTime = endDate.getTime();
long diffTime = endTime - startTime;
long diffDays = diffTime / (1000 * 60 * 60 * 24);
DateFormat dateFormat = DateFormat.getDateInstance();
System.out.println("The difference between "+
  dateFormat.format(startDate)+" and "+
  dateFormat.format(endDate)+" is "+
  diffDays+" days.");

This will not work when crossing daylight savings time (or leap seconds) as orange80 pointed out and might as well not give the expected results when using different times of day. Using JodaTime might be easier for correct results, as the only correct way with plain Java before 8 I know is to use Calendar's add and before/after methods to check and adjust the calculation:

start.add(Calendar.DAY_OF_MONTH, (int)diffDays);
while (start.before(end)) {
    start.add(Calendar.DAY_OF_MONTH, 1);
    diffDays++;
}
while (start.after(end)) {
    start.add(Calendar.DAY_OF_MONTH, -1);
    diffDays--;
}

How can I take a screenshot/image of a website using Python?

This is an old question and most answers are a bit dated. Currently, I would do 1 of 2 things.

1. Create a program that takes the screenshots

I would use Pyppeteer to take screenshots of websites. This runs on the Puppeteer package. Puppeteer spins up a headless chrome browser, so the screenshots will look exactly like they would in a normal browser.

This is taken from the pyppeteer documentation:

import asyncio
from pyppeteer import launch

async def main():
    browser = await launch()
    page = await browser.newPage()
    await page.goto('https://example.com')
    await page.screenshot({'path': 'example.png'})
    await browser.close()

asyncio.get_event_loop().run_until_complete(main())

2. Use a screenshot API

You could also use a screenshot API such as this one. The nice thing is that you don't have to set everything up yourself but can simply call an API endpoint.

This is taken from the screenshot API's documentation:

import urllib.parse
import urllib.request
import ssl

ssl._create_default_https_context = ssl._create_unverified_context

# The parameters.
token = "YOUR_API_TOKEN"
url = urllib.parse.quote_plus("https://example.com")
width = 1920
height = 1080
output = "image"

# Create the query URL.
query = "https://screenshotapi.net/api/v1/screenshot"
query += "?token=%s&url=%s&width=%d&height=%d&output=%s" % (token, url, width, height, output)

# Call the API.
urllib.request.urlretrieve(query, "./example.png")

How to copy data to clipboard in C#

Clip.exe is an executable in Windows to set the clipboard. Note that this does not work for other operating systems other than Windows, which still sucks.

        /// <summary>
        /// Sets clipboard to value.
        /// </summary>
        /// <param name="value">String to set the clipboard to.</param>
        public static void SetClipboard(string value)
        {
            if (value == null)
                throw new ArgumentNullException("Attempt to set clipboard with null");

            Process clipboardExecutable = new Process(); 
            clipboardExecutable.StartInfo = new ProcessStartInfo // Creates the process
            {
                RedirectStandardInput = true,
                FileName = @"clip", 
            };
            clipboardExecutable.Start();

            clipboardExecutable.StandardInput.Write(value); // CLIP uses STDIN as input.
            // When we are done writing all the string, close it so clip doesn't wait and get stuck
            clipboardExecutable.StandardInput.Close(); 

            return;
        }

jQuery how to find an element based on a data-attribute value?

Going back to his original question, about how to make this work without knowing the element type in advance, the following does this:

$(ContainerNode).find(el.nodeName + "[data-slide='" + current + "']");

Does Java have a complete enum for HTTP response codes?

If you are using Netty, you can use:

Java ElasticSearch None of the configured nodes are available

This means we are not able to instantiate ES transportClient and throw this exception. There are couple of possibilities that cause this issue.

  • Cluster name is incorrect. So open ES_HOME_DIR/config/elasticserach.yml file and check the cluster name value OR use this command: curl -XGET 'http://localhost:9200/_nodes'
  • Verify port 9200 is http port but elasticsearch service is using tcp port 9300 [by default]. So verify that the port is not blocked.
  • Authentication issue: set the header in transportClient's context for authentication:

    client.threadPool().getThreadContext()
      .putHeader("Authorization", "Basic " + encodeBase64String(basicHeader.getBytes()));
    

If you are still facing this issue then add the following property:

put("client.transport.ignore_cluster_name", true)

The below basic code is working fine for me:

Settings settings = Settings.builder()
            .put("cluster.name", "my-application").put("client.transport.sniff", true).put("client.transport.ignore_cluster_name", false).build();
    TransportClient client = new PreBuiltTransportClient(settings).addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));

ImportError: No module named 'google'

According to https://developers.google.com/api-client-library/python/apis/oauth2/v1 you need to install google-api-python-client package:

pip install --upgrade google-api-python-client

Is there a way to get LaTeX to place figures in the same page as a reference to that figure?

Yes, include float package into the top of your document and H (capital H) as a figure specifier:

\usepackage{float}

\begin{figure}[H]
.
.
.
\end{figure}

How do you round a double in Dart to a given degree of precision AFTER the decimal point?

Above solutions do not work for all cases. What worked for my problem was this solution that will round your number (0.5 to 1 or 0.49 to 0) and leave it without any decimals:

Input: 12.67

double myDouble = 12.67;
var myRoundedNumber; // Note the 'var' datatype

// Here I used 1 decimal. You can use another value in toStringAsFixed(x)
myRoundedNumber = double.parse((myDouble).toStringAsFixed(1));
myRoundedNumber = myRoundedNumber.round();

print(myRoundedNumber);

Output: 13

This link has other solutions too

How do you create a yes/no boolean field in SQL server?

bit is the most suitable option. Otherwise I once used int for that purpose. 1 for true & 0 for false.

Upgrading PHP on CentOS 6.5 (Final)

  1. Verify current version of PHP Type in the following to see the current PHP version:

    php -v

    Should output something like:

    PHP 5.3.3 (cli) (built: Jul 9 2015 17:39:00) Copyright (c) 1997-2010 The PHP Group Zend Engine v2.3.0, Copyright (c) 1998-2010 Zend Technologies

  2. Install the Remi and EPEL RPM repositories

If you haven’t already done so, install the Remi and EPEL repositories

wget https://dl.fedoraproject.org/pub/epel/epel-release-latest-6.noarch.rpm && rpm -Uvh epel-release-latest-6.noarch.rpm



wget http://rpms.famillecollet.com/enterprise/remi-release-6.rpm && rpm -Uvh remi-release-6*.rpm

Enable the REMI repository globally:

nano /etc/yum.repos.d/remi.repo

Under the section that looks like [remi] make the following changes:

[remi]
name=Remi's RPM repository for Enterprise Linux 6 - $basearch
#baseurl=http://rpms.remirepo.net/enterprise/6/remi/$basearch/
mirrorlist=http://rpms.remirepo.net/enterprise/6/remi/mirror
enabled=1
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-remi

Also, under the section that looks like [remi-php55] make the following changes:

[remi-php56]
name=Remi's PHP 5.6 RPM repository for Enterprise Linux 6 - $basearch
#baseurl=http://rpms.remirepo.net/enterprise/6/php56/$basearch/
mirrorlist=http://rpms.remirepo.net/enterprise/6/php56/mirror
# WARNING: If you enable this repository, you must also enable "remi"
enabled=1
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-remi

Type CTRL-O to save and CTRL-X to close the editor

  1. Upgrade PHP 5.3 to PHP 5.6 Now we can upgrade PHP. Simply type in the following command:

    yum -y upgrade php*

Once the update has completed, let’s verify that you have PHP 5.6 installed:

php -v

Should see output similar to the following:

PHP 5.6.14 (cli) (built: Sep 30 2015 14:07:43) 
Copyright (c) 1997-2015 The PHP Group
Zend Engine v2.6.0, Copyright (c) 1998-2015 Zend Technologies

How to apply slide animation between two activities in Android?

Kotlin example:

    private val SPLASH_DELAY: Long = 1000

    internal val mRunnable: Runnable = Runnable {
        if (!isFinishing) {
            val intent = Intent(applicationContext, HomeActivity::class.java)
            startActivity(intent)
            overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
            finish()
        }
    }


   private fun navigateToHomeScreen() {
        //Initialize the Handler
        mDelayHandler = Handler()

        //Navigate with delay
        mDelayHandler!!.postDelayed(mRunnable, SPLASH_DELAY)

    }

    public override fun onDestroy() {

        if (mDelayHandler != null) {
            mDelayHandler!!.removeCallbacks(mRunnable)
        }

        super.onDestroy()
    }

put animations in anim folder:

slide_in.xml

<?xml version="1.0" encoding="utf-8"?>
<translate
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:duration="@android:integer/config_longAnimTime"
        android:fromXDelta="100%p"
        android:toXDelta="0%p">
</translate>

slide_out.xml

<?xml version="1.0" encoding="utf-8"?>
<translate
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:duration="@android:integer/config_longAnimTime"
        android:fromXDelta="0%p"
        android:toXDelta="-100%p">
</translate>

USAGE

  navigateToHomeScreen();

appending array to FormData and send via AJAX

You can also send an array via FormData this way:

var formData = new FormData;
var arr = ['this', 'is', 'an', 'array'];
for (var i = 0; i < arr.length; i++) {
    formData.append('arr[]', arr[i]);
}

So you can write arr[] the same way as you do it with a simple HTML form. In case of PHP it should work.

You may find this article useful: How to pass an array within a query string?