Programs & Examples On #Isinteger

Determine if a String is an Integer in Java

You can use Integer.parseInt() or Integer.valueOf() to get the integer from the string, and catch the exception if it is not a parsable int. You want to be sure to catch the NumberFormatException it can throw.

It may be helpful to note that valueOf() will return an Integer object, not the primitive int.

What's the best way to check if a String represents an integer in Java?

Find this may helpful:

public static boolean isInteger(String self) {
    try {
        Integer.valueOf(self.trim());
        return true;
    } catch (NumberFormatException nfe) {
        return false;
    }
}

How to read request body in an asp.net core webapi controller?

A clearer solution, works in ASP.Net Core 2.1 / 3.1

Filter class

using Microsoft.AspNetCore.Authorization;
// For ASP.NET 2.1
using Microsoft.AspNetCore.Http.Internal;
// For ASP.NET 3.1
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;

public class ReadableBodyStreamAttribute : AuthorizeAttribute, IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationFilterContext context)
    {
        // For ASP.NET 2.1
        // context.HttpContext.Request.EnableRewind();
        // For ASP.NET 3.1
        // context.HttpContext.Request.EnableBuffering();
    }
}

In an Controller

[HttpPost]
[ReadableBodyStream]
public string SomePostMethod()
{
    //Note: if you're late and body has already been read, you may need this next line
    //Note2: if "Note" is true and Body was read using StreamReader too, then it may be necessary to set "leaveOpen: true" for that stream.
    HttpContext.Request.Body.Seek(0, SeekOrigin.Begin);

    using (StreamReader stream = new StreamReader(HttpContext.Request.Body))
    {
        string body = stream.ReadToEnd();
        // body = "param=somevalue&param2=someothervalue"
    }
}

How to do case insensitive search in Vim

You can use in your vimrc those commands:

  • set ignorecase - All your searches will be case insensitive
  • set smartcase - Your search will be case sensitive if it contains an uppercase letter

You need to set ignorecase if you want to use what smartcase provides.

I wrote recently an article about Vim search commands (both built in command and the best plugins to search efficiently).

Difference between Arrays.asList(array) and new ArrayList<Integer>(Arrays.asList(array))

package com.copy;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

public class CopyArray {

    public static void main(String[] args) {
        List<Integer> list1, list2 = null;
        Integer[] intarr = { 3, 4, 2, 1 };
        list1 = new ArrayList<Integer>(Arrays.asList(intarr));
        list1.add(30);
        list2 = Arrays.asList(intarr);
        // list2.add(40); Here, we can't modify the existing list,because it's a wrapper
        System.out.println("List1");
        Iterator<Integer> itr1 = list1.iterator();
        while (itr1.hasNext()) {
            System.out.println(itr1.next());
        }
        System.out.println("List2");
        Iterator<Integer> itr2 = list2.iterator();
        while (itr2.hasNext()) {
            System.out.println(itr2.next());
        }
    }
}

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

There's a duplicate question with a simpler answer using cut:

 svn status |  grep '\!' | cut -d\  -f2-

-d specifies the delimeter (space), -f specifies the list of columns (all starting with the 2nd)

Get element of JS object with an index

I know it's a late answer, but I think this is what OP asked for.

myobj[Object.keys(myobj)[0]];

forcing web-site to show in landscape mode only

I had to play with the widths of my main containers:

html {
  @media only screen and (orientation: portrait) and (max-width: 555px) {
    transform: rotate(90deg);
    width: calc(155%);
    .content {
      width: calc(155%);
    }
  }
}

Anaconda site-packages

I installed miniconda and found all the installed packages in /miniconda3/pkgs

How to attach a process in gdb

With a running instance of myExecutableName having a PID 15073:

hitting Tab twice after $ gdb myExecu in the command line, will automagically autocompletes to:

$ gdb myExecutableName 15073

and will attach gdb to this process. That's nice!

Android Call an method from another class

You should use the following code :

Class2 cls2 = new Class2();
cls2.UpdateEmployee();

In case you don't want to create a new instance to call the method, you can decalre the method as static and then you can just call Class2.UpdateEmployee().

Change bar plot colour in geom_bar with ggplot2 in r

If you want all the bars to get the same color (fill), you can easily add it inside geom_bar.

ggplot(data=df, aes(x=c1+c2/2, y=c3)) + 
geom_bar(stat="identity", width=c2, fill = "#FF6666")

enter image description here

Add fill = the_name_of_your_var inside aes to change the colors depending of the variable :

c4 = c("A", "B", "C")
df = cbind(df, c4)
ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) + 
geom_bar(stat="identity", width=c2)

enter image description here

Use scale_fill_manual() if you want to manually the change of colors.

ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) + 
geom_bar(stat="identity", width=c2) + 
scale_fill_manual("legend", values = c("A" = "black", "B" = "orange", "C" = "blue"))

enter image description here

Oracle SQL escape character (for a '&')

SELECT 'Free &' || ' Clear' FROM DUAL;

How can I access my localhost from my Android device?

The above didn't work for me. This did for Mac:

In terminal:

ifconfig

Then take the number after inet and put it in your mobile browser:

enter image description here

How does Facebook disable the browser's integrated Developer Tools?

Netflix also implements this feature

(function() {
    try {
        var $_console$$ = console;
        Object.defineProperty(window, "console", {
            get: function() {
                if ($_console$$._commandLineAPI)
                    throw "Sorry, for security reasons, the script console is deactivated on netflix.com";
                return $_console$$
            },
            set: function($val$$) {
                $_console$$ = $val$$
            }
        })
    } catch ($ignore$$) {
    }
})();

They just override console._commandLineAPI to throw security error.

Makefile to compile multiple C programs?

############################################################################
# 'A Generic Makefile for Building Multiple main() Targets in $PWD'
# Author:  Robert A. Nader (2012)
# Email: naderra at some g
# Web: xiberix
############################################################################
#  The purpose of this makefile is to compile to executable all C source
#  files in CWD, where each .c file has a main() function, and each object
#  links with a common LDFLAG.
#
#  This makefile should suffice for simple projects that require building
#  similar executable targets.  For example, if your CWD build requires
#  exclusively this pattern:
#
#  cc -c $(CFLAGS) main_01.c
#  cc main_01.o $(LDFLAGS) -o main_01
#
#  cc -c $(CFLAGS) main_2..c
#  cc main_02.o $(LDFLAGS) -o main_02
#
#  etc, ... a common case when compiling the programs of some chapter,
#  then you may be interested in using this makefile.
#
#  What YOU do:
#
#  Set PRG_SUFFIX_FLAG below to either 0 or 1 to enable or disable
#  the generation of a .exe suffix on executables
#
#  Set CFLAGS and LDFLAGS according to your needs.
#
#  What this makefile does automagically:
#
#  Sets SRC to a list of *.c files in PWD using wildcard.
#  Sets PRGS BINS and OBJS using pattern substitution.
#  Compiles each individual .c to .o object file.
#  Links each individual .o to its corresponding executable.
#
###########################################################################
#
PRG_SUFFIX_FLAG := 0
#
LDFLAGS := 
CFLAGS_INC := 
CFLAGS := -g -Wall $(CFLAGS_INC)
#
## ==================- NOTHING TO CHANGE BELOW THIS LINE ===================
##
SRCS := $(wildcard *.c)
PRGS := $(patsubst %.c,%,$(SRCS))
PRG_SUFFIX=.exe
BINS := $(patsubst %,%$(PRG_SUFFIX),$(PRGS))
## OBJS are automagically compiled by make.
OBJS := $(patsubst %,%.o,$(PRGS))
##
all : $(BINS)
##
## For clarity sake we make use of:
.SECONDEXPANSION:
OBJ = $(patsubst %$(PRG_SUFFIX),%.o,$@)
ifeq ($(PRG_SUFFIX_FLAG),0)
        BIN = $(patsubst %$(PRG_SUFFIX),%,$@)
else
        BIN = $@
endif
## Compile the executables
%$(PRG_SUFFIX) : $(OBJS)
    $(CC) $(OBJ)  $(LDFLAGS) -o $(BIN)
##
## $(OBJS) should be automagically removed right after linking.
##
veryclean:
ifeq ($(PRG_SUFFIX_FLAG),0)
    $(RM) $(PRGS)
else
    $(RM) $(BINS)
endif
##
rebuild: veryclean all
##
## eof Generic_Multi_Main_PWD.makefile

CSS transition effect makes image blurry / moves image 1px, in Chrome?

Scaling to double and bringing down to half with zoom worked for me.

transform: scale(2);
zoom: 0.5;

changing the owner of folder in linux

Use chown to change ownership and chmod to change rights.

use the -R option to apply the rights for all files inside of a directory too.

Note that both these commands just work for directories too. The -R option makes them also change the permissions for all files and directories inside of the directory.

For example

sudo chown -R username:group directory

will change ownership (both user and group) of all files and directories inside of directory and directory itself.

sudo chown username:group directory

will only change the permission of the folder directory but will leave the files and folders inside the directory alone.

you need to use sudo to change the ownership from root to yourself.

Edit:

Note that if you use chown user: file (Note the left-out group), it will use the default group for that user.

Also You can change the group ownership of a file or directory with the command:

chgrp group_name file/directory_name

You must be a member of the group to which you are changing ownership to.

You can find group of file as follows

# ls -l file
-rw-r--r-- 1 root family 0 2012-05-22 20:03 file

# chown sujit:friends file

User 500 is just a normal user. Typically user 500 was the first user on the system, recent changes (to /etc/login.defs) has altered the minimum user id to 1000 in many distributions, so typically 1000 is now the first (non root) user.

What you may be seeing is a system which has been upgraded from the old state to the new state and still has some processes knocking about on uid 500. You can likely change it by first checking if your distro should indeed now use 1000, and if so alter the login.defs file yourself, the renumber the user account in /etc/passwd and chown/chgrp all their files, usually in /home/, then reboot.

But in answer to your question, no, you should not really be worried about this in all likelihood. It'll be showing as "500" instead of a username because o user in /etc/passwd has a uid set of 500, that's all.

Also you can show your current numbers using id i'm willing to bet it comes back as 1000 for you.

Determine what attributes were changed in Rails after_save callback?

you can add a condition to the after_update like so:

class SomeModel < ActiveRecord::Base
  after_update :send_notification, if: :published_changed?

  ...
end

there's no need to add a condition within the send_notification method itself.

How to get std::vector pointer to the raw data?

something.data() will return a pointer to the data space of the vector.

How to replace comma (,) with a dot (.) using java

Use this:

String str = " 12,12"
str = str.replaceAll("(\\d+)\\,(\\d+)", "$1.$2");
System.out.println("str:"+str); //-> str:12.12

hope help you.

/etc/apt/sources.list" E212: Can't open file for writing

because the dir is not exist.

can use :!mkdir -p /etc/apt/ to make the directory.

then :wq

what is the basic difference between stack and queue?

A Visual Model

Pancake Stack (LIFO)

The only way to add one and/or remove one is from the top.

pancake stack

Line Queue (FIFO)

When one arrives they arrive at the end of the queue and when one leaves they leave from the front of the queue.

dmv line

Fun fact: the British refer to lines of people as a Queue

Multiline text in JLabel

Type the content (i.e., the "text" property field) inside a <html></html> tag. So you can use <br> or<P> to insert a newline.

For example:

String labelContent = "<html>Twinkle, twinkle, little star,<BR>How I wonder what you are.<BR>Up above the world so high,<BR>Like a diamond in the sky.</html>";

It will display as follows:

Twinkle, twinkle, little star,
How I wonder what you are.
Up above the world so high,
Like a diamond in the sky.

How to set shadows in React Native for android?

You can use my react-native-simple-shadow-view

  • This enables almost identical shadow in Android as in iOS
  • No need to use elevation, works with the same shadow parameters of iOS (shadowColor, shadowOpacity, shadowRadius, offset, etc.) so you don't need to write platform specific shadow styles
  • Can be used with semi-transparent views
  • Supported in android 18 and up

Nodejs cannot find installed module on Windows

I'll just quote from this node's blog post...

In general, the rule of thumb is:

  • If you’re installing something that you want to use in your program, using require('whatever'), then install it locally, at the root of your project.
  • If you’re installing something that you want to use in your shell, on the command line or something, install it globally, so that its binaries end up in your PATH environment variable.

...

Of course, there are some cases where you want to do both. Coffee-script and Express both are good examples of apps that have a command line interface, as well as a library. In those cases, you can do one of the following:

  1. Install it in both places. Seriously, are you that short on disk space? It’s fine, really. They’re tiny JavaScript programs.
  2. Install it globally, and then npm link coffee-script or npm link express (if you’re on a platform that supports symbolic links.) Then you only need to update the global copy to update all the symlinks as well.

Add image to left of text via css

For adding background icon always before text when length of text is not known in advance.

.create:before{
content: "";
display: inline-block;
background: #ccc url(arrow.png) no-repeat;
width: 10px;background-size: contain;
height: 10px;
}

Javascript find json value

var obj = [
  {"name": "Afghanistan", "code": "AF"}, 
  {"name": "Åland Islands", "code": "AX"}, 
  {"name": "Albania", "code": "AL"}, 
  {"name": "Algeria", "code": "DZ"}
];

// the code you're looking for
var needle = 'AL';

// iterate over each element in the array
for (var i = 0; i < obj.length; i++){
  // look for the entry with a matching `code` value
  if (obj[i].code == needle){
     // we found it
    // obj[i].name is the matched result
  }
}

Using Intent in an Android application to show another activity

add the activity in your manifest file

<activity android:name=".OrderScreen" />

What is the difference between Task.Run() and Task.Factory.StartNew()

Apart from the similarities i.e. Task.Run() being a shorthand for Task.Factory.StartNew(), there is a minute difference between their behaviour in case of sync and async delegates.

Suppose there are following two methods:

public async Task<int> GetIntAsync()
{
    return Task.FromResult(1);
}

public int GetInt()
{
    return 1;
}

Now consider the following code.

var sync1 = Task.Run(() => GetInt());
var sync2 = Task.Factory.StartNew(() => GetInt());

Here both sync1 and sync2 are of type Task<int>

However, difference comes in case of async methods.

var async1 = Task.Run(() => GetIntAsync());
var async2 = Task.Factory.StartNew(() => GetIntAsync());

In this scenario, async1 is of type Task<int>, however async2 is of type Task<Task<int>>

Focusable EditText inside ListView

In my case, there is 14 input edit text in the list view. The problem I was facing, when the keyboard open, edit text focus lost, scroll the layout, and as soon as focused view not visible to the user keyboard down. It was not good for the user experience. I can't use windowSoftInputMethod="adjustPan". So after so much searching, I found a link that inflates custom layout and sets data on view as an adapter by using LinearLayout and scrollView and work well for my case.

C++11 introduced a standardized memory model. What does it mean? And how is it going to affect C++ programming?

If you use mutexes to protect all your data, you really shouldn't need to worry. Mutexes have always provided sufficient ordering and visibility guarantees.

Now, if you used atomics, or lock-free algorithms, you need to think about the memory model. The memory model describes precisely when atomics provide ordering and visibility guarantees, and provides portable fences for hand-coded guarantees.

Previously, atomics would be done using compiler intrinsics, or some higher level library. Fences would have been done using CPU-specific instructions (memory barriers).

How to join three table by laravel eloquent model

With Eloquent its very easy to retrieve relational data. Checkout the following example with your scenario in Laravel 5.

We have three models:

1) Article (belongs to user and category)

2) Category (has many articles)

3) User (has many articles)


1) Article.php

<?php

namespace App\Models;
 use Eloquent;

class Article extends Eloquent{

    protected $table = 'articles';

    public function user()
    {
        return $this->belongsTo('App\Models\User');
    }

    public function category()
    {
        return $this->belongsTo('App\Models\Category');
    }

}

2) Category.php

<?php

namespace App\Models;

use Eloquent;

class Category extends Eloquent
{
    protected $table = "categories";

    public function articles()
    {
        return $this->hasMany('App\Models\Article');
    }

}

3) User.php

<?php

namespace App\Models;
use Eloquent;

class User extends Eloquent
{
    protected $table = 'users';

    public function articles()
    {
        return $this->hasMany('App\Models\Article');
    }

}

You need to understand your database relation and setup in models. User has many articles. Category has many articles. Articles belong to user and category. Once you setup the relationships in Laravel, it becomes easy to retrieve the related information.

For example, if you want to retrieve an article by using the user and category, you would need to write:

$article = \App\Models\Article::with(['user','category'])->first();

and you can use this like so:

//retrieve user name 
$article->user->user_name  

//retrieve category name 
$article->category->category_name

In another case, you might need to retrieve all the articles within a category, or retrieve all of a specific user`s articles. You can write it like this:

$categories = \App\Models\Category::with('articles')->get();

$users = \App\Models\Category::with('users')->get();

You can learn more at http://laravel.com/docs/5.0/eloquent

How to convert JSON to a Ruby hash

What about the following snippet?

require 'json'
value = '{"val":"test","val1":"test1","val2":"test2"}'
puts JSON.parse(value) # => {"val"=>"test","val1"=>"test1","val2"=>"test2"}

How to return a list of keys from a Hash Map?

Since Java 8:

List<String> myList = map.keySet().stream().collect(Collectors.toList());

C++ "was not declared in this scope" compile error

What's wrong:

The definition of "nonrecursivecountcells" has no parameter named grid. You need to pass the type AND variable name to the function. You only passed the type.

Note if you use the name grid for the parameter, that name has nothing to do with your main() declaration of grid. You could have used any other name as well.

***Also you can't pass arrays as values.


How to fix:

The easy way to fix this is to pass a pointer to an array to the function "nonrecursivecountcells".

int nonrecursivecountcells(color[ROW_SIZE][COL_SIZE], int, int);

better and type safe ->

int nonrecursivecountcells(color (&grid)[ROW_SIZE][COL_SIZE], int, int);

About scope:

A variable created on the stack comes out of scope when the block it is declared in is terminated. A block is anything within an opening and matching closing brace. For example an if() { }, function() { }, while() {}, ...

Note I said variable and not data. For example you can allocate memory on the heap and that data will still remain valid even outside of the scope. But the variable that originally pointed to it would still come out of scope.

Install numpy on python3.3 - Install pip for python3

In the solution below I used python3.4 as binary, but it's safe to use with any version or binary of python. it works fine on windows too (except the downloading pip with wget obviously but just save the file locally and run it with python).

This is great if you have multiple versions of python installed, so you can manage external libraries per python version.

So first, I'd recommend get-pip.py, it's great to install pip :

wget https://bootstrap.pypa.io/get-pip.py

Then you need to install pip for your version of python, I have python3.4 so for me this is the command :

python3.4 get-pip.py

Now pip is installed for python3.4 and in order to get libraries for python3.4 one need to call it within this version, like this :

python3.4 -m pip

So if you want to install numpy you would use :

python3.4 -m pip install numpy

Note that numpy is quite the heavy library. I thought my system was hanging and failing. But using the verbose option, you can see that the system is fine :

python3.4 -m pip install numpy -v

This may tell you that you lack python.h but you can easily get it :

On RHEL (Red hat, CentOS, Fedora) it would be something like this :

yum install python34-devel

On debian-like (Debian, Ubuntu, Kali, ...) :

apt-get install python34-dev

Then rerun this :

python3.4 -m pip install numpy -v

ImageView in android XML layout with layout_height="wrap_content" has padding top & bottom

I had a simular issue and resolved it using android:adjustViewBounds="true" on the ImageView.

<ImageView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:adjustViewBounds="true"
    android:contentDescription="@string/banner_alt"
    android:src="@drawable/banner_portrait" />

Java FileOutputStream Create File if not exists

File f = new File("Test.txt");
if(!f.exists()){
  f.createNewFile();
}else{
  System.out.println("File already exists");
}

Pass this f to your FileOutputStream constructor.

How do you get a list of the names of all files present in a directory in Node.js?

I'm assuming from your question that you don't want directories names, just files.

Directory Structure Example

animals
+-- all.jpg
+-- mammals
¦   +-- cat.jpg
¦   +-- dog.jpg
+-- insects
    +-- bee.jpg

Walk function

Credits go to Justin Maier in this gist

If you want just an array of the files paths use return_object: false:

const fs = require('fs').promises;
const path = require('path');

async function walk(dir) {
    let files = await fs.readdir(dir);
    files = await Promise.all(files.map(async file => {
        const filePath = path.join(dir, file);
        const stats = await fs.stat(filePath);
        if (stats.isDirectory()) return walk(filePath);
        else if(stats.isFile()) return filePath;
    }));

    return files.reduce((all, folderContents) => all.concat(folderContents), []);
}

Usage

async function main() {
   console.log(await walk('animals'))
}

Output

[
  "/animals/all.jpg",
  "/animals/mammals/cat.jpg",
  "/animals/mammals/dog.jpg",
  "/animals/insects/bee.jpg"
];

System.Threading.Timer in C# it seems to be not working. It runs very fast every 3 second

This is not the correct usage of the System.Threading.Timer. When you instantiate the Timer, you should almost always do the following:

_timer = new Timer( Callback, null, TIME_INTERVAL_IN_MILLISECONDS, Timeout.Infinite );

This will instruct the timer to tick only once when the interval has elapsed. Then in your Callback function you Change the timer once the work has completed, not before. Example:

private void Callback( Object state )
{
    // Long running operation
   _timer.Change( TIME_INTERVAL_IN_MILLISECONDS, Timeout.Infinite );
}

Thus there is no need for locking mechanisms because there is no concurrency. The timer will fire the next callback after the next interval has elapsed + the time of the long running operation.

If you need to run your timer at exactly N milliseconds, then I suggest you measure the time of the long running operation using Stopwatch and then call the Change method appropriately:

private void Callback( Object state )
{
   Stopwatch watch = new Stopwatch();

   watch.Start();
   // Long running operation

   _timer.Change( Math.Max( 0, TIME_INTERVAL_IN_MILLISECONDS - watch.ElapsedMilliseconds ), Timeout.Infinite );
}

I strongly encourage anyone doing .NET and is using the CLR who hasn't read Jeffrey Richter's book - CLR via C#, to read is as soon as possible. Timers and thread pools are explained in great details there.

IndentationError: unexpected indent error

The indentation is wrong, as the error tells you. As you can see, you have indented the code beginning with the indicated line too little to be in the for loop, but too much to be at the same level as the for loop. Python sees the lack of indentation as ending the for loop, then complains you have indented the rest of the code too much. (The def line I'm betting is just an artifact of how Stack Overflow wants you to format your code.)

Edit: Given your correction, I'm betting you have a mixture of tabs and spaces in the source file, such that it looks to the human eye like the code lines up, but Python considers it not to. As others have suggested, using only spaces is the recommended practice (see PEP 8). If you start Python with python -t, you will get warnings if there are mixed tabs and spaces in your code, which should help you pinpoint the issue.

startActivityForResult() from a Fragment and finishing child Activity, doesn't call onActivityResult() in Fragment

The most important thing, that all are missing here is... The launchMode of FirstActivity must be singleTop. If it is singleInstance, the onActivityResult in FragmentA will be called just after calling the startActivityForResult method. So, It will not wait for calling of the finish() method in SecondActivity.

So go through the following steps, It will definitely work as it worked for me too after a long research.

In AndroidManifest.xml file, make launchMode of FirstActivity.Java as singleTop.

<activity
        android:name=".FirstActivity"
        android:label="@string/title_activity_main"
        android:launchMode="singleTop"
        android:theme="@style/AppTheme.NoActionBar" />

In FirstActivity.java, override onActivityResult method. As this will call the onActivityResult of FragmentA.

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
}

In FragmentA.Java, override onActivityResult method

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    Log.d("FragmentA.java","onActivityResult called");
}

Call startActivityForResult(intent, HOMEWORK_POST_ACTIVITY); from FragmentA.Java

Call finish(); method in SecondActivity.java

Hope this will work.

How to find the size of an int[]?

You can't do that for a dynamically allocated array (or a pointer). For static arrays, you can use sizeof(array) to get the whole array size in bytes and divide it by the size of each element:

#define COUNTOF(x) (sizeof(x)/sizeof(*x))

To get the size of a dynamic array, you have to keep track of it manually and pass it around with it, or terminate it with a sentinel value (like '\0' in null terminated strings).

Update: I realized that your question is tagged C++ and not C. You should definitely consider using std::vector instead of arrays in C++ if you want to pass things around:

std::vector<int> v;
v.push_back(1);
v.push_back(2);
std::cout << v.size() << std::endl; // prints 2

Read a javascript cookie by name

One of the shortest ways is this, however as mentioned previously it can return the wrong cookie if there's similar names (MyCookie vs AnotherMyCookie):

var regex = /MyCookie=(.[^;]*)/ig;
var match = regex.exec(document.cookie);
var value = match[1];

I use this in a chrome extension so I know the name I'm setting, and I can make sure there won't be a duplicate, more or less.

How to get a property value based on the name

In addition other guys answer, its Easy to get property value of any object by use Extension method like:

public static class Helper
    {
        public static object GetPropertyValue(this object T, string PropName)
        {
            return T.GetType().GetProperty(PropName) == null ? null : T.GetType().GetProperty(PropName).GetValue(T, null);
        }

    }

Usage is:

Car foo = new Car();
var balbal = foo.GetPropertyValue("Make");

How might I convert a double to the nearest integer value?

Methods in other answers throw OverflowException if the float value is outside the Int range. https://docs.microsoft.com/en-us/dotnet/api/system.convert.toint32?view=netframework-4.8#System_Convert_ToInt32_System_Single_

int result = 0;
try {
    result = Convert.ToInt32(value);
}
catch (OverflowException) {
    if (value > 0) result = int.MaxValue;
    else result = int.Minvalue;
}

Disable Scrolling on Body

This post was helpful, but just wanted to share a slight alternative that may help others:

Setting max-height instead of height also does the trick. In my case, I'm disabling scrolling based on a class toggle. Setting .someContainer {height: 100%; overflow: hidden;} when the container's height is smaller than that of the viewport would stretch the container, which wouldn't be what you'd want. Setting max-height accounts for this, but if the container's height is greater than the viewport's when the content changes, still disables scrolling.

How do I connect to a Websphere Datasource with a given JNDI name?

For those like me, only needing information on how to connect to a (DB2) WAS Data Source from Java using JNDI lookup (Used IBM Websphere 8.5.5 & DB2 Universal JDBC Driver Provider with implementation class: com.ibm.db2.jcc.DB2ConnectionPoolDataSource):

public DataSource getJndiDataSource() throws NamingException {
    DataSource datasource = null;
    InitialContext context = new InitialContext();
    // Tomcat/Possibly others: java:comp/env/jdbc/myDatasourceJndiName
    datasource = (DataSource) context.lookup("jdbc/myDatasourceJndiName");
    return datasource;
}

test if display = none

Try this instead to only select the visible elements under the tbody:

$('tbody :visible').highlight(myArray[i]);

Java generating Strings with placeholders

If you can change the format of your placeholder, you could use String.format(). If not, you could also replace it as pre-processing.

String.format("hello %s!", "world");

More information in this other thread.

How to check Spark Version

You can get the spark version by using the following command:

spark-submit --version

spark-shell --version

spark-sql --version

You can visit the below site to know the spark-version used in CDH 5.7.0

http://www.cloudera.com/documentation/enterprise/release-notes/topics/cdh_rn_new_in_cdh_57.html#concept_m3k_rxh_1v

How can I check if string contains characters & whitespace, not just whitespace?

I've used the following method to detect if a string contains only whitespace. It also matches empty strings.

if (/^\s*$/.test(myStr)) {
  // the string contains only whitespace
}

Android - default value in editText

You can use text property in your xml file for particular Edittext fields. For example :

<EditText
    android:id="@+id/ET_User"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="yourusername"/>

like this all Edittext fields contains text whatever u want,if user wants to change particular Edittext field he remove older text and enter his new text.

In Another way just you get the particular Edittext field id in activity class and set text to that one.

Another way = programmatically

Example:

EditText username=(EditText)findViewById(R.id.ET_User);

username.setText("jack");

How do I list all the files in a directory and subdirectories in reverse chronological order?

If the number of files you want to view fits within the maximum argument limit you can use globbing to get what you want, with recursion if you have globstar support.

For exactly 2 layers deep use: ls -d * */*

With globstar, for recursion use: ls -d **/*

The -d argument to ls tells it not to recurse directories passed as arguments (since you are using the shell globbing to do the recursion). This prevents ls using its recursion formatting.

Checkbox for nullable boolean

I also faced the same issue. I tried the following approach to solve the issue because i don't want to change the DB and again generate the EDMX.

@{

   bool testVar = (Model.MYVar ? true : false);

 }

<label>@Html.CheckBoxFor(m => testVar)testVar</label><br />

Map.Entry: How to use it?

Hash-Map stores the (key,value) pair as the Map.Entry Type.As you know that Hash-Map uses Linked Hash-Map(In case Collision occurs). Therefore each Node in the Bucket of Hash-Map is of Type Map.Entry. So whenever you iterate through the Hash-Map you will get Nodes of Type Map.Entry.

Now in your example when you are iterating through the Hash-Map, you will get Map.Entry Type(Which is Interface), To get the Key and Value from this Map.Entry Node Object, interface provided methods like getValue(), getKey() etc. So as per the code, In your Object you are adding all operators JButtons viz (+,-,/,*,=).

How to tell if tensorflow is using gpu acceleration from inside python shell?

Tensorflow 2.1

A simple calculation that can be verified with nvidia-smi for memory usage on the GPU.

import tensorflow as tf 

c1 = []
n = 10

def matpow(M, n):
    if n < 1: #Abstract cases where n < 1
        return M
    else:
        return tf.matmul(M, matpow(M, n-1))

with tf.device('/gpu:0'):
    a = tf.Variable(tf.random.uniform(shape=(10000, 10000)), name="a")
    b = tf.Variable(tf.random.uniform(shape=(10000, 10000)), name="b")
    c1.append(matpow(a, n))
    c1.append(matpow(b, n))

Best way to find os name and version in Unix/Linux platform

this command gives you a description of your operating system

cat /etc/os-release

Radio button checked event handling

Try something like this:

$(function(){
  $('input[type="radio"]').click(function(){
    if ($(this).is(':checked'))
    {
      alert($(this).val());
    }
  });
});

If you give your radio buttons a class then you can replace the code $('input[type="radio"]') with $('.someclass').

jQuery select box validation

http://docs.jquery.com/Plugins/Validation/Methods/required

edit the code for 'select' as below for checking for a 0 or null value selection from select list

case 'select':
var options = $("option:selected", element);
return (options[0].value != 0 && options.length > 0 && options[0].value != '') && (element.type == "select-multiple" || ($.browser.msie && !(options[0].attributes['value'].specified) ? options[0].text : options[0].value).length > 0);

Access host database from a docker container

From Docker 17.06 onwards, a special Mac-only DNS name is available in docker containers that resolves to the IP address of the host. It is:

docker.for.mac.localhost

The documentation is here: https://docs.docker.com/docker-for-mac/networking/#httphttps-proxy-support

Crop image in android

I found a really cool library, try this out. this is really smooth and easy to use.

https://github.com/TakuSemba/CropMe

Access a global variable in a PHP function

For many years I have always used this format:

<?php
    $data = "Hello";

    function sayHello(){
        echo $GLOBALS["data"];
    }

    sayHello();
?>

I find it straightforward and easy to follow. The $GLOBALS is how PHP lets you reference a global variable. If you have used things like $_SERVER, $_POST, etc. then you have reference a global variable without knowing it.

Qt. get part of QString

If you do not need to modify the substring, then you can use QStringRef. The QStringRef class is a read only wrapper around an existing QString that references a substring within the existing string. This gives much better performance than creating a new QString object to contain the sub-string. E.g.

QString myString("This is a string");
QStringRef subString(&myString, 5, 2); // subString contains "is"

If you do need to modify the substring, then left(), mid() and right() will do what you need...

QString myString("This is a string");
QString subString = myString.mid(5,2); // subString contains "is"
subString.append("n't"); // subString contains "isn't"

Objective-C - Remove last character from string

The documentation is your friend, NSString supports a call substringWithRange that can shorten the string that you have an return the shortened String. You cannot modify an instance of NSString it is immutable. If you have an NSMutableString is has a method called deleteCharactersInRange that can modify the string in place

...
NSRange r;
r.location = 0;
r.size = [mutable length]-1;
NSString* shorted = [stringValue substringWithRange:r];
...

Why does the arrow (->) operator in C exist?

C also does a good job at not making anything ambiguous.

Sure the dot could be overloaded to mean both things, but the arrow makes sure that the programmer knows that he's operating on a pointer, just like when the compiler won't let you mix two incompatible types.

Table Naming Dilemma: Singular vs. Plural Names

Tables: plural

Multiple users are listed in the users table.

Models: singular

A singular user can be selected from the users table.

Controllers: plural

http://myapp.com/users would list multiple users.

That's my take on it anyway.

How can I get the iOS 7 default blue color programmatically?

Use self.view.tintColor from a view controller, or self.tintColor from a UIView subclass.

Which @NotNull Java annotation should I use?

Doesn't sun have their own now? What's this:
http://www.java2s.com/Open-Source/Java-Document/6.0-JDK-Modules-com.sun/istack/com.sun.istack.internal.htm

This seems to be packaged with all the versions of Java I've used within the last few years.

Edit: As mentioned in the comments below, you probably don't want to use these. In that case, my vote is for the IntelliJ jetbrains annotations!

Split varchar into separate columns in Oracle

Depends on the consistency of the data - assuming a single space is the separator between what you want to appear in column one vs two:

SELECT SUBSTR(t.column_one, 1, INSTR(t.column_one, ' ')-1) AS col_one,
       SUBSTR(t.column_one, INSTR(t.column_one, ' ')+1) AS col_two
  FROM YOUR_TABLE t

Oracle 10g+ has regex support, allowing more flexibility depending on the situation you need to solve. It also has a regex substring method...

Reference:

How to convert float number to Binary?

Consider below example

Convert 2.625 to binary.

We will consider the integer and fractional part separately.

The integral part is easy, 2 = 10. 

For the fractional part:

0.625   × 2 =   1.25    1   Generate 1 and continue with the rest.
0.25    × 2 =   0.5     0   Generate 0 and continue.
0.5     × 2 =   1.0     1   Generate 1 and nothing remains.

So 0.625 = 0.101, and 2.625 = 10.101.

See this link for more information.

Calling javascript function in iframe

Instead of getting the frame from the document, try getting the frame from the window object.

in the above example change this:

if (typeof (document.all.resultFrame.Reset) == "function")
    document.all.resultFrame.Reset();
else
    alert("resultFrame.Reset NOT found");

to

if (typeof (window.frames[0].Reset) == "function")
    window.frames[0].Reset();
else
    alert("resultFrame.Reset NOT found");

the problem is that the scope of the javascript inside the iframe is not exposed through the DOM element for the iframe. only window objects contain the javascript scoping information for the frames.

How do you get/set media volume (not ringtone volume) in Android?

If you happen to have a volume bar that you want to adjust –similar to what you see on iPhone's iPod app– here's how.

    @Override
public boolean onKeyDown(int keyCode, KeyEvent event) {

    switch (keyCode) {
    case KeyEvent.KEYCODE_VOLUME_UP:
        audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI);
        //Raise the Volume Bar on the Screen
        volumeControl.setProgress( audioManager.getStreamVolume(AudioManager.STREAM_MUSIC)
                + AudioManager.ADJUST_RAISE);
        return true;
    case KeyEvent.KEYCODE_VOLUME_DOWN:
        //Adjust the Volume
        audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_LOWER, AudioManager.FLAG_SHOW_UI);
        //Lower the VOlume Bar on the Screen
        volumeControl.setProgress(audioManager
                .getStreamVolume(AudioManager.STREAM_MUSIC)
                + AudioManager.ADJUST_LOWER);
        return true;
    default:
        return false;
    }

Reset textbox value in javascript

To set value

 $('#searchField').val('your_value');

to retrieve value

$('#searchField').val();

How to deal with ModalDialog using selenium webdriver?

I have tried it, it works for you.

String mainWinHander = webDriver.getWindowHandle();

// code for clicking button to open new window is ommited

//Now the window opened. So here reture the handle with size = 2
Set<String> handles = webDriver.getWindowHandles();

for(String handle : handles)
{
    if(!mainWinHander.equals(handle))
    {
        // Here will block for ever. No exception and timeout!
        WebDriver popup = webDriver.switchTo().window(handle);
        // do something with popup
        popup.close();
    }
}

How do I add a Font Awesome icon to input field?

You can use another tag instead of input and apply FontAwesome the normal way.

instead of your input with type image you can use this:

<i class="icon-search icon-2x"></i>

quick CSS:

.icon-search {
    color:white;
    background-color:black;
}

Here is a quick fiddle: DEMO

You can style it a little better and add event functionality, to the i object, which you can do by using a <button type="submit"> object instead of i, or with javascript.

The button sollution would be something like this:

<button type="submit" class="icon-search icon-large"></button>

And the CSS:

.icon-search {
    height:32px;
    width:32px;
    border: none;
    cursor: pointer;
    color:white;
    background-color:black;
    position:relative;
}

here is my fiddle updated with the button instead of i: DEMO


Update: Using FontAwesome on any tag

The problem with FontAwsome is that its stylesheet uses :before pseudo-elements to add the icons to an element - and pseudo elements don't work/are not allowed on input elements. This is why using FontAwesome the normal way will not work with input.

But there is a solution - you can use FontAwesome as a regular font like so:

CSS:

input[type="submit"] {
    font-family: FontAwesome;
}

HTML:

<input type="submit" class="search" value="&#xf002;" />

The glyphs can be passed as values of the value attribute. The ascii codes for the individual letters/icons can be found in the FontAwesome css file, you just need to change them into a HTML ascii number like \f002 to &#xf002; and it should work.

Link to the FontAwesome ascii code (cheatsheet): fortawesome.github.io/Font-Awesome/cheatsheet

The size of the icons can be easily adjusted via font-size.

See the above example using an input element in a jsfidde:

DEMO


Update: FontAwesome 5

With FontAwesome version 5 the CSS required for this solution has changed - the font family name has changed and the font weight must be specified:

input[type="submit"] {
    font-family: "Font Awesome 5 Free"; // for the open access version
    font-size: 1.3333333333333333em;
    font-weight: 900;
}

See @WillFastie 's comment with link to updated fiddle bellow. Thanks!

Can I call methods in constructor in Java?

Why not to use Static Initialization Blocks ? Additional details here: Static Initialization Blocks

Selecting Multiple Values from a Dropdown List in Google Spreadsheet

You would use data validation for this. Click in the cell you want to have a multiple drop down > DATA > Validation > Criteria (List from a Range) - here you select form a list of items you want in the drop down. And .. you are good. I have included an example to reference.

Get values from other sheet using VBA

Maybe you can use the script i am using to retrieve a certain cell value from another sheet back to a specific sheet.

Sub reviewRow()
Application.ScreenUpdating = False
Results = MsgBox("Do you want to View selected row?", vbYesNo, "")
If Results = vbYes And Range("C10") > 1 Then
i = Range("C10") //this is where i put the row number that i want to retrieve or review that can be changed as needed
Worksheets("Sheet1").Range("C6") = Worksheets("Sheet2").Range("C" & i) //sheet names can be changed as necessary
End if
Application.ScreenUpdating = True
End Sub

You can make a form using this and personalize it as needed.

Body set to overflow-y:hidden but page is still scrollable in Chrome

Use:

overflow: hidden;
height: 100%;
position: fixed;
width: 100%;

$.ajax - dataType

as per docs:

  • "json": Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)
  • "text": A plain text string.

How to use boolean datatype in C?

C99 introduced _Bool as intrinsic pure boolean type. No #includes needed:

int main(void)
{
  _Bool b = 1;
  b = 0;
}

On a true C99 (or higher) compliant C compiler the above code should compile perfectly fine.

Array as session variable

First change the array to a string by using implode() function. E.g $number=array(1,2,3,4,5,...); $stringofnumber=implode("|",$number); then pass the string to a session. e.g $_SESSION['string']=$stringofnumber; so when you go to the page where you want to use the array, just explode your string. e.g $number=explode("|", $_SESSION['string']); finally number is your array but remember to start array on the of each page.

How do I fix a "Performance counter registry hive consistency" when installing SQL Server R2 Express?

Save the execution file on your desktop Make sure you note the name of your file Go to start and type cmd right click on it

select run as administrator press enter

then you something below

C:\Users\your computer name\Desktop>

If you are seeing

C:\Windows\system32>

make sure you change it using CD

type the name of your file

C:\Users\your computer name\Desktop>the name of the file your copy.exe/ACTION=install /SKIPRULES=PerfMonCounterNotCorruptedCheck

Stop embedded youtube iframe?

One cannot simply overestimate this post and answers thx OP and helpers. My solution with just video_id exchanging:

<div style="pointer-events: none;">
    <iframe id="myVideo" src="https://www.youtube.com/embed/video_id?rel=0&modestbranding=1&fs=0&controls=0&autoplay=1&showinfo=0&version=3&enablejsapi=1" width="560" height="315" frameborder="0"></iframe> </div>

    <button id="play">PLAY</button>

    <button id="pause">PAUSE</button>


    <script>
        $('#play').click(function() {
            $('#myVideo').each(function(){ 
                var frame = document.getElementById("myVideo");
                frame.contentWindow.postMessage(
                    '{"event":"command","func":"playVideo","args":""}', 
                    '*'); 
            });
        });

        $('#pause').click(function() {
            $('#myVideo').each(function(){ 
                var frame = document.getElementById("myVideo");
                frame.contentWindow.postMessage(
                  '{"event":"command","func":"pauseVideo","args":""}',
                  '*'); 
            });
        });
    </script>

Proper way to exit command line program?

if you do ctrl-z and then type exit it will close background applications.

Ctrl+Q is another good way to kill the application.

setup android on eclipse but don't know SDK directory

ADT Plugin (UNSUPPORTED)

The Eclipse ADT plugin is no longer supported, as per this announcement in June 2015.

The Eclipse ADT plugin has many known bugs and potential security bugs that will not be fixed.

You should immediately switch to use Android Studio, the official IDE for Android.

For help transitioning your projects, read Migrate to Android Studio.

How to check whether a variable is a class or not?

isinstance(X, type)

Return True if X is class and False if not.

Postgresql: password authentication failed for user "postgres"

I hope this will help you short of time. You can change the password of postgres sql by using bellow command.

Command

sudo -u postgres psql

And next you can update the password

Command

Alter user postgres password 'YOUR_NEW_PASSWORD';

Change string color with NSAttributedString?

In Swift 4:

// Custom color
let greenColor = UIColor(red: 10/255, green: 190/255, blue: 50/255, alpha: 1)
// create the attributed colour
let attributedStringColor = [NSAttributedStringKey.foregroundColor : greenColor];
// create the attributed string
let attributedString = NSAttributedString(string: "Hello World!", attributes: attributedStringColor)
// Set the label
label.attributedText = attributedString

In Swift 3:

// Custom color
let greenColor = UIColor(red: 10/255, green: 190/255, blue: 50/255, alpha: 1)
// create the attributed color
let attributedStringColor : NSDictionary = [NSForegroundColorAttributeName : greenColor];
// create the attributed string
let attributedString = NSAttributedString(string: "Hello World!", attributes: attributedStringColor as? [String : AnyObject])
// Set the label
label.attributedText = attributedString 

Enjoy.

How to create a new variable in a data.frame based on a condition?

One obvious and straightforward possibility is to use "if-else conditions". In that example

x <- c(1, 2, 4)
y <- c(1, 4, 5)
w <- ifelse(x <= 1, "good", ifelse((x >= 3) & (x <= 5), "bad", "fair"))
data.frame(x, y, w)

** For the additional question in the edit** Is that what you expect ?

> d1 <- c("e", "c", "a")
> d2 <- c("e", "a", "b")
> 
> w <- ifelse((d1 == "e") & (d2 == "e"), 1, 
+    ifelse((d1=="a") & (d2 == "b"), 2,
+    ifelse((d1 == "e"), 3, 99)))
>     
> data.frame(d1, d2, w)
  d1 d2  w
1  e  e  1
2  c  a 99
3  a  b  2

If you do not feel comfortable with the ifelse function, you can also work with the if and else statements for such applications.

Login to website, via C#

Sometimes, it may help switching off AllowAutoRedirect and setting both login POST and page GET requests the same user agent.

request.UserAgent = userAgent;
request.AllowAutoRedirect = false;

How to execute an SSIS package from .NET?

So there is another way you can actually fire it from any language. The best way I think, you can just create a batch file which will call your .dtsx package.

Next you call the batch file from any language. As in windows platform, you can run batch file from anywhere, I think this will be the most generic approach for your purpose. No code dependencies.

Below is a blog for more details..

https://www.mssqltips.com/sqlservertutorial/218/command-line-tool-to-execute-ssis-packages/

Happy coding.. :)

Thanks, Ayan

Removing the fragment identifier from AngularJS urls (# symbol)

Be sure to check browser support for the html5 history API:

  if(window.history && window.history.pushState){
    $locationProvider.html5Mode(true);
  }

To show a new Form on click of a button in C#

private void ButtonClick(object sender, System.EventArgs e)
{
    MyForm form = new MyForm();
    form.Show(); // or form.ShowDialog(this);
}

Java variable number or arguments for a method

Variable number of arguments

It is possible to pass a variable number of arguments to a method. However, there are some restrictions:

  • The variable number of parameters must all be the same type
  • They are treated as an array within the method
  • They must be the last parameter of the method

To understand these restrictions, consider the method, in the following code snippet, used to return the largest integer in a list of integers:

private static int largest(int... numbers) {
     int currentLargest = numbers[0];
     for (int number : numbers) {
        if (number > currentLargest) {
            currentLargest = number;
        }
     }
     return currentLargest;
}

source Oracle Certified Associate Java SE 7 Programmer Study Guide 2012

How to update data in one table from corresponding data in another table in SQL Server 2005

 UPDATE Employee SET Empid=emp3.empid 
 FROM EMP_Employee AS emp3
 WHERE Employee.Empid=emp3.empid

Does adding a duplicate value to a HashSet/HashMap replace the previous value

The docs are pretty clear on this: HashSet.add doesn't replace:

Adds the specified element to this set if it is not already present. More formally, adds the specified element e to this set if this set contains no element e2 such that (e==null ? e2==null : e.equals(e2)). If this set already contains the element, the call leaves the set unchanged and returns false.

But HashMap.put will replace:

If the map previously contained a mapping for the key, the old value is replaced.

php artisan migrate throwing [PDO Exception] Could not find driver - Using Laravel

I think you missed the mysql driver for php5. Execute below command:

sudo apt-get install php5-mysql
/etc/init.d/php5-fpm restart

XML Schema Validation : Cannot find the declaration of element

cvc-elt.1: Cannot find the declaration of element 'Root'. [7]

Your schemaLocation attribute on the root element should be xsi:schemaLocation, and you need to fix it to use the right namespace.

You should probably change the targetNamespace of the schema and the xmlns of the document to http://myNameSpace.com (since namespaces are supposed to be valid URIs, which Test.Namespace isn't, though urn:Test.Namespace would be ok). Once you do that it should find the schema. The point is that all three of the schema's target namespace, the document's namespace, and the namespace for which you're giving the schema location must be the same.

(though it still won't validate as your <element2> contains an <element3> in the document where the schema expects item)

How to increase dbms_output buffer?

Here you go:

DECLARE
BEGIN
  dbms_output.enable(NULL); -- Disables the limit of DBMS
  -- Your print here !
END;

Differences between hard real-time, soft real-time, and firm real-time?

The simplest way to distinguish between the different kinds of real-time system types is answering the question:

Is a delayed system response (after the deadline) is still useful or not?

So depending on the answer you get for this question, your system could be included as one of the following categories:

  1. Hard: No, and delayed answers are considered a system failure

This is the case when missing the dead-line will make the system unusable. For example the system controlling the car Airbag system should detect the crash and inflate rapidly the bag. The whole process takes more or less one-twenty-fifth of a second. Thus, if the system for example react with 1 second of delay the consequences could be mortal and it will be no benefit having the bag inflated once the car has already crashed.

  1. Firm: No, but delayed answers are not necessary a system failure

This is the case when missing the deadline is tolerable but it will affect the quality of the service. As a simple example consider a video encryption system. Normally the password of encryption is generated in the server (video Head end) and sent to the customer set-top box. This process should be synchronized so normally the set-top box receives the password before starts receiving the encrypted video frames. In this case a delay it may lead to video glitches since the set-top box is not able to decode the frames because it hasn't received the password yet. In this case the service (film, an interesting football match, etc) could be affected by not meeting the deadline. Receiving the password with delay in this case is not useful since the frames encrypted with the same have already caused the glitches.

  1. Soft: Yes, but the system service is degraded

As from the the wikipedia description the usefulness of a result degrades after its deadline. That means, getting a response from the system out of the deadline is still useful for the end user but its usefulness degrade after reaching the deadline. A simple example for this case is a software that automatically controls the temperature of a room (or a building). In this case if the system has some delays reading the temperature sensors it will be a little bit slow to react upon brusque temperature changes. However, at the end it will end up reacting to the change and adjusting accordingly the temperature to keep it constant for example. So in this case the delayed reaction is useful, but it degrades the system quality of service.

inject bean reference into a Quartz job in Spring?

You can use this SpringBeanJobFactory to automatically autowire quartz objects using spring:

import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.scheduling.quartz.SpringBeanJobFactory;

public final class AutowiringSpringBeanJobFactory extends SpringBeanJobFactory implements
    ApplicationContextAware {

    private transient AutowireCapableBeanFactory beanFactory;

    @Override
    public void setApplicationContext(final ApplicationContext context) {
        beanFactory = context.getAutowireCapableBeanFactory();
    }

    @Override
    protected Object createJobInstance(final TriggerFiredBundle bundle) throws Exception {
        final Object job = super.createJobInstance(bundle);
        beanFactory.autowireBean(job);
        return job;
    }
}

Then, attach it to your SchedulerBean (in this case, with Java-config):

@Bean
public SchedulerFactoryBean quartzScheduler() {
    SchedulerFactoryBean quartzScheduler = new SchedulerFactoryBean();

    ...

    AutowiringSpringBeanJobFactory jobFactory = new AutowiringSpringBeanJobFactory();
    jobFactory.setApplicationContext(applicationContext);
    quartzScheduler.setJobFactory(jobFactory);

    ...

    return quartzScheduler;
}

Working for me, using spring-3.2.1 and quartz-2.1.6.

Check out the complete gist here.

I found the solution in this blog post

How to select a drop-down menu value with Selenium using Python?

Selenium provides a convenient Select class to work with select -> option constructs:

from selenium import webdriver
from selenium.webdriver.support.ui import Select

driver = webdriver.Firefox()
driver.get('url')

select = Select(driver.find_element_by_id('fruits01'))

# select by visible text
select.select_by_visible_text('Banana')

# select by value 
select.select_by_value('1')

See also:

Attach the Java Source Code

To attach JDK source so that you refer to Java Source Code for code look-up which helps in learning the library implementation and sometimes in debugging, all you have to do is:

In your Eclipse Java Project > JRE Reference Library locate rt.jar. Right click and go to Properties:

Select "Java Source Attachment" on the right and to the left select "External Location" and click on "External File" Button and locate "src.zip" file in your $JAVA_HOME path in my case for my windows machine src.zip location is: C:/Program Files/Java/jdk1.7.0_45/src.zip.

You are done now! Just Ctrl + click on any Java library Class in your project code to look-up the source code for the java class.

How to get parameters from the URL with JSP

About the Implicit Objects of the Unified Expression Language, the Java EE 5 Tutorial writes:

Implicit Objects

The JSP expression language defines a set of implicit objects:

  • pageContext: The context for the JSP page. Provides access to various objects including:
    • servletContext: The context for the JSP page’s servlet and any web components contained in the same application. See Accessing the Web Context.
    • session: The session object for the client. See Maintaining Client State.
    • request: The request triggering the execution of the JSP page. See Getting Information from Requests.
    • response: The response returned by the JSP page. See Constructing Responses.
  • In addition, several implicit objects are available that allow easy access to the following objects:
    • param: Maps a request parameter name to a single value
    • paramValues: Maps a request parameter name to an array of values
    • header: Maps a request header name to a single value
    • headerValues: Maps a request header name to an array of values
    • cookie: Maps a cookie name to a single cookie
    • initParam: Maps a context initialization parameter name to a single value
  • Finally, there are objects that allow access to the various scoped variables described in Using Scope Objects.
    • pageScope: Maps page-scoped variable names to their values
    • requestScope: Maps request-scoped variable names to their values
    • sessionScope: Maps session-scoped variable names to their values
    • applicationScope: Maps application-scoped variable names to their values

The interesting parts are in bold :)

So, to answer your question, you should be able to access it like this (using EL):

${param.accountID}

Or, using JSP Scriptlets (not recommended):

<%
    String accountId = request.getParameter("accountID");
%>

What is the "double tilde" (~~) operator in JavaScript?

~(5.5)   // => -6
~(-6)    // => 5
~~5.5    // => 5  (same as Math.floor(5.5))
~~(-5.5) // => -5 (NOT the same as Math.floor(-5.5), which would give -6 )

For more info, see:

Load and execution sequence of a web page?

The chosen answer looks like does not apply to modern browsers, at least on Firefox 52. What I observed is that the requests of loading resources like css, javascript are issued before HTML parser reaches the element, for example

<html>
  <head>
    <!-- prints the date before parsing and blocks HTMP parsering -->
    <script>
      console.log("start: " + (new Date()).toISOString());
      for(var i=0; i<1000000000; i++) {};
    </script>

    <script src="jquery.js" type="text/javascript"></script>
    <script src="abc.js" type="text/javascript"></script>
    <link rel="stylesheets" type="text/css" href="abc.css"></link>
    <style>h2{font-wight:bold;}</style>
    <script>
      $(document).ready(function(){
      $("#img").attr("src", "kkk.png");
     });
   </script>
 </head>
 <body>
   <img id="img" src="abc.jpg" style="width:400px;height:300px;"/>
   <script src="kkk.js" type="text/javascript"></script>
   </body>
</html>

What I found that the start time of requests to load css and javascript resources were not being blocked. Looks like Firefox has a HTML scan, and identify key resources(img resource is not included) before starting to parse the HTML.

static function in C

Looking at the posts above I would like to give a more clarified answer:

Suppose our main.c file looks like this:

#include "header.h"

int main(void) {
    FunctionInHeader();
}

Now consider three cases:

  • Case 1: Our header.h file looks like this:

     #include <stdio.h>
    
     static void FunctionInHeader();
    
     void FunctionInHeader() {
         printf("Calling function inside header\n");
     }
    

    Then the following command on linux:

     gcc main.c -o main
    

    will succeed! That's because after the main.c file includes the header.h, the static function definition will be in the same main.c file (more precisely, in the same translation unit) to where it's called.

    If one runs ./main, the output will be Calling function inside header, which is what that static function should print.

  • Case 2: Our header header.h looks like this:

      static void FunctionInHeader();     
    

    and we also have one more file header.c, which looks like this:

      #include <stdio.h>
      #include "header.h"
    
      void FunctionInHeader() {
          printf("Calling function inside header\n");
      }
    

    Then the following command

      gcc main.c header.c -o main
    

    will give an error. In this case main.c includes only the declaration of the static function, but the definition is left in another translation unit and the static keyword prevents the code defining a function to be linked

  • Case 3:

    Similar to case 2, except that now our header header.h file is:

      void FunctionInHeader(); // keyword static removed
    

    Then the same command as in case 2 will succeed, and further executing ./main will give the expected result. Here the FunctionInHeader definition is in another translation unit, but the code defining it can be linked.

Thus, to conclude:

static keyword prevents the code defining a function to be linked,
when that function is defined in another translation unit than where it is called.

Getting values from query string in an url using AngularJS $location

Not sure if it has changed since the accepted answer was accepted, but it is possible.

$location.search() will return an object of key-value pairs, the same pairs as the query string. A key that has no value is just stored in the object as true. In this case, the object would be:

{"test_user_bLzgB": true}

You could access this value directly with $location.search().test_user_bLzgB

Example (with larger query string): http://fiddle.jshell.net/TheSharpieOne/yHv2p/4/show/?test_user_bLzgB&somethingElse&also&something=Somethingelse

Note: Due to hashes (as it will go to http://fiddle.jshell.net/#/url, which would create a new fiddle), this fiddle will not work in browsers that do not support js history (will not work in IE <10)

Edit:
As pointed out in the comments by @Naresh and @DavidTchepak, the $locationProvider also needs to be configured properly: https://code.angularjs.org/1.2.23/docs/guide/$location#-location-service-configuration

Assign pandas dataframe column dtypes

For those coming from Google (etc.) such as myself:

convert_objects has been deprecated since 0.17 - if you use it, you get a warning like this one:

FutureWarning: convert_objects is deprecated.  Use the data-type specific converters 
pd.to_datetime, pd.to_timedelta and pd.to_numeric.

You should do something like the following:

Can one do a for each loop in java in reverse order?

This will mess with the original list and also needs to be called outside of the loop. Also you don't want to perform a reverse every time you loop - would that be true if one of the Iterables.reverse ideas was applied?

Collections.reverse(stringList);

for(String string: stringList){
//...do something
}

"Retrieving the COM class factory for component.... error: 80070005 Access is denied." (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))

  1. Make sure that you have Office runtime installed on the server.
  2. If you are using Windows Server 2008 then using office interops is a lenghty configuration and here are the steps.

Better is to move to Open XML or you can configure as below

  • Install MS Office Pro Latest (I used 2010 Pro)
  • Create User ExcelUser. Assign WordUser with Admin Group
  • Go to Computer -> Manage
  • Add User with below options
  • User Options Password Never Expires
  • Password Cannot Be Change

Com+ Configuration

  • Go to Control Panel - > Administrator -> Component Services -> DCOM Config
  • Open Microsoft Word 97 - 2003 Properties
  • General -> Authentication Level : None
  • Security -> Customize all 3 permissions to allow everyone
  • Identity -> This User -> Use ExcelUser /password
  • Launch the Excel App to make sure everything is fine

3.Change the security settings of Microsoft Excel Application in DCOM Config.

Controlpanel --> Administrative tools-->Component Services -->computers --> myComputer -->DCOM Config --> Microsoft Excel Application.

Right click to get properties dialog. Go to Security tab and customize permissions

See the posts here: Error while creating Excel object , Excel manipulations in WCF using COM

Cast a Double Variable to Decimal

You can cast a double to a decimal like this, without needing the M literal suffix:

double dbl = 1.2345D;
decimal dec = (decimal) dbl;

You should use the M when declaring a new literal decimal value:

decimal dec = 123.45M;

(Without the M, 123.45 is treated as a double and will not compile.)

How to create many labels and textboxes dynamically depending on the value of an integer variable?

You can try this:

int cleft = 1;
intaleft = 1;
private void button2_Click(object sender, EventArgs e) 
{
     TextBox txt = new TextBox();
     this.Controls.Add(txt);
     txt.Top = cleft * 40;
     txt.Size = new Size(200, 16);
     txt.Left = 150;
     cleft = cleft + 1;
     Label lbl = new Label();
     this.Controls.Add(lbl);
     lbl.Top = aleft * 40;
     lbl.Size = new Size(100, 16);
     lbl.ForeColor = Color.Blue;
     lbl.Text = "BoxNo/CardNo";
     lbl.Left = 70;
     aleft = aleft + 1;
     return;
}
private void btd_Click(object sender, EventArgs e)
{ 
    //Here you Delete Text Box One By One(int ix for Text Box)
    for (int ix = this.Controls.Count - 2; ix >= 0; ix--)
    //Here you Delete Lable One By One(int ix for Lable)
    for (int x = this.Controls.Count - 2; x >= 0; x--)
    {
        if (this.Controls[ix] is TextBox) 
        this.Controls[ix].Dispose();
        if (this.Controls[x] is Label) 
        this.Controls[x].Dispose();
        return;
    }
}

How to run test methods in specific order in JUnit4?

If you want to run test methods in a specific order in JUnit 5, you can use the below code.

@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class MyClassTest { 

    @Test
    @Order(1)
    public void test1() {}

    @Test
    @Order(2)
    public void test2() {}

}

What is difference between mutable and immutable String in java

In Java, all strings are immutable. When you are trying to modify a String, what you are really doing is creating a new one. However, when you use a StringBuilder, you are actually modifying the contents, instead of creating a new one.

unable to remove file that really exists - fatal: pathspec ... did not match any files

If your file idea/workspace.xml is added to .gitignore (or its parent folder) just add it manually to git version control. Also you can add it using TortoiseGit. After the next push you will see, that your problem is solved.

Add to git versioning using TortoiseGit

python exception message capturing

Updating this to something simpler for logger (works for both python 2 and 3). You do not need traceback module.

import logging

logger = logging.Logger('catch_all')

def catchEverythingInLog():
    try:
        ... do something ...
    except Exception as e:
        logger.error(e, exc_info=True)
        ... exception handling ...

This is now the old way (though still works):

import sys, traceback

def catchEverything():
    try:
        ... some operation(s) ...
    except:
        exc_type, exc_value, exc_traceback = sys.exc_info()
        ... exception handling ...

exc_value is the error message.

Using ConfigurationManager to load config from an arbitrary location

Use XML processing:

var appPath = AppDomain.CurrentDomain.BaseDirectory;
var configPath = Path.Combine(appPath, baseFileName);;
var root = XElement.Load(configPath);

// can call root.Elements(...)

Exception thrown in catch and finally clause

Exceptions in the finally block supersede exceptions in the catch block.

Java Language Specification:

If the catch block completes abruptly for reason R, then the finally block is executed. Then there is a choice:

  • If the finally block completes normally, then the try statement completes abruptly for reason R.

  • If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S (and reason R is discarded).

JavaScript Editor Plugin for Eclipse

Complete the following steps in Eclipse to get plugins for JavaScript files:

  1. Open Eclipse -> Go to "Help" -> "Install New Software"
  2. Select the repository for your version of Eclipse. I have Juno so I selected http://download.eclipse.org/releases/juno
  3. Expand "Programming Languages" -> Check the box next to "JavaScript Development Tools"
  4. Click "Next" -> "Next" -> Accept the Terms of the License Agreement -> "Finish"
  5. Wait for the software to install, then restart Eclipse (by clicking "Yes" button at pop up window)
  6. Once Eclipse has restarted, open "Window" -> "Preferences" -> Expand "General" and "Editors" -> Click "File Associations" -> Add ".js" to the "File types:" list, if it is not already there
  7. In the same "File Associations" dialog, click "Add" in the "Associated editors:" section
  8. Select "Internal editors" radio at the top
  9. Select "JavaScript Viewer". Click "OK" -> "OK"

To add JavaScript Perspective: (Optional)
10. Go to "Window" -> "Open Perspective" -> "Other..."
11. Select "JavaScript". Click "OK"

To open .html or .js file with highlighted JavaScript syntax:
12. (Optional) Select JavaScript Perspective
13. Browse and Select .html or .js file in Script Explorer in [JavaScript Perspective] (Or Package Explorer [Java Perspective] Or PyDev Package Explorer [PyDev Perspective] Don't matter.)
14. Right-click on .html or .js file -> "Open With" -> "Other..."
15. Select "Internal editors"
16. Select "Java Script Editor". Click "OK" (see JavaScript syntax is now highlighted )

HttpContext.Current.Session is null when routing requests

The config section seems sound as it works if when pages are accessed normally. I've tried the other configurations suggested but the problem is still there.

I doubt the problem is in the Session provider since it works without the routing.

How can I get the key value in a JSON object?

You can simply traverse through the object and return if a match is found.

Here is the code:

returnKeyforValue : function() {
    var JsonObj= { "one":1, "two":2, "three":3, "four":4, "five":5 };
        for (key in JsonObj) {
        if(JsonObj[key] === "Keyvalue") {
            return key;
        }
    }
}

Why am I getting an OPTIONS request instead of a GET request?

I was able to fix it with the help of following headers

Access-Control-Allow-Origin
Access-Control-Allow-Headers
Access-Control-Allow-Credentials
Access-Control-Allow-Methods

If you are on Nodejs, here is the code you can copy/paste.

app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin','*');
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
  res.header('Access-Control-Allow-Credentials', true);
  res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH');
  next();
});

HTML Tags in Javascript Alert() method

You can use all Unicode characters and the escape characters \n and \t. An example:

_x000D_
_x000D_
document.getElementById("test").onclick = function() {_x000D_
  alert(_x000D_
    'This is an alert with basic formatting\n\n' _x000D_
    + "\t• list item 1\n" _x000D_
    + '\t• list item 2\n' _x000D_
    + '\t• list item 3\n\n' _x000D_
    + '???????????????????????\n\n' _x000D_
    + 'Simple table\n\n' _x000D_
    + 'Char\t| Result\n' _x000D_
    + '\\n\t| line break\n' _x000D_
    + '\\t\t| tab space'_x000D_
  );_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<title>Alert formatting</title>_x000D_
<meta charset=utf-8>_x000D_
<button id=test>Click</button>
_x000D_
_x000D_
_x000D_

Result in Firefox:

screenshot Firefox

You get the same look in almost all browsers.

PSQLException: current transaction is aborted, commands ignored until end of transaction block

Change the isolation level from repeatable read to read committed.

Showing the stack trace from a running Python application

How to debug any function in console:

Create function where you use pdb.set_trace(), then function you want debug.

>>> import pdb
>>> import my_function

>>> def f():
...     pdb.set_trace()
...     my_function()
... 

Then call created function:

>>> f()
> <stdin>(3)f()
(Pdb) s
--Call--
> <stdin>(1)my_function()
(Pdb) 

Happy debugging :)

Difference between number and integer datatype in oracle dictionary views

Integer is only there for the sql standard ie deprecated by Oracle.

You should use Number instead.

Integers get stored as Number anyway by Oracle behind the scenes.

Most commonly when ints are stored for IDs and such they are defined with no params - so in theory you could look at the scale and precision columns of the metadata views to see of no decimal values can be stored - however 99% of the time this will not help.

As was commented above you could look for number(38,0) columns or similar (ie columns with no decimal points allowed) but this will only tell you which columns cannot take decimals, and not what columns were defined so that INTS can be stored.

Suggestion: do a data profile on the number columns. Something like this:

 select max( case when trunc(column_name,0)=column_name then 0 else 1 end ) as has_dec_vals
 from table_name

Finding modified date of a file/folder

Here's what worked for me:

$a = Get-ChildItem \\server\XXX\Received_Orders\*.* | Where{$_.LastWriteTime -ge (Get-Date).AddDays(-7)}
if ($a = (Get-ChildItem \\server\XXX\Received_Orders\*.* | Where{$_.LastWriteTime -gt (Get-Date).AddDays(-7)}  
#Im using the -gt switch instead of -ge
{}
Else
{
'STORE XXX HAS NOT RECEIVED ANY ORDERS IN THE PAST 7 DAYS'
}


$b = Get-ChildItem \\COMP NAME\Folder\*.* | Where{$_.LastWriteTime -ge (Get-Date).AddDays(-1)}
if ($b = (Get-ChildItem \\COMP NAME\TFolder\*.* | Where{$_.LastWriteTime -gt (Get-Date).AddDays(-1)))}
{}
Else
{
'STORE XXX DID NOT RUN ITS BACKUP LAST NIGHT'
}

Force flex item to span full row width

When you want a flex item to occupy an entire row, set it to width: 100% or flex-basis: 100%, and enable wrap on the container.

The item now consumes all available space. Siblings are forced on to other rows.

_x000D_
_x000D_
.parent {
  display: flex;
  flex-wrap: wrap;
}

#range, #text {
  flex: 1;
}

.error {
  flex: 0 0 100%; /* flex-grow, flex-shrink, flex-basis */
  border: 1px dashed black;
}
_x000D_
<div class="parent">
  <input type="range" id="range">
  <input type="text" id="text">
  <label class="error">Error message (takes full width)</label>
</div>
_x000D_
_x000D_
_x000D_

More info: The initial value of the flex-wrap property is nowrap, which means that all items will line up in a row. MDN

wampserver doesn't go green - stays orange

If you can't start Wamp anymore right after a Windows update, this is often caused because of Windows that has automatically re-turned on the World Wide Web Publishing Service.

To solve: Click on Start, type Services, click Services, find World Wide Web Publishing Service, double click it, set Startup type to Disabled and click Stop button, OK this dialog and try to restart Wamp.

How to get different colored lines for different plots in a single figure?

Matplot colors your plot with different colors , but incase you wanna put specific colors

    import matplotlib.pyplot as plt
    import numpy as np
            
    x = np.arange(10)
            
    plt.plot(x, x)
    plt.plot(x, 2 * x,color='blue')
    plt.plot(x, 3 * x,color='red')
    plt.plot(x, 4 * x,color='green')
    plt.show()

Plotting images side by side using matplotlib

One thing that I found quite helpful to use to print all images :

_, axs = plt.subplots(n_row, n_col, figsize=(12, 12))
axs = axs.flatten()
for img, ax in zip(imgs, axs):
    ax.imshow(img)
plt.show()

What are the Ruby File.open modes and options?

opt is new for ruby 1.9. The various options are documented in IO.new : www.ruby-doc.org/core/IO.html

Find all files in a folder

First off; best practice would be to get the users Desktop folder with

string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

Then you can find all the files with something like

string[] files = Directory.GetFiles(path, "*.txt", SearchOption.AllDirectories);

Note that with the above line you will find all files with a .txt extension in the Desktop folder of the logged in user AND all subfolders.

Then you could copy or move the files by enumerating the above collection like

// For copying...
foreach (string s in files)
{
   File.Copy(s, "C:\newFolder\newFilename.txt");
}

// ... Or for moving
foreach (string s in files)
{
   File.Move(s, "C:\newFolder\newFilename.txt");
}

Please note that you will have to include the filename in your Copy() (or Move()) operation. So you would have to find a way to determine the filename of at least the extension you are dealing with and not name all the files the same like what would happen in the above example.

With that in mind you could also check out the DirectoryInfo and FileInfo classes. These work in similair ways, but you can get information about your path-/filenames, extensions, etc. more easily

Check out these for more info:

http://msdn.microsoft.com/en-us/library/system.io.directory.aspx

http://msdn.microsoft.com/en-us/library/ms143316.aspx

http://msdn.microsoft.com/en-us/library/system.io.file.aspx

How do I get total physical memory size using PowerShell without WMI?

Id like to say that instead of going with the systeminfo this would help over to get the total physical memory in GB's the machine

Get-CimInstance Win32_PhysicalMemory | Measure-Object -Property capacity -Sum | Foreach {"{0:N2}" -f ([math]::round(($_.Sum / 1GB),2))}

you can pass this value to the variable and get the gross output for the total physical memory in the machine

   $totalmemory = Get-CimInstance Win32_PhysicalMemory | Measure-Object -Property capacity -Sum | Foreach {"{0:N2}" -f ([math]::round(($_.Sum / 1GB),2))}
   $totalmemory

JavaScript: Upload file

Pure JS

You can use fetch optionally with await-try-catch

let photo = document.getElementById("image-file").files[0];
let formData = new FormData();
     
formData.append("photo", photo);
fetch('/upload/image', {method: "POST", body: formData});

_x000D_
_x000D_
async function SavePhoto(inp) 
{
    let user = { name:'john', age:34 };
    let formData = new FormData();
    let photo = inp.files[0];      
         
    formData.append("photo", photo);
    formData.append("user", JSON.stringify(user)); 
    
    const ctrl = new AbortController()    // timeout
    setTimeout(() => ctrl.abort(), 5000);
    
    try {
       let r = await fetch('/upload/image', 
         {method: "POST", body: formData, signal: ctrl.signal}); 
       console.log('HTTP response code:',r.status); 
    } catch(e) {
       console.log('Huston we have problem...:', e);
    }
    
}
_x000D_
<input id="image-file" type="file" onchange="SavePhoto(this)" >
<br><br>
Before selecting the file open chrome console > network tab to see the request details.
<br><br>
<small>Because in this example we send request to https://stacksnippets.net/upload/image the response code will be 404 ofcourse...</small>

<br><br>
(in stack overflow snippets there is problem with error handling, however in <a href="https://jsfiddle.net/Lamik/b8ed5x3y/5/">jsfiddle version</a> for 404 errors 4xx/5xx are <a href="https://stackoverflow.com/a/33355142/860099">not throwing</a> at all but we can read response status which contains code)
_x000D_
_x000D_
_x000D_

Old school approach - xhr

let photo = document.getElementById("image-file").files[0];  // file from input
let req = new XMLHttpRequest();
let formData = new FormData();

formData.append("photo", photo);                                
req.open("POST", '/upload/image');
req.send(formData);

_x000D_
_x000D_
function SavePhoto(e) 
{
    let user = { name:'john', age:34 };
    let xhr = new XMLHttpRequest();
    let formData = new FormData();
    let photo = e.files[0];      
    
    formData.append("user", JSON.stringify(user));   
    formData.append("photo", photo);
    
    xhr.onreadystatechange = state => { console.log(xhr.status); } // err handling
    xhr.timeout = 5000;
    xhr.open("POST", '/upload/image'); 
    xhr.send(formData);
}
_x000D_
<input id="image-file" type="file" onchange="SavePhoto(this)" >
<br><br>
Choose file and open chrome console > network tab to see the request details.
<br><br>
<small>Because in this example we send request to https://stacksnippets.net/upload/image the response code will be 404 ofcourse...</small>

<br><br>
(the stack overflow snippets, has some problem with error handling - the xhr.status is zero (instead of 404) which is similar to situation when we run script from file on <a href="https://stackoverflow.com/a/10173639/860099">local disc</a> - so I provide also js fiddle version which shows proper http error code <a href="https://jsfiddle.net/Lamik/k6jtq3uh/2/">here</a>)
_x000D_
_x000D_
_x000D_

SUMMARY

  • In server side you can read original file name (and other info) which is automatically included to request by browser in filename formData parameter.
  • You do NOT need to set request header Content-Type to multipart/form-data - this will be set automatically by browser.
  • Instead of /upload/image you can use full address like http://.../upload/image.
  • If you want to send many files in single request use multiple attribute: <input multiple type=... />, and attach all chosen files to formData in similar way (e.g. photo2=...files[2];... formData.append("photo2", photo2);)
  • You can include additional data (json) to request e.g. let user = {name:'john', age:34} in this way: formData.append("user", JSON.stringify(user));
  • You can set timeout: for fetch using AbortController, for old approach by xhr.timeout= milisec
  • This solutions should work on all major browsers.

Should Jquery code go in header or footer?

For me jQuery is a little bit special. Maybe an exception to the norm. There are so many other scripts that rely on it, so its quite important that it loads early so the other scripts that come later will work as intended. As someone else pointed out even this page loads jQuery in the head section.

Error:Cause: unable to find valid certification path to requested target

If you are running behind a corporate proxy with SSL interception, you will need to follow these steps to trust your proxy certificate for HTTPS:

  • In Android Studio, Open File -> Settings
    • In Tools -> Server Certificates
      • Tick ‘Accept non-trusted certificates automatically’
      • Also click the ‘+’ and manually add the corporate proxy root certificate.
    • In Appearance and Behaviour -> System Settings -> HTTP Proxy
      • Set your corporate proxy URL and port details
  • Download KeyStore Explorer: http://keystore-explorer.org/downloads.html
  • In KeyStore Explorer (run as admin), open the Android Studio JRE certificate store: C:\Program Files\Android\Android Studio\jre\jre\lib\security\cacerts
    • The password should be ‘changeit’
    • Import the corporate proxy root certificate, and save.
  • In Android Studio, select File -> Invalidate Cache and Restart

how to use html2canvas and jspdf to export to pdf in a proper and simple way

I have made a jsfiddle for you.

 <canvas id="canvas" width="480" height="320"></canvas> 
      <button id="download">Download Pdf</button>

'

        html2canvas($("#canvas"), {
            onrendered: function(canvas) {         
                var imgData = canvas.toDataURL(
                    'image/png');              
                var doc = new jsPDF('p', 'mm');
                doc.addImage(imgData, 'PNG', 10, 10);
                doc.save('sample-file.pdf');
            }
        });

jsfiddle: http://jsfiddle.net/rpaul/p4s5k59s/5/

Tested in Chrome38, IE11 and Firefox 33. Seems to have issues with Safari. However, Andrew got it working in Safari 8 on Mac OSx by switching to JPEG from PNG. For details, see his comment below.

How to write PNG image to string with the PIL?

With modern (as of mid-2017 Python 3.5 and Pillow 4.0):

StringIO no longer seems to work as it used to. The BytesIO class is the proper way to handle this. Pillow's save function expects a string as the first argument, and surprisingly doesn't see StringIO as such. The following is similar to older StringIO solutions, but with BytesIO in its place.

from io import BytesIO
from PIL import Image

image = Image.open("a_file.png")
faux_file = BytesIO()
image.save(faux_file, 'png')

Convert varchar2 to Date ('MM/DD/YYYY') in PL/SQL

Easiest way is probably to convert from a VARCHAR to a DATE; then format it back to a VARCHAR again in the format you want;

SELECT TO_CHAR(TO_DATE(DOJ,'MM/DD/YYYY'), 'MM/DD/YYYY') FROM EmpTable;

An SQLfiddle to test with.

stdcall and cdecl

I want to improve on @adf88's answer. I feel that pseudocode for the STDCALL does not reflect the way of how it happens in reality. 'a', 'b', and 'c' aren't popped from the stack in the function body. Instead they are popped by the ret instruction (ret 12 would be used in this case) that in one swoop jumps back to the caller and at the same time pops 'a', 'b', and 'c' from the stack.

Here is my version corrected according to my understanding:

STDCALL:

/* 1. calling STDCALL in pseudo-assembler (similar to what the compiler outputs) */
push on the stack a copy of 'z', then copy of 'y', then copy of 'x'
call
move contents of register A to 'i' variable

/* 2. STDCALL 'Function' body in pseaudo-assembler */ copy 'a' (from stack) to register A copy 'b' (from stack) to register B add A and B, store result in A copy 'c' (from stack) to register B add A and B, store result in A jump back to caller code and at the same time pop 'a', 'b' and 'c' off the stack (a, b and c are removed from the stack in this step, result in register A)

Converting a double to an int in Javascript without rounding

As @Quentin and @Pointy pointed out in their comments, it's not a good idea to use parseInt() because it is designed to convert a string to an integer. When you pass a decimal number to it, it first converts the number to a string, then casts it to an integer. I suggest you use Math.trunc(), Math.floor(), ~~num, ~~v , num | 0, num << 0, or num >> 0 depending on your needs. This performance test demonstrates the difference in parseInt() and Math.floor() performance. Also, this post explains the difference between the proposed methods.

How to mute an html5 video player using jQuery

$("video").prop('muted', true); //mute

AND

$("video").prop('muted', false); //unmute

See all events here

(side note: use attr if in jQuery < 1.6)

Getting the last revision number in SVN?

<?php
    $url = 'your repository here';
    $output = `svn info $url`;
    echo "<pre>$output</pre>";
?>

You can get the output in XML like so:

$output = `svn info $url --xml`;

If there is an error then the output will be directed to stderr. To capture stderr in your output use thusly:

$output = `svn info $url 2>&1`;

Looping through rows in a DataView

The DataView object itself is used to loop through DataView rows.

DataView rows are represented by the DataRowView object. The DataRowView.Row property provides access to the original DataTable row.

C#

foreach (DataRowView rowView in dataView)
{
    DataRow row = rowView.Row;
    // Do something //
}

VB.NET

For Each rowView As DataRowView in dataView
    Dim row As DataRow = rowView.Row
    ' Do something '
Next

convert string to date in sql server

This will do the trick:

SELECT CONVERT(char(10), GetDate(),126)

How to call base.base.method()?

public class A
{
    public int i = 0;
    internal virtual void test()
    {
        Console.WriteLine("A test");
    }
}

public class B : A
{
    public new int i = 1;
    public new void test()
    {
        Console.WriteLine("B test");
    }
}

public class C : B
{
    public new int i = 2;
    public new void test()
    {
        Console.WriteLine("C test - ");
        (this as A).test(); 
    }
}

Most efficient way to check for DBNull and then assign to a variable?

I try to avoid this check as much as possible.

Obviously doesn't need to be done for columns that can't hold null.

If you're storing in a Nullable value type (int?, etc.), you can just convert using as int?.

If you don't need to differentiate between string.Empty and null, you can just call .ToString(), since DBNull will return string.Empty.

Shell script to copy files from one location to another location and rename add the current date to every file

You can be used this step is very useful:

for i in `ls -l folder1 | grep -v total | awk '{print $ ( ? )}'`
do
   cd folder1
   cp $i folder2/$i.`date +%m%d%Y`
done

Assert that a method was called in a Python unit test

Yes, I can give you the outline but my Python is a bit rusty and I'm too busy to explain in detail.

Basically, you need to put a proxy in the method that will call the original, eg:

 class fred(object):
   def blog(self):
     print "We Blog"


 class methCallLogger(object):
   def __init__(self, meth):
     self.meth = meth

   def __call__(self, code=None):
     self.meth()
     # would also log the fact that it invoked the method

 #example
 f = fred()
 f.blog = methCallLogger(f.blog)

This StackOverflow answer about callable may help you understand the above.

In more detail:

Although the answer was accepted, due to the interesting discussion with Glenn and having a few minutes free, I wanted to enlarge on my answer:

# helper class defined elsewhere
class methCallLogger(object):
   def __init__(self, meth):
     self.meth = meth
     self.was_called = False

   def __call__(self, code=None):
     self.meth()
     self.was_called = True

#example
class fred(object):
   def blog(self):
     print "We Blog"

f = fred()
g = fred()
f.blog = methCallLogger(f.blog)
g.blog = methCallLogger(g.blog)
f.blog()
assert(f.blog.was_called)
assert(not g.blog.was_called)

Android ImageView setImageResource in code

This is how to set an image into ImageView using the setImageResource() method:

ImageView myImageView = (ImageView)v.findViewById(R.id.img_play);
// supossing to have an image called ic_play inside my drawables.
myImageView.setImageResource(R.drawable.ic_play);

How does cookie based authentication work?

Cookie-Based Authentication

Cookies based Authentication works normally in these 4 steps-

  1. The user provides a username and password in the login form and clicks Log In.
  2. After the request is made, the server validate the user on the backend by querying in the database. If the request is valid, it will create a session by using the user information fetched from the database and store them, for each session a unique id called session Id is created ,by default session Id is will be given to client through the Browser.
  3. Browser will submit this session Id on each subsequent requests, the session ID is verified against the database, based on this session id website will identify the session belonging to which client and then give access the request.

  4. Once a user logs out of the app, the session is destroyed both client-side and server-side.

How to clone a Date object?

Use the Date object's getTime() method, which returns the number of milliseconds since 1 January 1970 00:00:00 UTC (epoch time):

var date = new Date();
var copiedDate = new Date(date.getTime());

In Safari 4, you can also write:

var date = new Date();
var copiedDate = new Date(date);

...but I'm not sure whether this works in other browsers. (It seems to work in IE8).

How to show first commit by 'git log'?

You can just reverse your log and just head it for the first result.

git log --pretty=oneline --reverse | head -1

how to stop Javascript forEach?

Wy not use plain return?

function recurs(comment){
comment.comments.forEach(function(elem){
    recurs(elem);
    if(...) return;
});

it will return from 'recurs' function. I use it like this. Althougth this will not break from forEach but from whole function, in this simple example it might work

MySQL select with CONCAT condition

There is an alternative to repeating the CONCAT expression or using subqueries. You can make use of the HAVING clause, which recognizes column aliases.

SELECT 
  neededfield, CONCAT(firstname, ' ', lastname) AS firstlast 
FROM
  users 
HAVING firstlast = "Bob Michael Jones"

Here is a working SQL Fiddle.

MSIE and addEventListener Problem in Javascript?

Internet Explorer (IE8 and lower) doesn't support addEventListener(...). It has its own event model using the attachEvent method. You could use some code like this:

var element = document.getElementById('container');
if (document.addEventListener){
    element .addEventListener('copy', beforeCopy, false); 
} else if (el.attachEvent){
    element .attachEvent('oncopy', beforeCopy);
}

Though I recommend avoiding writing your own event handling wrapper and instead use a JavaScript framework (such as jQuery, Dojo, MooTools, YUI, Prototype, etc) and avoid having to create the fix for this on your own.

By the way, the third argument in the W3C model of events has to do with the difference between bubbling and capturing events. In almost every situation you'll want to handle events as they bubble, not when they're captured. It is useful when using event delegation on things like "focus" events for text boxes, which don't bubble.

Lists in ConfigParser

There is nothing stopping you from packing the list into a delimited string and then unpacking it once you get the string from the config. If you did it this way your config section would look like:

[Section 3]
barList=item1,item2

It's not pretty but it's functional for most simple lists.

How do I get specific properties with Get-AdUser

This worked for me as well:

Get-ADUser -Filter * -SearchBase "ou=OU,dc=Domain,dc=com" -Properties Enabled, CanonicalName, Displayname, Givenname, Surname, EmployeeNumber, EmailAddress, Department, StreetAddress, Title | select Enabled, CanonicalName, Displayname, GivenName, Surname, EmployeeNumber, EmailAddress, Department, Title | Export-CSV "C:\output.csv"

querying WHERE condition to character length?

SELECT *
   FROM   my_table
   WHERE  substr(my_field,1,5) = "abcde";

How to emulate a BEFORE INSERT trigger in T-SQL / SQL Server for super/subtype (Inheritance) entities?

Sometimes a BEFORE trigger can be replaced with an AFTER one, but this doesn't appear to be the case in your situation, for you clearly need to provide a value before the insert takes place. So, for that purpose, the closest functionality would seem to be the INSTEAD OF trigger one, as @marc_s has suggested in his comment.

Note, however, that, as the names of these two trigger types suggest, there's a fundamental difference between a BEFORE trigger and an INSTEAD OF one. While in both cases the trigger is executed at the time when the action determined by the statement that's invoked the trigger hasn't taken place, in case of the INSTEAD OF trigger the action is never supposed to take place at all. The real action that you need to be done must be done by the trigger itself. This is very unlike the BEFORE trigger functionality, where the statement is always due to execute, unless, of course, you explicitly roll it back.

But there's one other issue to address actually. As your Oracle script reveals, the trigger you need to convert uses another feature unsupported by SQL Server, which is that of FOR EACH ROW. There are no per-row triggers in SQL Server either, only per-statement ones. That means that you need to always keep in mind that the inserted data are a row set, not just a single row. That adds more complexity, although that'll probably conclude the list of things you need to account for.

So, it's really two things to solve then:

  • replace the BEFORE functionality;

  • replace the FOR EACH ROW functionality.

My attempt at solving these is below:

CREATE TRIGGER sub_trg
ON sub1
INSTEAD OF INSERT
AS
BEGIN
  DECLARE @new_super TABLE (
    super_id int
  );
  INSERT INTO super (subtype_discriminator)
  OUTPUT INSERTED.super_id INTO @new_super (super_id)
  SELECT 'SUB1' FROM INSERTED;

  INSERT INTO sub (super_id)
  SELECT super_id FROM @new_super;
END;

This is how the above works:

  1. The same number of rows as being inserted into sub1 is first added to super. The generated super_id values are stored in a temporary storage (a table variable called @new_super).

  2. The newly inserted super_ids are now inserted into sub1.

Nothing too difficult really, but the above will only work if you have no other columns in sub1 than those you've specified in your question. If there are other columns, the above trigger will need to be a bit more complex.

The problem is to assign the new super_ids to every inserted row individually. One way to implement the mapping could be like below:

CREATE TRIGGER sub_trg
ON sub1
INSTEAD OF INSERT
AS
BEGIN
  DECLARE @new_super TABLE (
    rownum   int IDENTITY (1, 1),
    super_id int
  );
  INSERT INTO super (subtype_discriminator)
  OUTPUT INSERTED.super_id INTO @new_super (super_id)
  SELECT 'SUB1' FROM INSERTED;

  WITH enumerated AS (
    SELECT *, ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS rownum
    FROM inserted
  )
  INSERT INTO sub1 (super_id, other columns)
  SELECT n.super_id, i.other columns
  FROM enumerated AS i
  INNER JOIN @new_super AS n
  ON i.rownum = n.rownum;
END;

As you can see, an IDENTIY(1,1) column is added to @new_user, so the temporarily inserted super_id values will additionally be enumerated starting from 1. To provide the mapping between the new super_ids and the new data rows, the ROW_NUMBER function is used to enumerate the INSERTED rows as well. As a result, every row in the INSERTED set can now be linked to a single super_id and thus complemented to a full data row to be inserted into sub1.

Note that the order in which the new super_ids are inserted may not match the order in which they are assigned. I considered that a no-issue. All the new super rows generated are identical save for the IDs. So, all you need here is just to take one new super_id per new sub1 row.

If, however, the logic of inserting into super is more complex and for some reason you need to remember precisely which new super_id has been generated for which new sub row, you'll probably want to consider the mapping method discussed in this Stack Overflow question:

How to sum columns in a dataTable?

It's a pity to use .NET and not use collections and lambda to save your time and code lines This is an example of how this works: Transform yourDataTable to Enumerable, filter it if you want , according a "FILTER_ROWS_FIELD" column, and if you want, group your data by a "A_GROUP_BY_FIELD". Then get the count, the sum, or whatever you wish. If you want a count and a sum without grouby don't group the data

var groupedData = from b in yourDataTable.AsEnumerable().Where(r=>r.Field<int>("FILTER_ROWS_FIELD").Equals(9999))
                          group b by b.Field<string>("A_GROUP_BY_FIELD") into g
                          select new
                          {
                              tag = g.Key,
                              count = g.Count(),
                              sum = g.Sum(c => c.Field<double>("rvMoney"))
                          };

How can I find the OWNER of an object in Oracle?

Interesting question - I don't think there's any Oracle function that does this (almost like a "which" command in Unix), but you can get the resolution order for the name by:

select * from 
(
 select  object_name objname, object_type, 'my object' details, 1 resolveOrder 
  from user_objects
  where object_type not like 'SYNONYM'
 union all
 select synonym_name obj , 'my synonym', table_owner||'.'||table_name, 2 resolveOrder
  from user_synonyms
 union all
 select  synonym_name obj , 'public synonym', table_owner||'.'||table_name, 3 resolveOrder
  from all_synonyms where owner = 'PUBLIC'
)
where objname like upper('&objOfInterest')

Combine multiple JavaScript files into one JS file

You can use a script that I made. You need JRuby to run this though. https://bitbucket.org/ardee_aram/jscombiner (JSCombiner).

What sets this apart is that it watches file changes in the javascript, and combines it automatically to the script of your choice. So there is no need to manually "build" your javascript each time you test it. Hope it helps you out, I am currently using this.

Move textfield when keyboard appears swift

The best way is using NotificationCenter to catch keyboard actions. You can follow the steps in this short article https://medium.com/@demirciy/keyboard-handling-deb1a96a8207

Comparing user-inputted characters in C

For a start, your answer variable should be of type char, not char*.

As for the if statement:

if (answer == ('Y' || 'y'))

This is first evaluating 'Y' || 'y' which, in Boolean logic (and for ASCII) is true since both of them are "true" (non-zero). In other words, you'd only get the if statement to fire if you'd somehow entered CTRLA (again, for ASCII, and where a true values equates to 1)*a.

You could use the more correct:

if ((answer == 'Y') || (answer == 'y'))

but you really should be using:

if (toupper(answer) == 'Y')

since that's the more portable way to achieve the same end.


*a You may be wondering why I'm putting in all sorts of conditionals for my statements. While the vast majority of C implementations use ASCII and certain known values, it's not necessarily mandated by the ISO standards. I know for a fact that at least one compiler still uses EBCDIC so I don't like making unwarranted assumptions.

C# using streams

I wouldn't call those different kind of streams. The Stream class have CanRead and CanWrite properties that tell you if the particular stream can be read from and written to.

The major difference between different stream classes (such as MemoryStream vs FileStream) is the backing store - where the data is read from or where it's written to. It's kind of obvious from the name. A MemoryStream stores the data in memory only, a FileStream is backed by a file on disk, a NetworkStream reads data from the network and so on.

Excel VBA Open workbook, perform actions, save as, close

After discussion posting updated answer:

Option Explicit
Sub test()

    Dim wk As String, yr As String
    Dim fname As String, fpath As String
    Dim owb As Workbook

    With Application
        .DisplayAlerts = False
        .ScreenUpdating = False
        .EnableEvents = False
    End With

    wk = ComboBox1.Value
    yr = ComboBox2.Value
    fname = yr & "W" & wk
    fpath = "C:\Documents and Settings\jammil\Desktop\AutoFinance\ProjectControl\Data"

    On Error GoTo ErrorHandler
    Set owb = Application.Workbooks.Open(fpath & "\" & fname)

    'Do Some Stuff

    With owb
        .SaveAs fpath & Format(Date, "yyyymm") & "DB" & ".xlsx", 51
        .Close
    End With

    With Application
        .DisplayAlerts = True
        .ScreenUpdating = True
        .EnableEvents = True
    End With

Exit Sub
ErrorHandler: If MsgBox("This File Does Not Exist!", vbRetryCancel) = vbCancel Then

Else: Call Clear

End Sub

Error Handling:

You could try something like this to catch a specific error:

    On Error Resume Next
    Set owb = Application.Workbooks.Open(fpath & "\" & fname)
    If Err.Number = 1004 Then
    GoTo FileNotFound
    Else
    End If

    ...
    Exit Sub
    FileNotFound: If MsgBox("This File Does Not Exist!", vbRetryCancel) = vbCancel Then

    Else: Call Clear

Setting focus to iframe contents

This is something that worked for me, although it smells a bit wrong:

var iframe = ...
var doc = iframe.contentDocument;

var i = doc.createElement('input');
i.style.display = 'none'; 
doc.body.appendChild(i);
i.focus();
doc.body.removeChild(i);

hmmm. it also scrolls to the bottom of the content. Guess I should be inserting the dummy textbox at the top.

apply drop shadow to border-top only?

.item .content{
    width: 94.1%;
    background: #2d2d2d;
    padding: 3%;
    border-top: solid 1px #000;
    position: relative;
}
.item .content:before{
      content: "";
      display: block;
      position: absolute;
      top: 0px;
      left: 0;
      width: 100%;
      height: 1px;
      -webkit-box-shadow: 0px 1px 13px rgba(255,255,255,1);
      -moz-box-shadow: 0px 1px 13px rgba(255,255,255,1);
      box-shadow: 0px 1px 13px rgba(255,255,255,1);
      z-index: 100;
}

I am like using something like it for it.

Querying Datatable with where condition

something like this ? :

DataTable dt = ...
DataView dv = new DataView(dt);
dv.RowFilter = "(EmpName != 'abc' or EmpName != 'xyz') and (EmpID = 5)"

Is it what you are searching for?

How to make the corners of a button round?

style button with icon enter image description here

   <Button
        android:id="@+id/buttonVisaProgress"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="5dp"
        android:background="@drawable/shape"
        android:onClick="visaProgress"
        android:drawableTop="@drawable/ic_1468863158_double_loop"
        android:padding="10dp"
        android:text="Visa Progress"
        android:textColor="@android:color/white" />

shape.xml

    <?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="14dp" />
<gradient
    android:angle="45"
    android:centerColor="#1FA8D1"
    android:centerX="35%"
    android:endColor="#060d96"
    android:startColor="#0e7e1d"
    android:type="linear" />
<padding
    android:bottom="0dp"
    android:left="0dp"
    android:right="0dp"
    android:top="0dp" />
<size
    android:width="270dp"
    android:height="60dp" />
<stroke
    android:width="3dp"
    android:color="#000000" />

How to change the pop-up position of the jQuery DatePicker control

Within Jquery.UI, just update the _checkOffset function, so that viewHeight is added to offset.top, before offset is returned.

_checkOffset: function(inst, offset, isFixed) {
    var dpWidth = inst.dpDiv.outerWidth(),
    dpHeight = inst.dpDiv.outerHeight(),
    inputWidth = inst.input ? inst.input.outerWidth() : 0,
    inputHeight = inst.input ? inst.input.outerHeight() : 0,
    viewWidth = document.documentElement.clientWidth + (isFixed ? 0 : $(document).scrollLeft()),
            viewHeight = document.documentElement.clientHeight + (isFixed ? 0 : ($(document).scrollTop()||document.body.scrollTop));
        offset.left -= (this._get(inst, "isRTL") ? (dpWidth - inputWidth) : 0);
        offset.left -= (isFixed && offset.left === inst.input.offset().left) ? $(document).scrollLeft() : 0;
        offset.top -= (isFixed && offset.top === (inst.input.offset().top + inputHeight)) ? ($(document).scrollTop()||document.body.scrollTop) : 0;

        // now check if datepicker is showing outside window viewport - move to a better place if so.
        offset.left -= Math.min(offset.left, (offset.left + dpWidth > viewWidth && viewWidth > dpWidth) ?
            Math.abs(offset.left + dpWidth - viewWidth) : 0);
        offset.top -= Math.min(offset.top, (offset.top + dpHeight > viewHeight && viewHeight > dpHeight) ?
            Math.abs(dpHeight + inputHeight) : 0);
**offset.top = offset.top + viewHeight;**
        return offset;
    },

Why Git is not allowing me to commit even after configuration?

I had this problem even after setting the config properly. git config

My scenario was issuing git command through supervisor (in Linux). On further debugging, supervisor was not reading the git config from home folder. Hence, I had to set the environment HOME variable in the supervisor config so that it can locate the git config correctly. It's strange that supervisor was not able to locate the git config just from the username configured in supervisor's config (/etc/supervisor/conf.d).

How to clear cache of Eclipse Indigo

If you are asking about cache where eclipse stores your project and workspace information right click on your project(s) and choose refresh. Then go to project in the menu on top of the window and click "clean".

This typically does what you need.

If it does not try to remove project from the workspace (just press "delete" on the project and then say that you DO NOT want to remove the sources). Then open project again.

If this does not work too, do the same with the workspace. If this still does not work, perform fresh checkout of your project from source control and create new workspace.

Well, this should work.

Using std::max_element on a vector<double>

min/max_element return the iterator to the min/max element, not the value of the min/max element. You have to dereference the iterator in order to get the value out and assign it to a double. That is:

cLower = *min_element(C.begin(), C.end());

getting the ng-object selected with ng-change

This is the cleanest way to get a value from an angular select options list (other than The Id or Text). Assuming you have a Product Select like this on your page :

<select ng-model="data.ProductId"
        ng-options="product.Id as product.Name for product in productsList"
        ng-change="onSelectChange()">
</select>

Then in Your Controller set the callback function like so:

    $scope.onSelectChange = function () {
        var filteredData = $scope.productsList.filter(function (response) {
            return response.Id === $scope.data.ProductId;
        })
        console.log(filteredData[0].ProductColor);
    }

Simply Explained: Since the ng-change event does not recognize the option items in the select, we are using the ngModel to filter out the selected Item from the options list loaded in the controller.

Furthermore, since the event is fired before the ngModel is really updated, you might get undesirable results, So a better way would be to add a timeout :

        $scope.onSelectChange = function () {
            $timeout(function () {
            var filteredData = $scope.productsList.filter(function (response) {
                return response.Id === $scope.data.ProductId;
            })
            console.log(filteredData[0].ProductColor);
            }, 100);
        };

How to kill a while loop with a keystroke?

There is a solution that requires no non-standard modules and is 100% transportable

import thread

def input_thread(a_list):
    raw_input()
    a_list.append(True)

def do_stuff():
    a_list = []
    thread.start_new_thread(input_thread, (a_list,))
    while not a_list:
        stuff()

Submit form without page reloading

Here is some jQuery for posting to a php page and getting html back:

$('form').submit(function() {
    $.post('tip.php', function(html) {
       // do what you need in your success callback
    }
    return false;
});

Drop view if exists

Regarding the error

'CREATE VIEW' must be the first statement in a query batch.

Microsoft SQL Server has a quirky reqirement that CREATE VIEW be the only statement in a batch. This is also true of a few other statements, such as CREATE FUNCTION. It is not true of CREATE TABLE, so go figure …

The solution is to send your script to the server in small batches. One way to do this is to select a single statement and execute it. This is clearly inconvenient.

The more convenient solution is to get the client to send the script in small isolated batches.

The GO keyword is not strictly an SQL command, which is why you can’t end it with a semicolon like real SQL commands. Instead it is an instruction to the client to break the script at this point and to send the portion as a batch.

As a result, you end up writing something like:

DROP VIEW IF EXISTS … ;
GO
CREATE VIEW … AS … ;
GO

None of the other database servers I have encountered (PostgreSQL, MySQL, Oracle, SQLite) have this quirk, so the requirement appears to be Microsoft Only.

Verifying a specific parameter with Moq

A simpler way would be to do:

ObjectA.Verify(
    a => a.Execute(
        It.Is<Params>(p => p.Id == 7)
    )
);

.htaccess redirect all pages to new domain

If the new domain you are redirecting your old site to is on a diffrent host, you can simply use a Redirect

Redirect 301 / http://newdomain.com

This will redirect all requests from olddomain to the newdomain .

Redirect directive will not work or may cause a Redirect loop if your newdomain and olddomain both are on same host, in that case you'll need to use mod-rewrite to redirect based on the requested host header.

RewriteEngine on


RewriteCond %{HTTP_HOST} ^(www\.)?olddomain\.com$
RewriteRule ^ http://newdomain.com%{REQUEST_URI} [NE,L,R] 

SQL Insert Multiple Rows

You can use SQL Bulk Insert Statement

BULK INSERT TableName
FROM 'filePath'
WITH
(
  FIELDTERMINATOR = '','',
  ROWTERMINATOR = ''\n'',
  ROWS_PER_BATCH = 10000, 
  FIRSTROW = 2,
  TABLOCK
)

for more reference check

https://www.google.co.in/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=sql%20bulk%20insert

You Can Also Bulk Insert Your data from Code as well

for that Please check below Link:

http://www.codeproject.com/Articles/439843/Handling-BULK-Data-insert-from-CSV-to-SQL-Server

Element-wise addition of 2 lists?

Perhaps this is pythonic and slightly useful if you have an unknown number of lists, and without importing anything.

As long as the lists are of the same length, you can use the below function.

Here the *args accepts a variable number of list arguments (but only sums the same number of elements in each).

The * is used again in the returned list to unpack the elements in each of the lists.

def sum_lists(*args):
    return list(map(sum, zip(*args)))

a = [1,2,3]
b = [1,2,3]  

sum_lists(a,b)

Output:

[2, 4, 6]

Or with 3 lists

sum_lists([5,5,5,5,5], [10,10,10,10,10], [4,4,4,4,4])

Output:

[19, 19, 19, 19, 19]

How to change string into QString?

Alternative way:

std::string s = "This is an STL string";
QString qs = QString::fromAscii(s.data(), s.size());

This has the advantage of not using .c_str() which might cause the std::string to copy itself in case there is no place to add the '\0' at the end.

Python: finding lowest integer

Or no float conversion at all by just specifying floats in the list.

l = [-1.2, 0.0, 1]
x = min(l)

or

l = min([-1.2, 0.0, 1])

Throw keyword in function's signature

The only practical effect of the throw specifier is that if something different from myExc is thrown by your function, std::unexpected will be called (instead of the normal unhandled exception mechanism).

To document the kind of exceptions that a function can throw, I typically do this:

bool
some_func() /* throw (myExc) */ {
}

How to get the employees with their managers

You could have just changed your query to:

SELECT ename, empno, (SELECT ename FROM EMP WHERE empno = e.mgr)AS MANAGER, mgr 
from emp e 
order by empno;

This would tell the engine that for the inner emp table, empno should be matched with mgr column from the outer table. enter image description here

JavaScript DOM: Find Element Index In Container

You could make usage of Array.prototype.indexOf. For that, we need to somewhat "cast" the HTMLNodeCollection into a true Array. For instance:

var nodes = Array.prototype.slice.call( document.getElementById('list').children );

Then we could just call:

nodes.indexOf( liNodeReference );

Example:

_x000D_
_x000D_
var nodes = Array.prototype.slice.call( document.getElementById('list').children ),_x000D_
    liRef = document.getElementsByClassName('match')[0];_x000D_
_x000D_
console.log( nodes.indexOf( liRef ) );
_x000D_
<ul id="list">_x000D_
    <li>foo</li>_x000D_
    <li class="match">bar</li>_x000D_
    <li>baz</li>    _x000D_
</ul>
_x000D_
_x000D_
_x000D_

CSS image resize percentage of itself?

Although it does not answer the question directly, one way to scale images is relative to the size (especially width) of the viewport, which is mostly the use case for responsive design. No wrapper elements needed.

_x000D_
_x000D_
img {
    width: 50vw;
}
_x000D_
<img src="" />
_x000D_
_x000D_
_x000D_

else & elif statements not working in Python

It looks like you are entering a blank line after the body of the if statement. This is a cue to the interactive compiler that you are done with the block entirely, so it is not expecting any elif/else blocks. Try entering the code exactly like this, and only hit enter once after each line:

if guess == number:
    print('Congratulations! You guessed it.')
elif guess < number:
    pass # Your code here
else:
    pass # Your code here

python's re: return True if string contains regex pattern

You can do something like this:

Using search will return a SRE_match object, if it matches your search string.

>>> import re
>>> m = re.search(u'ba[r|z|d]', 'bar')
>>> m
<_sre.SRE_Match object at 0x02027288>
>>> m.group()
'bar'
>>> n = re.search(u'ba[r|z|d]', 'bas')
>>> n.group()

If not, it will return None

Traceback (most recent call last):
  File "<pyshell#17>", line 1, in <module>
    n.group()
AttributeError: 'NoneType' object has no attribute 'group'

And just to print it to demonstrate again:

>>> print n
None

Reminder - \r\n or \n\r?

\r\n for Windows will do just fine.

String.Format for Hex

The number 0 in {0:X} refers to the position in the list or arguments. In this case 0 means use the first value, which is Blue. Use {1:X} for the second argument (Green), and so on.

colorstring = String.Format("#{0:X}{1:X}{2:X}{3:X}", Blue, Green, Red, Space);

The syntax for the format parameter is described in the documentation:

Format Item Syntax

Each format item takes the following form and consists of the following components:

{ index[,alignment][:formatString]}

The matching braces ("{" and "}") are required.

Index Component

The mandatory index component, also called a parameter specifier, is a number starting from 0 that identifies a corresponding item in the list of objects. That is, the format item whose parameter specifier is 0 formats the first object in the list, the format item whose parameter specifier is 1 formats the second object in the list, and so on.

Multiple format items can refer to the same element in the list of objects by specifying the same parameter specifier. For example, you can format the same numeric value in hexadecimal, scientific, and number format by specifying a composite format string like this: "{0:X} {0:E} {0:N}".

Each format item can refer to any object in the list. For example, if there are three objects, you can format the second, first, and third object by specifying a composite format string like this: "{1} {0} {2}". An object that is not referenced by a format item is ignored. A runtime exception results if a parameter specifier designates an item outside the bounds of the list of objects.

Alignment Component

The optional alignment component is a signed integer indicating the preferred formatted field width. If the value of alignment is less than the length of the formatted string, alignment is ignored and the length of the formatted string is used as the field width. The formatted data in the field is right-aligned if alignment is positive and left-aligned if alignment is negative. If padding is necessary, white space is used. The comma is required if alignment is specified.

Format String Component

The optional formatString component is a format string that is appropriate for the type of object being formatted. Specify a standard or custom numeric format string if the corresponding object is a numeric value, a standard or custom date and time format string if the corresponding object is a DateTime object, or an enumeration format string if the corresponding object is an enumeration value. If formatString is not specified, the general ("G") format specifier for a numeric, date and time, or enumeration type is used. The colon is required if formatString is specified.

Note that in your case you only have the index and the format string. You have not specified (and do not need) an alignment component.

How can I insert new line/carriage returns into an element.textContent?

Change the h1.textContent to h1.innerHTML and use <br> to go to the new line.