Programs & Examples On #Ternary operator

A ternary operator is any operator that takes three arguments. For the ternary conditional operator `?`...`:`, use [tag:conditional-operator].

How to write a PHP ternary operator

echo ($result ->vocation == 1) ? 'Sorcerer'
        : ($result->vocation == 2) ? 'Druid'
           :  ($result->vocation == 3) ? 'Paladin'


It’s kind of ugly. You should stick with normal if statements.

Ternary operator in AngularJS templates

  <body ng-app="app">
  <button type="button" ng-click="showme==true ? !showme :showme;message='Cancel Quiz'"  class="btn btn-default">{{showme==true ? 'Cancel Quiz': 'Take a Quiz'}}</button>
    <div ng-show="showme" class="panel panel-primary col-sm-4" style="margin-left:250px;">
      <div class="panel-heading">Take Quiz</div>
      <div class="form-group col-sm-8 form-inline" style="margin-top: 30px;margin-bottom: 30px;">

        <button type="button" class="btn btn-default">Start Quiz</button>

Button toggle and change header of button and show/hide div panel. See the Plunkr

Does Python have a ternary conditional operator?

I find cumbersome the default python syntax val = a if cond else b, so sometimes I do this:

iif = lambda (cond, a, b): a if cond else b
# so I can then use it like:
val = iif(cond, a, b)

Of course, it has the downside of always evaluating both sides (a and b), but the syntax it's way clearer to me

Angularjs if-then-else construction in expression

I am trying to check if a key exist in an array in angular way and landed here on this question. In my Angularjs 1.4 ternary operator worked like below


hence for the array key exist i did a simple JS check

Solution 1 : {{ array['key'] !== undefined ? array['key'] : 'n/a' }}

Solution 2 : {{ "key" in array ? array['key'] : 'n/a' }}

PHP syntax question: What does the question mark and colon mean?

This is the PHP ternary operator (also known as a conditional operator) - if first operand evaluates true, evaluate as second operand, else evaluate as third operand.

Think of it as an "if" statement you can use in expressions. Can be very useful in making concise assignments that depend on some condition, e.g.

$param = isset($_GET['param']) ? $_GET['param'] : 'default';

There's also a shorthand version of this (in PHP 5.3 onwards). You can leave out the middle operand. The operator will evaluate as the first operand if it true, and the third operand otherwise. For example:

$result = $x ?: 'default';

It is worth mentioning that the above code when using i.e. $_GET or $_POST variable will throw undefined index notice and to prevent that we need to use a longer version, with isset or a null coalescing operator which is introduced in PHP7:

$param = $_GET['param'] ?? 'default';

What is the Java ?: operator called and what does it do?

Conditional expressions are in a completely different style, with no explicit if in the statement.

The syntax is: boolean-expression ? expression1 : expression2;

The result of this conditional expression is

expression1 if boolean-expression is true;

otherwise the result is expression2.

Suppose you want to assign the larger number of variable num1 and num2 to max. You can simply write a statement using the conditional expression: max = (num1 > num2) ? num1 : num2;

Note: The symbols ? and : appear together in a conditional expression. They form a conditional operator and also called a ternary operator because it uses three operands. It is the only ternary operator in Java.

cited from: Intro to Java Programming 10th edition by Y. Daniel Liang page 126 - 127

Ternary operation in CoffeeScript

Coffeescript doesn't support javascript ternary operator. Here is the reason from the coffeescript author:

I love ternary operators just as much as the next guy (probably a bit more, actually), but the syntax isn't what makes them good -- they're great because they can fit an if/else on a single line as an expression.

Their syntax is just another bit of mystifying magic to memorize, with no analogue to anything else in the language. The result being equal, I'd much rather have if/elses always look the same (and always be compiled into an expression).

So, in CoffeeScript, even multi-line ifs will compile into ternaries when appropriate, as will if statements without an else clause:

if sunny   

if sunny then go_outside() else read_a_book()

Both become ternaries, both can be used as expressions. It's consistent, and there's no new syntax to learn. So, thanks for the suggestion, but I'm closing this ticket as "wontfix".

Please refer to the github issue:

What is the idiomatic Go equivalent of C's ternary operator?

Suppose you have the following ternary expression (in C):

int a = test ? 1 : 2;

The idiomatic approach in Go would be to simply use an if block:

var a int

if test {
  a = 1
} else {
  a = 2

However, that might not fit your requirements. In my case, I needed an inline expression for a code generation template.

I used an immediately evaluated anonymous function:

a := func() int { if test { return 1 } else { return 2 } }()

This ensures that both branches are not evaluated as well.

Short form for Java if statement

1. You can remove brackets and line breaks.

if (city.getName() != null) name = city.getName(); else name = "N/A";

2. You can use ?: operators in java.


Variable = Condition ? BlockTrue : BlockElse;

So in your code you can do like this:

name = city.getName() == null ? "N/A" : city.getName();

3. Assign condition result for Boolean

boolean hasName = city.getName() != null;

EXTRA: for curious

In some languages based in JAVA like Groovy, you can use this syntax:

name = city.getName() ?: "N/A";

The operator ?: assign the value returned from the variable which we are asking for. In this case, the value of city.getName() if it's not null.

What does '?' do in C++?

You can just rewrite it as:

int qempty(){ return(f==r);}

Which does the same thing as said in the other answers.

What is a Question Mark "?" and Colon ":" Operator Used for?

Thats an if/else statement equilavent to

if(row % 2 == 1){

Conditional statement in a one line lambda function in python?

The right way to do this is simple:

def rate(T):
    if (T > 200):
        return 200*exp(-T)
        return 400*exp(-T)

There is absolutely no advantage to using lambda here. The only thing lambda is good for is allowing you to create anonymous functions and use them in an expression (as opposed to a statement). If you immediately assign the lambda to a variable, it's no longer anonymous, and it's used in a statement, so you're just making your code less readable for no reason.

The rate function defined this way can be stored in an array, passed around, called, etc. in exactly the same way a lambda function could. It'll be exactly the same (except a bit easier to debug, introspect, etc.).

From a comment:

Well the function needed to fit in one line, which i didn't think you could do with a named function?

I can't imagine any good reason why the function would ever need to fit in one line. But sure, you can do that with a named function. Try this in your interpreter:

>>> def foo(x): return x + 1

Also these functions are stored as strings which are then evaluated using "eval" which i wasn't sure how to do with regular functions.

Again, while it's hard to be 100% sure without any clue as to why why you're doing this, I'm at least 99% sure that you have no reason or a bad reason for this. Almost any time you think you want to pass Python functions around as strings and call eval so you can use them, you actually just want to pass Python functions around as functions and use them as functions.

But on the off chance that this really is what you need here: Just use exec instead of eval.

You didn't mention which version of Python you're using. In 3.x, the exec function has the exact same signature as the eval function:

exec(my_function_string, my_globals, my_locals)

In 2.7, exec is a statement, not a function—but you can still write it in the same syntax as in 3.x (as long as you don't try to assign the return value to anything) and it works.

In earlier 2.x (before 2.6, I think?) you have to do it like this instead:

exec my_function_string in my_globals, my_locals

How do I use the ternary operator ( ? : ) in PHP as a shorthand for "if / else"?

There's also a shorthand ternary operator and it looks like this:

(expression1) ?: expression2 will return expression1 if it evaluates to true or expression2 otherwise.


$a = 'Apples';
echo ($a ?: 'Oranges') . ' are great!';

will return

Apples are great!

Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.

From the PHP Manual

One-line list comprehension: if-else variants

I was able to do this

>>> [x if x % 2 != 0 else x * 100 for x in range(1,10)]
    [1, 200, 3, 400, 5, 600, 7, 800, 9]

Ternary operator in PowerShell

If you're just looking for a syntactically simple way to assign/return a string or numeric based on a boolean condition, you can use the multiplication operator like this:

"Condition is "+("true"*$condition)+("false"*!$condition)

If you're only ever interested in the result when something is true, you can just omit the false part entirely (or vice versa), e.g. a simple scoring system:

$isTall = $true
$isDark = $false
$isHandsome = $true

$score = (2*$isTall)+(4*$isDark)+(10*$isHandsome)
"Score = $score"
# or
# "Score = $((2*$isTall)+(4*$isDark)+(10*$isHandsome))"

Note that the boolean value should not be the leading term in the multiplication, i.e. $condition*"true" etc. won't work.

?: ?? Operators Instead Of IF|ELSE

The ternary operator (?:) is not designed for control flow, it's only designed for conditional assignment. If you need to control the flow of your program, use a control structure, such as if/else.

PHP ternary operator vs null coalescing operator

Null Coalescing operator performs just two tasks: it checks whether the variable is set and whether it is null. Have a look at the following example:

# case 1:
$greeting = 'Hola';
echo $greeting ?? 'Hi There'; # outputs: 'Hola'

# case 2:
$greeting = null;
echo $greeting ?? 'Hi There'; # outputs: 'Hi There'

# case 3:
echo $greeting ?? 'Hi There'; # outputs: 'Hi There'

The above code example states that Null Coalescing operator treats a non-existing variable and a variable which is set to NULL in the same way.

Null Coalescing operator is an improvement over the ternary operator. Have a look at the following code snippet comparing the two:

<?php /* example: checking for the $_POST field that goes by the name of 'fullname'*/
# in ternary operator
echo "Welcome ", (isset($_POST['fullname']) && !is_null($_POST['fullname']) ? $_POST['fullname'] : 'Mr. Whosoever.'); # outputs: Welcome Mr. Whosoever.
# in null coalecing operator
echo "Welcome ", ($_POST['fullname'] ?? 'Mr. Whosoever.'); # outputs: Welcome Mr. Whosoever.

So, the difference between the two is that Null Coalescing operator operator is designed to handle undefined variables better than the ternary operator. Whereas, the ternary operator is a shorthand for if-else.

Null Coalescing operator is not meant to replace ternary operator, but in some use cases like in the above example, it allows you to write clean code with less hassle.


Omitting the second expression when using the if-else shorthand

Another option:

x === 2 ? doSomething() : void 0;

Putting a simple if-then-else statement on one line

<execute-test-successful-condition> if <test> else <execute-test-fail-condition>

with your code-snippet it would become,

count = 0 if count == N else N + 1

How do I use the conditional operator (? :) in Ruby?

@pst gave a great answer, but I'd like to mention that in Ruby the ternary operator is written on one line to be syntactically correct, unlike Perl and C where we can write it on multiple lines:

(true) ? 1 : 0

Normally Ruby will raise an error if you attempt to split it across multiple lines, but you can use the \ line-continuation symbol at the end of a line and Ruby will be happy:

(true)   \
  ? 1    \
  : 0

This is a simple example, but it can be very useful when dealing with longer lines as it keeps the code nicely laid out.

It's also possible to use the ternary without the line-continuation characters by putting the operators last on the line, but I don't like or recommend it:

(true) ?
  1 :

I think that leads to really hard to read code as the conditional test and/or results get longer.

I've read comments saying not to use the ternary operator because it's confusing, but that is a bad reason to not use something. By the same logic we shouldn't use regular expressions, range operators ('..' and the seemingly unknown "flip-flop" variation). They're powerful when used correctly, so we should learn to use them correctly.

Why have you put brackets around true?

Consider the OP's example:

<% question = question.size > 20 ? question.question.slice(0, 20)+"..." : question.question %>

Wrapping the conditional test helps make it more readable because it visually separates the test:

<% question = (question.size > 20) ? question.question.slice(0, 20)+"..." : question.question %>

Of course, the whole example could be made a lot more readable by using some judicious additions of whitespace. This is untested but you'll get the idea:

<% question = (question.size > 20) ? question.question.slice(0, 20) + "..." \
                                   : question.question 

Or, more written more idiomatically:

<% question = if (question.size > 20)
                question.question.slice(0, 20) + "..."

It'd be easy to argument that readability suffers badly from question.question too.

inline conditionals in angular.js

EDIT: 2Toad's answer below is what you're looking for! Upvote that thing

If you're using Angular <= 1.1.4 then this answer will do:

One more answer for this. I'm posting a separate answer, because it's more of an "exact" attempt at a solution than a list of possible solutions:

Here's a filter that will do an "immediate if" (aka iif):

app.filter('iif', function () {
   return function(input, trueValue, falseValue) {
        return input ? trueValue : falseValue;

and can be used like this:

{{foo == "bar" | iif : "it's true" : "no, it's not"}}

How to write an inline IF statement in JavaScript?

If you just want an inline IF (without the ELSE), you can use the logical AND operator:

(a < b) && /*your code*/;

If you need an ELSE also, use the ternary operation that the other people suggested.

The ternary (conditional) operator in C

It's crucial for code obfuscation, like this:

Look->       See?!

Oh, well

HTTP Basic Authentication - what's the expected web browser experience?

WWW-Authenticate header

You may also get this if the server is sending a 401 response code but not setting the WWW-Authenticate header correctly - I should know, I've just fixed that in out own code because VB apps weren't popping up the authentication prompt.

Write variable to file, including name

the repr function will return a string which is the exact definition of your dict (except for the order of the element, dicts are unordered in python). unfortunately, i can't tell a way to automatically get a string which represent the variable name.

>>> dict = {'one': 1, 'two': 2}
>>> repr(dict)
"{'two': 2, 'one': 1}"

writing to a file is pretty standard stuff, like any other file write:

f = open( '', 'w' )
f.write( 'dict = ' + repr(dict) + '\n' )

RGB to hex and hex to RGB

You can try this simple piece of code below.

For HEX to RGB

list($r, $g, $b) = sscanf(#7bde84, "#%02x%02x%02x");
echo $r . "," . $g . "," . $b;

This will return 123,222,132

For RGB to HEX

$rgb = (123,222,132),
$rgbarr = explode(",",$rgb,3);
echo sprintf("#%02x%02x%02x", $rgbarr[0], $rgbarr[1], $rgbarr[2]);

This will return #7bde84

Finding first and last index of some value in a list in Python

Perhaps the two most efficient ways to find the last index:

def rindex(lst, value):
    i = lst.index(value)
    return len(lst) - i - 1
def rindex(lst, value):
    return len(lst) - operator.indexOf(reversed(lst), value) - 1

Both take only O(1) extra space and the two in-place reversals of the first solution are much faster than creating a reverse copy. Let's compare it with the other solutions posted previously:

def rindex(lst, value):
    return len(lst) - lst[::-1].index(value) - 1

def rindex(lst, value):
    return len(lst) - next(i for i, val in enumerate(reversed(lst)) if val == value) - 1

Benchmark results, my solutions are the red and green ones: unshuffled, full range

This is for searching a number in a list of a million numbers. The x-axis is for the location of the searched element: 0% means it's at the start of the list, 100% means it's at the end of the list. All solutions are fastest at location 100%, with the two reversed solutions taking pretty much no time for that, the double-reverse solution taking a little time, and the reverse-copy taking a lot of time.

A closer look at the right end: unshuffled, tail part

At location 100%, the reverse-copy solution and the double-reverse solution spend all their time on the reversals (index() is instant), so we see that the two in-place reversals are about seven times as fast as creating the reverse copy.

The above was with lst = list(range(1_000_000, 2_000_001)), which pretty much creates the int objects sequentially in memory, which is extremely cache-friendly. Let's do it again after shuffling the list with random.shuffle(lst) (probably less realistic, but interesting):

shuffled list, full range

shuffled list, tail part

All got a lot slower, as expected. The reverse-copy solution suffers the most, at 100% it now takes about 32 times (!) as long as the double-reverse solution. And the enumerate-solution is now second-fastest only after location 98%.

Overall I like the operator.indexOf solution best, as it's the fastest one for the last half or quarter of all locations, which are perhaps the more interesting locations if you're actually doing rindex for something. And it's only a bit slower than the double-reverse solution in earlier locations.

All benchmarks done with CPython 3.9.0 64-bit on Windows 10 Pro 1903 64-bit.

Java generics - why is "extends T" allowed but not "implements T"?

The answer is in here :

To declare a bounded type parameter, list the type parameter's name, followed by the extends keyword, followed by its upper bound […]. Note that, in this context, extends is used in a general sense to mean either extends (as in classes) or implements (as in interfaces).

So there you have it, it's a bit confusing, and Oracle knows it.

Uri not Absolute exception getting while calling Restful Webservice

For others who landed in this error and it's not 100% related to the OP question, please check that you are passing the value and it is not null in case of spring-boot: @Value annotation.

initializing strings as null vs. empty string

The default constructor initializes the string to the empty string. This is the more economic way of saying the same thing.

However, the comparison to NULL stinks. That is an older syntax still in common use that means something else; a null pointer. It means that there is no string around.

If you want to check whether a string (that does exist) is empty, use the empty method instead:

if (myStr.empty()) ...

R color scatter plot points based on values

Best thing to do here is to add a column to the data object to represent the point colour. Then update sections of it by filtering.

data<- read.table('sample_data.txtt', header=TRUE,
# Create new column filled with default colour
# Set new column values to appropriate colours
# Plot all points at once, using newly generated colours
plot(data$col_name1,data$col_name2, ylim=c(0,5), col=data$Colour, ylim=c(0,10))

It should be clear how to adapt this for plots with more colours & conditions.

Convert a Python int into a big-endian string of bytes

You can use the struct module:

import struct
print struct.pack('>I', your_int)

'>I' is a format string. > means big endian and I means unsigned int. Check the documentation for more format chars.

NSPhotoLibraryUsageDescription key must be present in Info.plist to use camera roll

i faced the same issue few days earlier for my IONIC 4 Project. when i uploaded my IPA, i got this warnings from App Store Connect.

enter image description here

I fixed the "Missing Purpose String in info.plist" issue, by the following steps. hope it will also work for you.

  1. Goto your "info.plist" file.

enter image description here

  1. Find this key, called Privacy - Photo Library Usage Description. if it's not present there, add a new one and it's value, like below image.

enter image description here


Excel VBA Run-time Error '32809' - Trying to Understand it

In my case following helped:

  1. Save file as .xlsx (macro-free) - all macros would be erased while saving;
  2. Open source file with macros and copy modules to the .xlsx file;
  3. Save file as .xlsm - full recompile performed.

Afterwards everything started working normally. I had file with 200+ sheets and 50+ macros and posting comments in each module didn't help, but this solution worked.

What are the differences between stateless and stateful systems, and how do they impact parallelism?

A stateful server keeps state between connections. A stateless server does not.

So, when you send a request to a stateful server, it may create some kind of connection object that tracks what information you request. When you send another request, that request operates on the state from the previous request. So you can send a request to "open" something. And then you can send a request to "close" it later. In-between the two requests, that thing is "open" on the server.

When you send a request to a stateless server, it does not create any objects that track information regarding your requests. If you "open" something on the server, the server retains no information at all that you have something open. A "close" operation would make no sense, since there would be nothing to close.

HTTP and NFS are stateless protocols. Each request stands on its own.

Sometimes cookies are used to add some state to a stateless protocol. In HTTP (web pages), the server sends you a cookie and then the browser holds the state, only to send it back to the server on a subsequent request.

SMB is a stateful protocol. A client can open a file on the server, and the server may deny other clients access to that file until the client closes it.

How to style a checkbox using CSS

You can use iCheck. It is customized checkboxes and radio buttons for jQuery & Zepto, and maybe it will help you.

Make sure jQuery v1.7+ is loaded before the icheck.js

  1. Choose a color scheme, there are 10 different styles available:
    • Black — minimal.css
    • Red — red.css
    • Green — green.css
    • Blue — blue.css
    • Aero — aero.css
    • Grey — grey.css
    • Orange — orange.css
    • Yellow — yellow.css
    • Pink — pink.css
    • Purple — purple.css
  2. Copy /skins/minimal/ folder and icheck.js file to your site.
  3. Insert before in your HTML (replace your-path and color-scheme):

    <link href="your-path/minimal/color-scheme.css" rel="stylesheet">
    <script src="your-path/icheck.js"></script>

    Example for a Red color scheme:

    <link href="your-path/minimal/red.css" rel="stylesheet">
    <script src="your-path/icheck.js"></script>
  4. Add some checkboxes and radio buttons to your HTML:

    <input type="checkbox">
    <input type="checkbox" checked>
    <input type="radio" name="iCheck">
    <input type="radio" name="iCheck" checked>
  5. Add JavaScript to your HTML to launch iCheck plugin:

            checkboxClass: 'icheckbox_minimal',
            radioClass: 'iradio_minimal',
            increaseArea: '20%' // Optional
  6. For different from black color schemes use this code (example for Red):

            checkboxClass: 'icheckbox_minimal-red',
            radioClass: 'iradio_minimal-red',
            increaseArea: '20%' // Optional
  7. Done

Can you force Vue.js to reload/re-render?

<router-view :key="$route.params.slug" />

just use key with your any params its auto reload children..

Split bash string by newline characters

There is another way if all you want is the text up to the first line feed:



After that y will contain some and nothing else (no line feed).

What is happening here?

We perform a parameter expansion substring removal (${PARAMETER%PATTERN}) for the shortest match up to the first ANSI C line feed ($'\n') and drop everything that follows (*).

perform an action on checkbox checked or unchecked event on html form

    syn<input type="checkbox" name="checkfield" id="g01-01" />


    var _val = $(this).is(':checked') ? 'checked' : 'unchecked';

ImportError: DLL load failed: The specified module could not be found

I had the same issue with importing matplotlib.pylab with Python 3.5.1 on Win 64. Installing the Visual C++ Redistributable für Visual Studio 2015 from this links: fixed the missing DLLs.

I find it better and easier than downloading and pasting DLLs.

Git and nasty "error: cannot lock existing info/refs fatal"

I had this problem, when I was trying to create a new feature branch that contained name of the old branch, e.g. origin - branch1 and I wanted to create branch1-feature. It wasn't possibble, but branch1/feature was already.

How change default SVN username and password to commit changes?

since your local username on your laptop frequently does not match the server's username, you can set this in the ~/.subversion/servers file

Add the server to the [groups] section with a name, then add a section with that name and provide a username.

for example, for a login like [email protected] this is what your config would look like:

exampleserver =

username = me

Doctrine 2: Update query with query builder

With a small change, it worked fine for me


Deserialize from string instead TextReader

public static string XmlSerializeToString(this object objectInstance)
    var serializer = new XmlSerializer(objectInstance.GetType());
    var sb = new StringBuilder();

    using (TextWriter writer = new StringWriter(sb))
        serializer.Serialize(writer, objectInstance);

    return sb.ToString();

public static T XmlDeserializeFromString<T>(this string objectData)
    return (T)XmlDeserializeFromString(objectData, typeof(T));

public static object XmlDeserializeFromString(this string objectData, Type type)
    var serializer = new XmlSerializer(type);
    object result;

    using (TextReader reader = new StringReader(objectData))
        result = serializer.Deserialize(reader);

    return result;

To use it:

//Make XML
var settings = new ObjectCustomerSettings();
var xmlString = settings.XmlSerializeToString();

//Make Object
var settings = xmlString.XmlDeserializeFromString<ObjectCustomerSettings>(); 

Bash or KornShell (ksh)?

For scripts, I always use ksh because it smooths over gotchas.

But I find bash more comfortable for interactive use. For me the emacs key bindings and tab completion are the main benefits. But that's mostly force of habit, not any technical issue with ksh.

How to get the filename without the extension in Java?

Simplest way to get name from relative path or full path is using

import; FilenameUtils.getBaseName(definitionFilePath)

Concatenate columns in Apache Spark DataFrame

One option to concatenate string columns in Spark Scala is using concat.

It is necessary to check for null values. Because if one of the columns is null, the result will be null even if one of the other columns do have information.

Using concat and withColumn:

val newDf =
      when(col("COL1").isNotNull, col("COL1")).otherwise(lit("null")),
      when(col("COL2").isNotNull, col("COL2")).otherwise(lit("null"))))

Using concat and select:

val newDf = df.selectExpr("concat(nvl(COL1, ''), nvl(COL2, '')) as NEW_COLUMN")

With both approaches you will have a NEW_COLUMN which value is a concatenation of the columns: COL1 and COL2 from your original df.

Reload an iframe with jQuery

Here is another way

$( '#iframe' ).attr( 'src', function () { return $( this )[0].src; } );

Recyclerview and handling different type of row inflation

We can achieve multiple view on single RecyclerView from below way :-

Dependencies on Gradle so add below code:-

compile ''
compile ''

RecyclerView in XML


Activity Code

private RecyclerView mRecyclerView;
private CustomAdapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private String[] mDataset = {“Data - one ”, “Data - two”,
    “Showing data three”, “Showing data four”};
private int mDatasetTypes[] = {DataOne, DataTwo, DataThree}; //view types
mRecyclerView = (RecyclerView) findViewById(;
mLayoutManager = new LinearLayoutManager(MainActivity.this);
//Adapter is created in the last step
mAdapter = new CustomAdapter(mDataset, mDataSetTypes);

First XML

<?xml version="1.0" encoding="utf-8"?>
< xmlns:android=""
            android:textColor=“@color/white“ />
            android:textSize="30sp" />

Second XML

<?xml version="1.0" encoding="utf-8"?>
< xmlns:android=""
            android:textColor="@color/white" />
            android:textSize="30sp" />

Third XML

<?xml version="1.0" encoding="utf-8"?>
< xmlns:android=""
            android:text=“DataThree” />
            android:textSize="25sp" />
            android:text=“Show More” />

Now time to make adapter and this is main for showing different -2 view on same recycler view so please check this code focus fully :-

public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {
    private static final String TAG = "CustomAdapter";
    private String[] mDataSet;
    private int[] mDataSetTypes;
    public static final int dataOne = 0;
    public static final int dataTwo = 1;
    public static final int dataThree = 2;
    public static class ViewHolder extends RecyclerView.ViewHolder {
        public ViewHolder(View v) {
    public class DataOne extends ViewHolder {
        TextView temp;
        public DataOne(View v) {
            this.temp = (TextView) v.findViewById(;
    public class DataTwo extends ViewHolder {
        TextView score;
        public DataTwo(View v) {
            this.score = (TextView) v.findViewById(;
    public class DataThree extends ViewHolder {
        TextView headline;
        Button read_more;
        public DataThree(View v) {
            this.headline = (TextView) v.findViewById(;
            this.read_more = (Button) v.findViewById(;
    public CustomAdapter(String[] dataSet, int[] dataSetTypes) {
        mDataSet = dataSet;
        mDataSetTypes = dataSetTypes;
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
        View v;
        if (viewType == dataOne) {
            v = LayoutInflater.from(viewGroup.getContext())
                    .inflate(R.layout.weather_card, viewGroup, false);
            return new DataOne(v);
        } else if (viewType == dataTwo) {
            v = LayoutInflater.from(viewGroup.getContext())
                    .inflate(R.layout.news_card, viewGroup, false);
            return new DataThree(v);
        } else {
            v = LayoutInflater.from(viewGroup.getContext())
                    .inflate(R.layout.score_card, viewGroup, false);
            return new DataTwo(v);
    public void onBindViewHolder(ViewHolder viewHolder, final int position) {
        if (viewHolder.getItemViewType() == dataOne) {
            DataOne holder = (DataOne) viewHolder;
        else if (viewHolder.getItemViewType() == dataTwo) {
            DataThree holder = (DataTwo) viewHolder;
        else {
            DataTwo holder = (DataTwo) viewHolder;
    public int getItemCount() {
        return mDataSet.length;
    public int getItemViewType(int position) {
        return mDataSetTypes[position];

You can check also this link for more information.

How do I pass data between Activities in Android application?

You can use Intent

Intent mIntent = new Intent(FirstActivity.this, SecondActivity.class);
mIntent.putExtra("data", data);

Another way could be using singleton pattern also:

public class DataHolder {

 private static DataHolder dataHolder;
 private List<Model> dataList;

 public void setDataList(List<Model>dataList) {
    this.dataList = dataList;

 public List<Model> getDataList() {
    return dataList;

 public synchronized static DataHolder getInstance() {
    if (dataHolder == null) {
       dataHolder = new DataHolder();
    return dataHolder;

From your FirstActivity

private List<Model> dataList = new ArrayList<>();

On SecondActivity

private List<Model> dataList = DataHolder.getInstance().getDataList();

Perform Button click event when user press Enter key in Textbox

You can try:


    <asp:TextBox ID="TextBox1" runat="server" onKeyDown="submitButton(event)"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />

And javascript:

function submitButton(event) {
        if (event.which == 13) {

Code behind:

protected void Button1_Click(object sender, EventArgs e)
        //load data and fill to gridview
} // fixed the function view for users

Hope this help

UTF-8 output from PowerShell

Set the [Console]::OuputEncoding as encoding whatever you want, and print out with [Console]::WriteLine.

If powershell ouput method has a problem, then don't use it. It feels bit bad, but works like a charm :)

Android TextView Justify Text


We have created a simple class for this. There are currently two methods to achieve what you are looking for. Both require NO WEBVIEW and SUPPORTS SPANNABLES.


SUPPORTS: Android 2.0 to 5.X


// Please visit Github for latest setup instructions.



How can I de-install a Perl module installed via `cpan`?

Since at the time of installing of any module it mainly put corresponding .pm files in respective directories. So if you want to remove module only for some testing purpose or temporarily best is to find the path where module is stored using perldoc -l <MODULE> and then simply move the module from there to some other location. This approach can also be tried as a more permanent solution but i am not aware of any negative consequences as i do it mainly for testing.

Apply a function to every row of a matrix or a data frame

Apply does the job well, but is quite slow. Using sapply and vapply could be useful. dplyr's rowwise could also be useful Let's see an example of how to do row wise product of any data frame.

a = data.frame(t(iris[1:10,1:3]))
vapply(a, prod, 0)
sapply(a, prod)

Note that assigning to variable before using vapply/sapply/ apply is good practice as it reduces time a lot. Let's see microbenchmark results

a = data.frame(t(iris[1:10,1:3]))
b = iris[1:10,1:3]
    apply(b, 1 , prod),
    vapply(a, prod, 0),
    sapply(a, prod) , 
    apply(iris[1:10,1:3], 1 , prod),
    vapply(data.frame(t(iris[1:10,1:3])), prod, 0),
    sapply(data.frame(t(iris[1:10,1:3])), prod) ,
    b %>%  rowwise() %>%
        summarise(p = prod(Sepal.Length,Sepal.Width,Petal.Length))

Have a careful look at how t() is being used

hardcoded string "row three", should use @string resource

You must create them under strings.xml

<string name="close">Close</string>    

You must replace and reference like this


Do not use @strings even though the XML file says strings.xml or else it will not work.

How to create user for a db in postgresql?

From CLI:

$ su - postgres 
$ psql template1
template1=# CREATE USER tester WITH PASSWORD 'test_password';
template1=# GRANT ALL PRIVILEGES ON DATABASE "test_database" to tester;
template1=# \q

PHP (as tested on localhost, it works as expected):

  $connString = 'port=5432 dbname=test_database user=tester password=test_password';
  $connHandler = pg_connect($connString);
  echo 'Connected to '.pg_dbname($connHandler);

Changing default startup directory for command prompt in Windows 7


cmd.exe /k cd c:/

in a text file and save as cmd.bat Clicking this file does the trick. You can pin it to the start menu as well.

To start in a partitioned drive (e.g. D), use

cmd.exe /k d:

Refresh an page on button click

Page reload can be done using javascript code. Use either a HTML button and implement it like...

<input type="button" value="Reload Page" onClick="document.location.reload(true)">

count (non-blank) lines-of-code in bash

rgrep . | wc -l

gives the count of non blank lines in the current working directory.

Insert line break in wrapped cell via code

Just do Ctrl + Enter inside the text box

docker error: /var/run/docker.sock: no such file or directory

On my MAC when I start boot2docker-vm on the terminal using

boot2docker start

I see the following

To connect the Docker client to the Docker daemon, please set:
    export DOCKER_CERT_PATH=
    export DOCKER_TLS_VERIFY=1
    export DOCKER_HOST=tcp://:2376

After setting these environment variables I was able to run the build without the problem.

Update [2016-04-28] If you are using a the recent versions of docker you can do

eval $(docker-machine env) will set the environment

(docker-machine env will print the export statements)

How to state in requirements.txt a direct github source

“Editable” packages syntax can be used in requirements.txt to import packages from a variety of VCS (git, hg, bzr, svn):

-e git://

Also, it is possible to point to particular commit:

-e git://

package does not exist ; in Android studio 0.8

error: package does not exist import;

using jetify helped to solve .

from jcesarmobile' s post --- >

Error: "package* does not exist" This error occurs when some Cordova or Capacitor plugin has old android support dependencies instead of using the new AndroidX equivalent. You should report the issue in the plugin repository so the maintainers can update the plugin to use AndroidX dependencies.

As workaround you can also patch the plugin using jetifier

npm install jetifier

npx jetify

npx cap sync android

How can I set a DateTimePicker control to a specific date?

Can't figure out why, but in some circumstances if you have bound DataTimePicker and BindingSource contol is postioned to a new record, setting to Value property doesn't affect to bound field, so when you try to commit changes via EndEdit() method of BindingSource, you receive Null value doesn't allowed error. I managed this problem setting direct DataRow field.

How do you run multiple programs in parallel from a bash script?

prog1 & 2> .errorprog1.log; prog2 & 2> .errorprog2.log

Redirect errors to separate logs.

how to get current month and year

If you have following two labels:

<asp:Label ID="MonthLabel" runat="server" />
<asp:Label ID="YearLabel" runat="server" />

Than you can use following code just need to set the Text Property for these labels like:

MonthLabel.Text = DateTime.Now.Month.ToString();
YearLabel.Text = DateTime.Now.Year.ToString();

iOS 11, 12, and 13 installed certificates not trusted automatically (self signed)

Recommended solution is to install and trust a self-signed certificate (root). Assuming you created your own CA and the hierarchy of the certificated is correct you don't need to change the server trust evaluation. This is recommended because it doesn't require any changes in the code.

  1. Generate CA and the certificates (you can use openssl: Generating CA and self-signed certificates.
  2. Install root certificate (*.cer file) on the device - you can open it by Safari and it should redirect you to Settings
  3. When the certificated is installed, go to Certificate Trust Settings (Settings > General > About > Certificate Trust Settings) as in MattP answer.

If it is not possible then you need to change server trust evaluation.

More info in this document: Technical Q&A QA1948 HTTPS and Test Servers

How do I run a Python script on my web server?

Very simply, you can rename your Python script to "pythonscript.cgi". Post that in your cgi-bin directory, add the appropriate permissions and browse to it.

This is a great link you can start with.

Here's another good one.

Hope that helps.

EDIT (09/12/2015): The second link has long been removed. Replaced it with one that provides information referenced from the original.

Check if an element contains a class in JavaScript?

The easy and effective solution is trying .contains method.


How can I get city name from a latitude and longitude point?

In case if you don't want to use google geocoding API than you can refer to few other Free APIs for the development purpose. for example i used [mapquest] API in order to get the location name.

you can fetch location name easily by implementing this following function

 const fetchLocationName = async (lat,lng) => {
    await fetch(
      .then((response) => response.json())
      .then((responseJson) => {
          'ADDRESS GEOCODE is BACK!! => ' + JSON.stringify(responseJson),

Echoing the last command run in Bash?

After reading the answer from Gilles, I decided to see if the $BASH_COMMAND var was also available (and the desired value) in an EXIT trap - and it is!

So, the following bash script works as expected:


exit_trap () {
  local lc="$BASH_COMMAND" rc=$?
  echo "Command [$lc] exited with code [$rc]"

trap exit_trap EXIT
set -e

echo "foo"
false 12345
echo "bar"

The output is

Command [false 12345] exited with code [1]

bar is never printed because set -e causes bash to exit the script when a command fails and the false command always fails (by definition). The 12345 passed to false is just there to show that the arguments to the failed command are captured as well (the false command ignores any arguments passed to it)

string sanitizer for filename

This is how you can sanitize for a file system as asked

function filter_filename($name) {
    // remove illegal file system characters
    $name = str_replace(array_merge(
        array_map('chr', range(0, 31)),
        array('<', '>', ':', '"', '/', '\\', '|', '?', '*')
    ), '', $name);
    // maximise filename length to 255 bytes
    $ext = pathinfo($name, PATHINFO_EXTENSION);
    $name= mb_strcut(pathinfo($name, PATHINFO_FILENAME), 0, 255 - ($ext ? strlen($ext) + 1 : 0), mb_detect_encoding($name)) . ($ext ? '.' . $ext : '');
    return $name;

Everything else is allowed in a filesystem, so the question is perfectly answered...

... but it could be dangerous to allow for example single quotes ' in a filename if you use it later in an unsafe HTML context because this absolutely legal filename:

 ' onerror= 'alert(document.cookie).jpg

becomes an XSS hole:

<img src='<? echo $image ?>' />
// output:
<img src=' ' onerror= 'alert(document.cookie)' />

Because of that, the popular CMS software Wordpress removes them, but they covered all relevant chars only after some updates:

$special_chars = array("?", "[", "]", "/", "\\", "=", "<", ">", ":", ";", ",", "'", "\"", "&", "$", "#", "*", "(", ")", "|", "~", "`", "!", "{", "}", "%", "+", chr(0));
// ... a few rows later are whitespaces removed as well ...
preg_replace( '/[\r\n\t -]+/', '-', $filename )

Finally their list includes now most of the characters that are part of the URI rerserved-characters and URL unsafe characters list.

Of course you could simply encode all these chars on HTML output, but most developers and me too, follow the idiom "Better safe than sorry" and delete them in advance.

So finally I would suggest to use this:

function filter_filename($filename, $beautify=true) {
    // sanitize filename
    $filename = preg_replace(
        [<>:"/\\|?*]|            # file system reserved
        [\x00-\x1F]|             # control characters
        [\x7F\xA0\xAD]|          # non-printing characters DEL, NO-BREAK SPACE, SOFT HYPHEN
        [#\[\]@!$&\'()+,;=]|     # URI reserved
        [{}^\~`]                 # URL unsafe characters
        '-', $filename);
    // avoids ".", ".." or ".hiddenFiles"
    $filename = ltrim($filename, '.-');
    // optional beautification
    if ($beautify) $filename = beautify_filename($filename);
    // maximize filename length to 255 bytes
    $ext = pathinfo($filename, PATHINFO_EXTENSION);
    $filename = mb_strcut(pathinfo($filename, PATHINFO_FILENAME), 0, 255 - ($ext ? strlen($ext) + 1 : 0), mb_detect_encoding($filename)) . ($ext ? '.' . $ext : '');
    return $filename;

Everything else that does not cause problems with the file system should be part of an additional function:

function beautify_filename($filename) {
    // reduce consecutive characters
    $filename = preg_replace(array(
        // "file" becomes ""
        '/ +/',
        // "" becomes ""
        // "" becomes ""
    ), '-', $filename);
    $filename = preg_replace(array(
        // "" becomes ""
        // "" becomes ""
    ), '.', $filename);
    // lowercase for windows/unix interoperability
    $filename = mb_strtolower($filename, mb_detect_encoding($filename));
    // ".file-name.-" becomes "file-name"
    $filename = trim($filename, '.-');
    return $filename;

And at this point you need to generate a filename if the result is empty and you can decide if you want to encode UTF-8 characters. But you do not need that as UTF-8 is allowed in all file systems that are used in web hosting contexts.

The only thing you have to do is to use urlencode() (as you hopefully do it with all your URLs) so the filename ???????_???????.jpg becomes this URL as your <img src> or <a href>:

Stackoverflow does that, so I can post this link as a user would do it:

So this is a complete legal filename and not a problem as mentioned in his answer.

Rails 2.3.4 Persisting Model on Validation Failure

In your controller, render the new action from your create action if validation fails, with an instance variable, @car populated from the user input (i.e., the params hash). Then, in your view, add a logic check (either an if block around the form or a ternary on the helpers, your choice) that automatically sets the value of the form fields to the params values passed in to @car if car exists. That way, the form will be blank on first visit and in theory only be populated on re-render in the case of error. In any case, they will not be populated unless @car is set.

Bitbucket fails to authenticate on git pull

If you've changed the password on Windows 10, go to credential manager and update the password:

go to credential manager and update the password

Spring Boot JPA - configuring auto reconnect

I assume that boot is configuring the DataSource for you. In this case, and since you are using MySQL, you can add the following to your up to 1.3

spring.datasource.validationQuery=SELECT 1

As djxak noted in the comment, 1.4+ defines specific namespaces for the four connections pools Spring Boot supports: tomcat, hikari, dbcp, dbcp2 (dbcp is deprecated as of 1.5). You need to check which connection pool you are using and check if that feature is supported. The example above was for tomcat so you'd have to write it as follows in 1.4+:

spring.datasource.tomcat.validationQuery=SELECT 1

Note that the use of autoReconnect is not recommended:

The use of this feature is not recommended, because it has side effects related to session state and data consistency when applications don't handle SQLExceptions properly, and is only designed to be used when you are unable to configure your application to handle SQLExceptions resulting from dead and stale connections properly.

Unable to connect to any of the specified mysql hosts. C# MySQL

using System;
using System.Linq;
using MySql.Data.MySqlClient;

namespace ConsoleApplication1
    class Program
        static void Main(string[] args)

            // add here your connection details
            String connectionString = "Server=localhost;Database=database;Uid=username;Pwd=password;";
                MySqlConnection connection = new MySqlConnection(connectionString);

                Console.WriteLine("MySQL version: " + connection.ServerVersion);
            catch (Exception ex)

make sure your database server is running if its not running then its not able to make connection and bydefault mysql running on 3306 so don't need mention port if same in case of port number is different then we need to mention port

Create a directory if it doesn't exist

Probably the easiest and most efficient way is to use boost and the boost::filesystem functions. This way you can build a directory simply and ensure that it is platform independent.

const char* path = _filePath.c_str();
boost::filesystem::path dir(path);
    std::cerr<< "Directory Created: "<<_filePath<<std::endl;

boost::filesystem::create_directory - documentation

Check if element exists in jQuery

If you have a class on your element, then you can try the following:

if( $('.exists_content').hasClass('exists_content') ){
 //element available

Java :Add scroll into text area

The Easiest way to implement scrollbar using java swing is as below :

  1. Navigate to Design view
  2. right click on textArea
  3. Select surround with JScrollPane

How to efficiently use try...catch blocks in PHP

For posterity sake,the answer maybe too late.You should check for the return value of the variable and throw an exception. In that case you are assured that the program will jump from where the exception is being raised to the catch block. Find below.

   $tableAresults = $dbHandler->doSomethingWithTableA();
   if (!tableAresults) 
     throw new Exception('Problem with tableAresults');

  $tableBresults = $dbHandler->doSomethingElseWithTableB();
   if (!tableBresults) 
     throw new Exception('Problem with tableBresults');
} catch (Exception $e) {
    echo $e->getMessage();


Accessing post variables using Java Servlets

Here's a simple example. I didn't get fancy with the html or the servlet, but you should get the idea.

I hope this helps you out.

<form method="post" action="/myServlet">
<input type="text" name="username" />
<input type="password" name="password" />
<input type="submit" />

Now for the Servlet

import javax.servlet.*;
import javax.servlet.http.*;

public class MyServlet extends HttpServlet {
  public void doPost(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException {

    String userName = request.getParameter("username");
    String password = request.getParameter("password");

(WAMP/XAMP) send Mail using SMTP localhost

You can use this library to send email ,if having issue with local xampp,wamp...

class.phpmailer.php,class.smtp.php Write this code in file where your email function calls


    $mail = new PHPMailer();  
    $mail->SMTPAuth = true;
    $mail->SMTPSecure = "ssl";
    $mail->Host = "";
    $mail->Port = 465;
    $mail->Username = "your email ID";
    $mail->Password = "your email password";
    $fromname = "From Name in Email";

$To = trim($email,"\r\n");
      $tContent   = '';

      $tContent .="<table width='550px' colspan='2' cellpadding='4'>
            <tr><td align='center'><img src='imgpath' width='100' height='100'></td></tr>
            <tr><td height='20'>&nbsp;</td></tr>
                <table cellspacing='1' cellpadding='1' width='100%' height='100%'>
                <tr><td align='center'><h2>YOUR TEXT<h2></td></tr/>
                <tr><td align='center'>Name: ".trim(NAME,"\r\n")."</td></tr>
                <tr><td align='center'>ABCD TEXT: ".$abcd."</td></tr>
      $mail->From = "From email";
      $mail->FromName = $fromname;        
      $mail->Subject = "Your Details."; 
      $mail->Body = $tContent;
      $mail->set('X-Priority', '1'); //Priority 1 = High, 3 = Normal, 5 = low

ImportError: No module named pythoncom

You are missing the pythoncom package. It comes with ActivePython but you can get it separately on GitHub (previously on SourceForge) as part of pywin32.

You can also simply use:

pip install pywin32

How to change the integrated terminal in visual studio code or VSCode

Probably it is too late but the below thing worked for me:

  1. Open Settings --> this will open settings.json
  2. type
  3. Click on {} at the top right corner -- this will open an editor where this setting can be over ridden.
  4. Set the value as C:\\Users\\<user_name>\\Softwares\\Git\\bin\\bash.exe
  5. Click Ctrl + S

Try to open new terminal. It should open in bash editor in integrated mode.

How to use underscore.js as a template engine?

I am giving a very simple example


var data = {site:"mysite",name:"john",age:25};
var template = "Welcome you are at <%=site %>.This has been created by <%=name %> whose age is <%=age%>";
var parsedTemplate = _.template(template,data);

The result would be

Welcome you are at mysite.This has been created by john whose age is 25.

2) This is a template

   <script type="text/template" id="template_1">
       <% _.each(items,function(item,key,arr) { %>
             <span><%= key %></span>
             <span><%= %></span>
             <span><%= item.type %></span>
       <% }); %>

This is html

  <ul id="list_2"></ul>

This is the javascript code which contains json object and putting template into html

   var items = [
      var template = $("#template_1").html();

How to get current date in jquery?

This is what I came up with using only jQuery. It's just a matter of putting the pieces together.

        //Gather date information from local system
        var ThisMonth = new Date().getMonth() + 1;
        var ThisDay = new Date().getDate();
        var ThisYear = new Date().getFullYear();
        var ThisDate = ThisMonth.toString() + "/" + ThisDay.toString() + "/" + ThisYear.toString();

        //Gather time information from local system
        var ThisHour = new Date().getHours();
        var ThisMinute = new Date().getMinutes();
        var ThisTime = ThisHour.toString() + ":" + ThisMinute.toString();

        //Concatenate date and time for date-time stamp
        var ThisDateTime = ThisDate  + " " + ThisTime;

OpenSSL Verify return code: 20 (unable to get local issuer certificate)

I faced the same issue, It got fixed after keeping issuer subject value in the certificate as it is as subject of issuer certificate.

so please check "issuer subject value in the certificate(cert.pem) == subject of issuer (CA.pem)"

openssl verify -CAfile CA.pem cert.pem
cert.pem: OK

How to read integer values from text file

I would use nearly the same way but with list as buffer for read integers:

static Object[] readFile(String fileName) {
    Scanner scanner = new Scanner(new File(fileName));
    List<Integer> tall = new ArrayList<Integer>();
    while (scanner.hasNextInt()) {

    return tall.toArray();

Javascript/Jquery Convert string to array

Since array literal notation is still valid JSON, you can use JSON.parse() to convert that string into an array, and from there, use it's values.

var test = "[1,2]";
parsedTest = JSON.parse(test); //an array [1,2]

//access like and array
console.log(parsedTest[0]); //1
console.log(parsedTest[1]); //2

Converting <br /> into a new line for use in a text area


$var1 = "Line 1 info blah blah <br /> Line 2 info blah blah";
$var1 = str_replace("<br />", "\n", $var1);


<textarea><?php echo $var1; ?></textarea>

Get total number of items on Json object?

That's an Object and you want to count the properties of it.



PHP - find entry by object property from an array of objects

class ArrayUtils
    public static function objArraySearch($array, $index, $value)
        foreach($array as $arrayInf) {
            if($arrayInf->{$index} == $value) {
                return $arrayInf;
        return null;

Using it the way you wanted would be something like:


#1292 - Incorrect date value: '0000-00-00'

The error is because of the sql mode which can be strict mode as per latest MYSQL 5.7 documentation.

For more information read this.

Hope it helps.

substring of an entire column in pandas dataframe

I needed to convert a single column of strings of form nn.n% to float. I needed to remove the % from the element in each row. The attend data frame has two columns.

attend.iloc[:,1:2]=attend.iloc[:,1:2].applymap(lambda x: float(x[:-1]))

Its an extenstion to the original answer. In my case it takes a dataframe and applies a function to each value in a specific column. The function removes the last character and converts the remaining string to float.

How to execute an SSIS package from .NET?

Here's how do to it with the SSDB catalog that was introduced with SQL Server 2012...

using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.SqlClient;

using Microsoft.SqlServer.Management.IntegrationServices;

public List<string> ExecutePackage(string folder, string project, string package)
    // Connection to the database server where the packages are located
    SqlConnection ssisConnection = new SqlConnection(@"Data Source=.\SQL2012;Initial Catalog=master;Integrated Security=SSPI;");

    // SSIS server object with connection
    IntegrationServices ssisServer = new IntegrationServices(ssisConnection);

    // The reference to the package which you want to execute
    PackageInfo ssisPackage = ssisServer.Catalogs["SSISDB"].Folders[folder].Projects[project].Packages[package];

    // Add a parameter collection for 'system' parameters (ObjectType = 50), package parameters (ObjectType = 30) and project parameters (ObjectType = 20)
    Collection<PackageInfo.ExecutionValueParameterSet> executionParameter = new Collection<PackageInfo.ExecutionValueParameterSet>();

    // Add execution parameter (value) to override the default asynchronized execution. If you leave this out the package is executed asynchronized
    executionParameter.Add(new PackageInfo.ExecutionValueParameterSet { ObjectType = 50, ParameterName = "SYNCHRONIZED", ParameterValue = 1 });

    // Add execution parameter (value) to override the default logging level (0=None, 1=Basic, 2=Performance, 3=Verbose)
    executionParameter.Add(new PackageInfo.ExecutionValueParameterSet { ObjectType = 50, ParameterName = "LOGGING_LEVEL", ParameterValue = 3 });

    // Add a project parameter (value) to fill a project parameter
    executionParameter.Add(new PackageInfo.ExecutionValueParameterSet { ObjectType = 20, ParameterName = "MyProjectParameter", ParameterValue = "some value" });

    // Add a project package (value) to fill a package parameter
    executionParameter.Add(new PackageInfo.ExecutionValueParameterSet { ObjectType = 30, ParameterName = "MyPackageParameter", ParameterValue = "some value" });

    // Get the identifier of the execution to get the log
    long executionIdentifier = ssisPackage.Execute(false, null, executionParameter);

    // Loop through the log and do something with it like adding to a list
    var messages = new List<string>();
    foreach (OperationMessage message in ssisServer.Catalogs["SSISDB"].Executions[executionIdentifier].Messages)
        messages.Add(message.MessageType + ": " + message.Message);

    return messages;

The code is a slight adaptation of

There is also a similar article at

What is the difference between MOV and LEA?

It depends on the used assembler, because

mov ax,table_addr

in MASM works as

mov ax,word ptr[table_addr]

So it loads the first bytes from table_addr and NOT the offset to table_addr. You should use instead

mov ax,offset table_addr


lea ax,table_addr

which works the same.

lea version also works fine if table_addr is a local variable e.g.

some_procedure proc

local table_addr[64]:word

lea ax,table_addr

Histogram using gnuplot?

Be very careful: all of the answers on this page are implicitly taking the decision of where the binning starts - the left-hand edge of the left-most bin, if you like - out of the user's hands. If the user is combining any of these functions for binning data with his/her own decision about where binning starts (as is done on the blog which is linked to above) the functions above are all incorrect. With an arbitrary starting point for binning 'Min', the correct function is:

bin(x) = width*(floor((x-Min)/width)+0.5) + Min

You can see why this is correct sequentially (it helps to draw a few bins and a point somewhere in one of them). Subtract Min from your data point to see how far into the binning range it is. Then divide by binwidth so that you're effectively working in units of 'bins'. Then 'floor' the result to go to the left-hand edge of that bin, add 0.5 to go to the middle of the bin, multiply by the width so that you're no longer working in units of bins but in an absolute scale again, then finally add back on the Min offset you subtracted at the start.

Consider this function in action:

Min = 0.25 # where binning starts
Max = 2.25 # where binning ends
n = 2 # the number of bins
width = (Max-Min)/n # binwidth; evaluates to 1.0
bin(x) = width*(floor((x-Min)/width)+0.5) + Min

e.g. the value 1.1 truly falls in the left bin:

  • this function correctly maps it to the centre of the left bin (0.75);
  • Born2Smile's answer, bin(x)=width*floor(x/width), incorrectly maps it to 1;
  • mas90's answer, bin(x)=width*floor(x/width) + binwidth/2.0, incorrectly maps it to 1.5.

Born2Smile's answer is only correct if the bin boundaries occur at (n+0.5)*binwidth (where n runs over integers). mas90's answer is only correct if the bin boundaries occur at n*binwidth.

How to make promises work in IE11

If you want this type of code to run in IE11 (which does not support much of ES6 at all), then you need to get a 3rd party promise library (like Bluebird), include that library and change your coding to use ES5 coding structures (no arrow functions, no let, etc...) so you can live within the limits of what older browsers support.

Or, you can use a transpiler (like Babel) to convert your ES6 code to ES5 code that will work in older browsers.

Here's a version of your code written in ES5 syntax with the Bluebird promise library:

<script src=""></script>


'use strict';

var promise = new Promise(function(resolve) {
    setTimeout(function() {
    }, 1000);

promise.then(function(result) {
    alert("Fulfilled: " + result);
}, function(error) {
    alert("Rejected: " + error);


Calculate distance between 2 GPS coordinates

I needed to implement this in PowerShell, hope it can help someone else. Some notes about this method

  1. Don't split any of the lines or the calculation will be wrong
  2. To calculate in KM remove the * 1000 in the calculation of $distance
  3. Change $earthsRadius = 3963.19059 and remove * 1000 in the calculation of $distance the to calulate the distance in miles
  4. I'm using Haversine, as other posts have pointed out Vincenty's formulae is much more accurate

    Function MetresDistanceBetweenTwoGPSCoordinates($latitude1, $longitude1, $latitude2, $longitude2)  
      $Rad = ([math]::PI / 180);  
      $earthsRadius = 6378.1370 # Earth's Radius in KM  
      $dLat = ($latitude2 - $latitude1) * $Rad  
      $dLon = ($longitude2 - $longitude1) * $Rad  
      $latitude1 = $latitude1 * $Rad  
      $latitude2 = $latitude2 * $Rad  
      $a = [math]::Sin($dLat / 2) * [math]::Sin($dLat / 2) + [math]::Sin($dLon / 2) * [math]::Sin($dLon / 2) * [math]::Cos($latitude1) * [math]::Cos($latitude2)  
      $c = 2 * [math]::ATan2([math]::Sqrt($a), [math]::Sqrt(1-$a))  
      $distance = [math]::Round($earthsRadius * $c * 1000, 0) #Multiple by 1000 to get metres  
      Return $distance  

Retrieve last 100 lines logs

len=`cat filename | wc -l`
len=$(( $len + 1 ))
l=$(( $len - 99 ))
sed -n "${l},${len}p" filename

first line takes the length (Total lines) of file then +1 in the total lines after that we have to fatch 100 records so, -99 from total length then just put the variables in the sed command to fetch the last 100 lines from file

I hope this will help you.

StringLength vs MaxLength attributes ASP.NET MVC with Entity Framework EF Code First

Some quick but extremely useful additional information that I just learned from another post, but can't seem to find the documentation for (if anyone can share a link to it on MSDN that would be amazing):

The validation messages associated with these attributes will actually replace placeholders associated with the attributes. For example:

[MaxLength(100, "{0} can have a max of {1} characters")]
public string Address { get; set; }

Will output the following if it is over the character limit: "Address can have a max of 100 characters"

The placeholders I am aware of are:

  • {0} = Property Name
  • {1} = Max Length
  • {2} = Min Length

Much thanks to bloudraak for initially pointing this out.

How to use pagination on HTML tables?

With Reference to Anusree answer above and with respect,I am tweeking the code little bit to make sure it works in most of the cases.

  1. Created a reusable function paginate('#myTableId') which can be called any number times for any table.
  2. Adding code inside ajaxComplete function to make sure paging is called once table using jquery is completely loaded. We use paging mostly for ajax based tables.
  3. Remove Pagination div and rebind on every pagination call
  4. Configuring Number of rows per page


$(document).ready(function () {
    $(document).ajaxComplete(function () {
        function paginate(tableName,RecordsPerPage) {
            $(tableName).after('<div id="nav"></div>');
            var rowsShown = RecordsPerPage;
            var rowsTotal = $(tableName + ' tbody tr').length;
            var numPages = rowsTotal / rowsShown;
            for (i = 0; i < numPages; i++) {
                var pageNum = i + 1;
                $('#nav').append('<a href="#" rel="' + i + '">' + pageNum + '</a> ');
            $(tableName + ' tbody tr').hide();
            $(tableName + ' tbody tr').slice(0, rowsShown).show();
            $('#nav a:first').addClass('active');
            $('#nav a').bind('click', function () {

                $('#nav a').removeClass('active');
                var currPage = $(this).attr('rel');
                var startItem = currPage * rowsShown;
                var endItem = startItem + rowsShown;
                $(tableName + ' tbody tr').css('opacity', '0.0').hide().slice(startItem, endItem).
                    css('display', 'table-row').animate({ opacity: 1 }, 300);

filters on ng-model in an input

I believe that the intention of AngularJS inputs and the ngModel direcive is that invalid input should never end up in the model. The model should always be valid. The problem with having invalid model is that we might have watchers that fire and take (inappropriate) actions based on invalid model.

As I see it, the proper solution here is to plug into the $parsers pipeline and make sure that invalid input doesn't make it into the model. I'm not sure how did you try to approach things or what exactly didn't work for you with $parsers but here is a simple directive that solves your problem (or at least my understanding of the problem):

app.directive('customValidation', function(){
   return {
     require: 'ngModel',
     link: function(scope, element, attrs, modelCtrl) {

       modelCtrl.$parsers.push(function (inputValue) {

         var transformedInput = inputValue.toLowerCase().replace(/ /g, ''); 

         if (transformedInput!=inputValue) {

         return transformedInput;         

As soon as the above directive is declared it can be used like so:

<input ng-model="sth" ng-trim="false" custom-validation>

As in solution proposed by @Valentyn Shybanov we need to use the ng-trim directive if we want to disallow spaces at the beginning / end of the input.

The advantage of this approach is 2-fold:

  • Invalid value is not propagated to the model
  • Using a directive it is easy to add this custom validation to any input without duplicating watchers over and over again

Using JQuery to open a popup window and print

Are you sure you can't alter the HTML in the popup window?

If you can, add a <script> tag at the end of the popup's HTML, and call window.print() inside it. Then it won't be called until the HTML has loaded.

Function passed as template argument

The reason your functor example does not work is that you need an instance to invoke the operator().

How to open an existing project in Eclipse?

If you are trying to import non maven project into eclipse follow the below steps, it worked for me.

first clone project into your machine and follow the below steps to import in eclipse.

Project Explorer -> import -> Git -> Projects from git -> Existing Local repository -> Add -> select project root directory -> (check box) import as general project -> next -> finish


Displaying output of a remote command with Ansible

If you pass the -v flag to the ansible-playbook command, then ansible will show the output on your terminal.

For your use case, you may want to try using the fetch module to copy the public key from the server to your local machine. That way, it will only show a "changed" status when the file changes.

LINQ: Select an object and change some properties without creating a new object

If you want to update items with a Where clause, using a .Where(...) will truncate your results if you do:

mylist = mylist.Where(n => n.Id == ID).Select(n => { n.Property = ""; return n; }).ToList();

You can do updates to specific item(s) in the list like so:

mylist = mylist.Select(n => { if (n.Id == ID) { n.Property = ""; } return n; }).ToList();

Always return item even if you don't make any changes. This way it will be kept in the list.

Bootstrap: adding gaps between divs

Starting from Bootstrap v4 you can simply add the following to your div class attribute: mt-2 (margin top 2)

<div class="mt-2 col-md-12">
        This will have a two-point top margin!

More examples are given in the docs: Bootstrap v4 docs

Finding the average of an array using JS

Writing the function for average yourself is crazy. That's why modules exist. I found math.js

In my HTML file:

  <script src=""></script>

(or you can download it)

In my JS code:

math.mean([1,2,3]) // =2
math.mean(1,2,3) // the same

turn typescript object into json string

If you're using fs-extra, you can skip the JSON.stringify part with the writeJson function:

const fsExtra = require('fs-extra');

fsExtra.writeJson('./package.json', {name: 'fs-extra'})
.then(() => {
.catch(err => {

Groovy - Convert object to JSON string

I couldn't get the other answers to work within the evaluate console in Intellij so...


This works quite well, but unfortunately


didn't work for me.

To get it pretty printed I had to do this...


How to embed an autoplaying YouTube video in an iframe?

2014 iframe embed on how to embed a youtube video with autoplay and no suggested videos at end of clip


Example Below: .

<iframe width="640" height="360" src="//;autoplay=1" frameborder="0" allowfullscreen></iframe>

Difference between numeric, float and decimal in SQL Server

They Differ in Data Type Precedence

Decimal and Numeric are the same functionally but there is still data type precedence, which can be crucial in some cases.


The resulting data type is numeric because it takes data type precedence.

Exhaustive list of data types by precedence:

Reference link

Python unexpected EOF while parsing

I'm trying to answer in general, not related to this question, this error generally occurs when you break a syntax in half and forget the other half. Like in my case it was:

try :

since python was searching for a

except Exception as e:

but it encountered an EOF (End Of File), hence the error. See if you can find any incomplete syntax in your code.

How to keep indent for second line in ordered lists via CSS?

The easiest and cleanest way, without any hacks, is to just to indent the ul (or ol), like so:

ol {
  padding-left: 40px; // Or whatever padding your font size needs

This gives the same result as the accepted answer:


enter image description here

How to restart Activity in Android

In conjunction with strange SurfaceView lifecycle behaviour with the Camera. I have found that recreate() does not behave well with the lifecycle of SurfaceViews. surfaceDestroyed isn't ever called during the recreation cycle. It is called after onResume (strange), at which point my SurfaceView is destroyed.

The original way of recreating an activity works fine.

Intent intent = getIntent();

I can't figure out exactly why this is, but it is just an observation that can hopefully guide others in the future because it fixed my problems i was having with SurfaceViews

Border around specific rows in a table?

If you set the border-collapse style to collapse on the parent table you should be able to style the tr: (styles are inline for demo)

<table style="border-collapse: collapse;">
    <td>No Border</td>
  <tr style="border:2px solid #f00;">
    <td>No Border</td>


HTML output

How to iterate over rows in a DataFrame in Pandas

You can also use df.apply() to iterate over rows and access multiple columns for a function.

docs: DataFrame.apply()

def valuation_formula(x, y):
    return x * y * 0.5

df['price'] = df.apply(lambda row: valuation_formula(row['x'], row['y']), axis=1)

smtp configuration for php mail

Since some of the answers give here relate to setting up SMTP in general (and not just for @shinod particular issue where it had been working and stopped), I thought it would be helpful if I updated the answer because this is a lot simpler to do now than it used to be :-)

In PHP 4 the PEAR Mail package is typically already installed, and this really simple tutorial shows you the few lines of code that you need to add to your php file

Most hosting companies list the SMTP settings that you'll need. I use JustHost, and they list theirs at (under Outgoing Mail Server)

Sorting a DropDownList? - C#, ASP.NET

If you get a DataTable with the data, you can create a DataView off of this and then bind the drop down list to that. Your code would look something like...

DataView dvOptions = new DataView(DataTableWithOptions);
dvOptions.Sort = "Description";

ddlOptions.DataSource = dvOptions;
ddlOptions.DataTextField = "Description";
ddlOptions.DataValueField = "Id";

Your text field and value field options are mapped to the appropriate columnns in the data table you are receiving.

How to create a JSON object

$post_data = [
  "item" => [
    'item_type_id' => $item_type,
    'string_key' => $string_key,
    'string_value' => $string_value,
    'string_extra' => $string_extra,
    'is_public' => $public,
    'is_public_for_contacts' => $public_contacts

$post_data = json_encode(post_data);
$post_data = json_decode(post_data);
return $post_data;

Amazon S3 upload file and get URL

To make the file public before uploading you can use the #withCannedAcl method of PutObjectRequest:

myAmazonS3Client.putObject(new PutObjectRequest('some-grails-bucket',  'somePath/someKey.jpg', new    File('/Users/ben/Desktop/photo.jpg')).withCannedAcl(CannedAccessControlList.PublicRead))

Add class to <html> with Javascript?

This should also work:

document.documentElement.className = 'myClass';



IE 10 reckons it's readonly; yet:

It worked!?

Opera works:


I can also confirm it works in:

  • Chrome 26
  • Firefox 19.02
  • Safari 5.1.7

How to make JavaScript execute after page load?

Just define <body onload="aFunction()"> that will be called after the page has been loaded. Your code in the script is than enclosed by aFunction() { }.

What's the difference between “mod” and “remainder”?

In mathematics the result of the modulo operation is the remainder of the Euclidean division. However, other conventions are possible. Computers and calculators have various ways of storing and representing numbers; thus their definition of the modulo operation depends on the programming language and/or the underlying hardware.

 7 modulo  3 -->  1  
 7 modulo -3 --> -2 
-7 modulo  3 -->  2  
-7 modulo -3 --> -1 

Searching word in vim?

like this:


\< means beginning of a word, and \> means the end of a word,

Adding @Roe's comment:
VIM provides a shortcut for this. If you already have word on screen and you want to find other instances of it, you can put the cursor on the word and press '*' to search forward in the file or '#' to search backwards.

What does ||= (or-equals) mean in Ruby?

||= is called a conditional assignment operator.

It basically works as = but with the exception that if a variable has already been assigned it will do nothing.

First example:

x ||= 10

Second example:

x = 20
x ||= 10

In the first example x is now equal to 10. However, in the second example x is already defined as 20. So the conditional operator has no effect. x is still 20 after running x ||= 10.

".addEventListener is not a function" why does this error occur?

Try this one:

var comment = document.querySelector("button");
function showComment() {
  var place = document.querySelector('#textfield');
  var commentBox = document.createElement('textarea');
comment.addEventListener('click', showComment, false);

Use querySelector instead of className

Difference between number and integer datatype in oracle dictionary views

This is what I got from oracle documentation, but it is for oracle 10g release 2:

When you define a NUMBER variable, you can specify its precision (p) and scale (s) so that it is sufficiently, but not unnecessarily, large. Precision is the number of significant digits. Scale can be positive or negative. Positive scale identifies the number of digits to the right of the decimal point; negative scale identifies the number of digits to the left of the decimal point that can be rounded up or down.

The NUMBER data type is supported by Oracle Database standard libraries and operates the same way as it does in SQL. It is used for dimensions and surrogates when a text or INTEGER data type is not appropriate. It is typically assigned to variables that are not used for calculations (like forecasts and aggregations), and it is used for variables that must match the rounding behavior of the database or require a high degree of precision. When deciding whether to assign the NUMBER data type to a variable, keep the following facts in mind in order to maximize performance:

  • Analytic workspace calculations on NUMBER variables is slower than other numerical data types because NUMBER values are calculated in software (for accuracy) rather than in hardware (for speed).
  • When data is fetched from an analytic workspace to a relational column that has the NUMBER data type, performance is best when the data already has the NUMBER data type in the analytic workspace because a conversion step is not required.

VarBinary vs Image SQL Server Data Type to Store Binary Data?


Variable-length binary data from 0 through 2^31-1 (2,147,483,647) bytes. Still it IS supported to use image datatype, but be aware of:

varbinary [ ( n | max) ]

Variable-length binary data. n can be a value from 1 through 8,000. max indicates that the maximum storage size is 2^31-1 bytes. The storage size is the actual length of the data entered + 2 bytes. The data that is entered can be 0 bytes in length. The ANSI SQL synonym for varbinary is binary varying.

So both are equally in size (2GB). But be aware of:

Though the end of "image" datatype is still not determined, you should use the "future" proof equivalent.

But you have to ask yourself: why storing BLOBS in a Column?

How to append output to the end of a text file

Use the >> operator to append text to a file.

jQuery override default validation error message display (Css) Popup/Tooltip like

Add following css to your .validate method to change the css or functionality

 errorElement: "div",
    wrapper: "div",
    errorPlacement: function(error, element) {
        offset = element.offset();

How to assign a select result to a variable?

I just had the same problem and...

declare @userId uniqueidentifier
set @userId = (select top 1 UserId from aspnet_Users)

or even shorter:

declare @userId uniqueidentifier
SELECT TOP 1 @userId = UserId FROM aspnet_Users

Checking for multiple conditions using "when" on single task in ansible

The problem with your conditional is in this part sshkey_result.rc == 1, because sshkey_result does not contain rc attribute and entire conditional fails.

If you want to check if file exists check exists attribute.

Here you can read more about stat module and how to use it.

What linux shell command returns a part of a string?

expr(1) has a substr subcommand:

expr substr <string> <start-index> <length>

This may be useful if you don't have bash (perhaps embedded Linux) and you don't want the extra "echo" process you need to use cut(1).

Avoid line break between html elements

If you need this for several words or elements, but can't apply it to a whole TD or similar, the Span tag can be used.

<span style="white-space: nowrap">Text to break together</span>
<span class=nobr>Text to break together</span>

If you use the class version, remember to set up the CSS as detailed in the accepted answer.

Set variable with multiple values and use IN

You need a table variable:

declare @values table
    Value varchar(1000)

insert into @values values ('A')
insert into @values values ('B')
insert into @values values ('C')

select blah
from foo
where myField in (select value from @values)

Core Data: Quickest way to delete all instances of an entity

in iOS 11.3 and Swift 4.1

let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
        let batchDeleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest )
        batchDeleteRequest.resultType = .resultTypeCount
        do {
            let batchDeleteResult = try dataController.viewContext.execute(batchDeleteRequest) as! NSBatchDeleteResult
            print("The batch delete request has deleted \(batchDeleteResult.result!) records.")
            dataController.viewContext.reset() // reset managed object context (need it for working)
        } catch {
            let updateError = error as NSError
            print("\(updateError), \(updateError.userInfo)")

you have to call reset after you do execute. If not, it will not update on the table view.

Possible to iterate backwards through a foreach?

As 280Z28 says, for an IList<T> you can just use the index. You could hide this in an extension method:

public static IEnumerable<T> FastReverse<T>(this IList<T> items)
    for (int i = items.Count-1; i >= 0; i--)
        yield return items[i];

This will be faster than Enumerable.Reverse() which buffers all the data first. (I don't believe Reverse has any optimisations applied in the way that Count() does.) Note that this buffering means that the data is read completely when you first start iterating, whereas FastReverse will "see" any changes made to the list while you iterate. (It will also break if you remove multiple items between iterations.)

For general sequences, there's no way of iterating in reverse - the sequence could be infinite, for example:

public static IEnumerable<T> GetStringsOfIncreasingSize()
    string ret = "";
    while (true)
        yield return ret;
        ret = ret + "x";

What would you expect to happen if you tried to iterate over that in reverse?

How do I escape spaces in path for scp copy in Linux?

Use 3 backslashes to escape spaces in names of directories:

scp user@host:/path/to/directory\\\ with\\\ spaces/file ~/Downloads

should copy to your Downloads directory the file from the remote directory called directory with spaces.

Where to find Java JDK Source Code?

Yes!! Got it!

I downloaded the Java Developer Kit (JDK) from for Linux. There was in. But first I uninstalled all Java packages with synaptic.

Merge (Concat) Multiple JSONObjects in Java

This is what I do

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

 * This class has all static functions to merge 2 objects into one
public class MergeHelper {
    private static ObjectMapper objectMapper = new ObjectMapper();

     * return a merge JsonNode, merge newJson into oldJson; override or insert
     * fields from newJson into oldJson
     * @param oldJson
     * @param newJson
     * @return
    public static JsonNode mergeJsonObject(JsonNode oldJson, JsonNode newJson) {
        ObjectNode merged = objectMapper.createObjectNode();
        merged.setAll((ObjectNode) oldJson);
        merged.setAll((ObjectNode) newJson);
        return merged;

How to set ID using javascript?

Do you mean like this?

var hello1 = document.getElementById('hello1'); = btoa(;

To further the example, say you wanted to get all elements with the class 'abc'. We can use querySelectorAll() to accomplish this:


<div class="abc"></div>
<div class="abc"></div>


var abcElements = document.querySelectorAll('.abc');

// Set their ids
for (var i = 0; i < abcElements.length; i++)
    abcElements[i].id = 'abc-' + i;

This will assign the ID 'abc-<index number>' to each element. So it would come out like this:

<div class="abc" id="abc-0"></div>
<div class="abc" id="abc-1"></div>

To create an element and assign an id we can use document.createElement() and then appendChild().

var div = document.createElement('div'); = 'hello1';

var body = document.querySelector('body');


You can set the id on your element like this if your script is in your HTML file.

<input id="{{str(product["avt"]["fto"])}}" >
<span>New price :</span>
<span class="assign-me">

<script type="text/javascript">
    var s = document.getElementsByClassName('assign-me')[0]; = btoa({{str(produit["avt"]["fto"])}});

Your requirements still aren't 100% clear though.

How can I get a process handle by its name in C++?

OpenProcess Function

From MSDN:

To open a handle to another local process and obtain full access rights, you must enable the SeDebugPrivilege privilege.

Count the number of Occurrences of a Word in a String

StringUtils in apache commons-lang have CountMatches method to counts the number of occurrences of one String in another.

   String input = "i have a male cat. the color of male cat is Black";
   int occurance = StringUtils.countMatches(input, "male cat");

JsonParseException : Illegal unquoted character ((CTRL-CHAR, code 10)

This can happen if you have a newline (or other control character) in a JSON string literal.

{"foo": "bar

If you are the one producing the data, replace actual newlines with escaped ones "\\n" when creating your string literals.

{"foo": "bar\nbaz"}

jQuery date formatting

I'm not quite sure if I'm allowed to answer a question that was asked like 2 years ago as this is my first answer on stackoverflow but, here's my solution;

If you once retrieved the date from your MySQL database, split it and then use the splitted values.

$(document).ready(function () {
    var datefrommysql = $('.date-from-mysql').attr("date");
    var arraydate = datefrommysql.split('.');
    var yearfirstdigit = arraydate[2][2];
    var yearlastdigit = arraydate[2][3];
    var day = arraydate[0];
    var month = arraydate[1];
    $('.formatted-date').text(day + "/" + month + "/" + yearfirstdigit + yearlastdigit);

Here's a fiddle.

What is the difference between Bower and npm?

Found this useful explanation from

On one hand npm was created to install modules used in a node.js environment, or development tools built using node.js such Karma, lint, minifiers and so on. npm can install modules locally in a project ( by default in node_modules ) or globally to be used by multiple projects. In large projects the way to specify dependencies is by creating a file called package.json which contains a list of dependencies. That list is recognized by npm when you run npm install, which then downloads and installs them for you.

On the other hand bower was created to manage your frontend dependencies. Libraries like jQuery, AngularJS, underscore, etc. Similar to npm it has a file in which you can specify a list of dependencies called bower.json. In this case your frontend dependencies are installed by running bower install which by default installs them in a folder called bower_components.

As you can see, although they perform a similar task they are targeted to a very different set of libraries.

How can I limit the visible options in an HTML <select> dropdown?

A minor but important modification to existing solutions aiming at preserving framework styling (i.e. Bootstrap): replace this.size=0 with this.removeAttribute('size').

<select class="custom-select" onmousedown="if(this.options.length>5){this.size=5}"
    onchange='this.blur()' onblur="this.removeAttribute('size')">

Turn off warnings and errors on PHP and MySQL

Always show errors on a testing server. Never show errors on a production server.

Write a script to determine whether the page is on a local, testing, or live server, and set $state to "local", "testing", or "live". Then:

if( $state == "local" || $state == "testing" )
    ini_set( "display_errors", "1" );
    error_reporting( E_ALL & ~E_NOTICE );
    error_reporting( 0 );

Changing SqlConnection timeout

I found an excellent blogpost on this subject:

Basically, you either set Connect Timeout in the connection string, or you set ConnectionTimeout on the command object.

Be aware that the timeout time is in seconds.

How to split page into 4 equal parts?

Similar to other posts, but with an important distinction to make this work inside a div. The simpler answers aren't very copy-paste-able because they directly modify div or draw over the entire page.

The key here is that the containing div dividedbox has relative positioning, allowing it to sit nicely in your document with the other elements, while the quarters within have absolute positioning, giving you vertical/horizontal control inside the containing div.

As a bonus, text is responsively centered in the quarters.


  <meta charset="utf-8">
  <title>Box model</title>
  <link rel="stylesheet" href="style.css">

  <h1 id="title">Title Bar</h1>
  <div id="dividedbox">
    <div class="quarter" id="NW">
    <div class="quarter" id="NE">
    <div class="quarter" id="SE">
    <div class="quarter" id="SW">



html, body { height:95%;} /* Important to make sure your divs have room to grow in the document */
#title { background: lightgreen}
#dividedbox { position: relative; width:100%; height:95%}   /* for div growth */
.quarter {position: absolute; width:50%; height:50%;  /* gives quarters their size */
  display: flex; justify-content: center; align-items: center;} /* centers text */
#NW { top:0;    left:0;     background:orange;     }
#NE { top:0;    left:50%;   background:lightblue;  }
#SW { top:50%;  left:0;     background:green;      }
#SE { top:50%;  left:50%;   background:red;        }

Django datetime issues (

From the Python language reference, under Function definitions:

Default parameter values are evaluated when the function definition is executed. This means that the expression is evaluated once, when the function is defined, and that that same “pre-computed” value is used for each call.

Fortunately, Django has a way to do what you want, if you use the auto_now argument for the DateTimeField:

date = models.DateTimeField(auto_now=True)

See the Django docs for DateTimeField.

Drag and drop a DLL to the GAC ("assembly") in windows server 2008 .net 4.0

In .net 4.0 Microsoft removed the ability to add DLLs to the Assembly simply by dragging and dropping.

Instead you need to use gacutil.exe, or create an installer to do it. Microsoft actually doesn’t recommend using gacutil, but I went that route anyway.

To use gacutil on a development machine go to:
Start -> programs -> Microsoft Visual studio 2010 -> Visual Studio Tools -> Visual Studio Command Prompt (2010)

Then use these commands to uninstall and Reinstall respectively. Note I did NOT include .dll in the uninstall command.
gacutil /u myDLL
gacutil /i "C:\Program Files\Custom\myDLL.dll"

To use Gacutil on a non-development machine you will have to copy the executable and config file from your dev machine to the production machine. It looks like there are a few different versions of Gacutil. The one that worked for me, I found here:
C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\NETFX 4.0 Tools\gacutil.exe C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\NETFX 4.0 Tools\gacutil.exe.config

Copy the files here or to the appropriate .net folder;

Then use these commands to uninstall and reinstall respectively
"C:\Users\BHJeremy\Desktop\Installing to the Gac in .net 4.0\gacutil.exe" /u "myDLL"

"C:\Windows\Microsoft.NET\Framework\v4.0.30319\gacutil.exe" /i "C:\Program Files\Custom\myDLL.dll"

Nested JSON objects - do I have to use arrays for everything?

You don't need to use arrays.

JSON values can be arrays, objects, or primitives (numbers or strings).

You can write JSON like this:

    "stuff": {
        "onetype": [
            {"id":1,"name":"John Doe"},
            {"id":2,"name":"Don Joeh"}
        "othertype": {"id":2,"company":"ACME"}
    "otherstuff": {
        "thing": [[1,42],[2,2]]

You can use it like this:

obj.otherstuff.thing[0][1]  //thing is a nested array or a 2-by-2 matrix.
                            //I'm not sure whether you intended to do that.

Apache HttpClient Android (Gradle)

I searched over and over this solution works like a charm ::

    apply plugin: ''
    android {
        compileSdkVersion 25
        buildToolsVersion "25.0.3"
        defaultConfig {
            applicationId "com.anzma.memories"
            useLibrary 'org.apache.http.legacy'
            minSdkVersion 15
            targetSdkVersion 25
            versionCode 1
            versionName "1.0"
            testInstrumentationRunner ""
 packagingOptions {
            exclude 'META-INF/DEPENDENCIES.txt'
            exclude 'META-INF/LICENSE.txt'
            exclude 'META-INF/NOTICE.txt'
            exclude 'META-INF/NOTICE'
            exclude 'META-INF/LICENSE'
            exclude 'META-INF/DEPENDENCIES'
            exclude 'META-INF/notice.txt'
            exclude 'META-INF/license.txt'
            exclude 'META-INF/dependencies.txt'
            exclude 'META-INF/LGPL2.1'
    buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), ''
    dependencies {
        compile fileTree(dir: 'libs', include: ['*.jar'])
        compile('org.apache.httpcomponents:httpmime:4.3.6') {
            exclude module: 'httpclient'
        compile 'org.apache.httpcomponents:httpclient-android:4.3.5'
        compile ''
        testCompile 'junit:junit:4.12'

How to show math equations in general github's markdown(not github's blog)

Mathcha is a sophisticated mathematics editor, but it can be used to render individual equations and save them as pure html, which you can then add to your documents as inline html OR you can save as SVG and insert as an image.

Should I make HTML Anchors with 'name' or 'id'?

I have to say if you are going to be linking to that area in the page... such as page.html#foo and Foo Title isn't a link you should be using:

<h1 id="foo">Foo Title</h1>

If you instead put an <a> reference around it your headline will be influenced by an <a> specific CSS within your site. It's just extra markup, and you shouldn't need it. I'd highly recommend placing an id on the headline, not only is it better formed, but it will allow you to either address that object in Javascript or CSS.

How to post JSON to a server using C#?

Ademar's solution can be improved by leveraging JavaScriptSerializer's Serialize method to provide implicit conversion of the object to JSON.

Additionally, it is possible to leverage the using statement's default functionality in order to omit explicitly calling Flush and Close.

var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://url");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";

using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
    string json = new JavaScriptSerializer().Serialize(new
                    user = "Foo",
                    password = "Baz"


var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
    var result = streamReader.ReadToEnd();

How can I compare time in SQL Server?


Separate the time value from the date value if you want to use indexes in your search (you probably should, for performance). You can: (1) use function-based indexes or (2) create a new column for time only, index this column and use it in you SELECT clause.

Keep in mind you will lose any index performance boost if you use functions in a SQL's WHERE clause, the engine has to do a scan search. Just run your query with EXPLAIN SELECT... to confirm this. This happens because the engine has to process EVERY value in the field for EACH comparison, and the converted value is not indexed.

Most answers say to use float(), convert(), cast(), addtime(), etc.. Again, your database won't use indexes if you do this. For small tables that may be OK.

It is OK to use functions in WHERE params though (where field = func(value)), because you won't be changing EACH field's value in the table.

In case you want to keep use of indexes, you can create a function-based index for the time value. The proper way to do this (and support for it) may depend on your database engine. Another option is adding a column to store only the time value and index this column, but try the former approach first.

Edit 06-02

Do some performance tests before updating your database to have a new time column or whatever to make use of indexes. In my tests, I found out the performance boost was minimal (when I could see some improvement) and wouldn't be worth the trouble and overhead of adding a new index.

python "TypeError: 'numpy.float64' object cannot be interpreted as an integer"

Similar situation. It was working. Then, I started to include pytables. At first view, no reason to errors. I decided to use another function, that has a domain constraint (elipse) and received the following error:

TypeError: 'numpy.float64' object cannot be interpreted as an integer


TypeError: 'numpy.float64' object is not iterable

The crazy thing: the previous function I was using, no code changed, started to return the same error. My intermediary function, already used was:

def MinMax(x, mini=0, maxi=1)
    return max(min(x,mini), maxi)

The solution was avoid numpy or math:

def MinMax(x, mini=0, maxi=1)
    x = [x_aux if x_aux > mini else mini for x_aux in x]
    x = [x_aux if x_aux < maxi else maxi for x_aux in x]
    return max(min(x,mini), maxi)

Then, everything calm again. It was like one library possessed max and min!

Getting list of pixel values from PIL

If you have numpy installed you can try:

data = numpy.asarray(im)

(I say "try" here, because it's unclear why getdata() isn't working for you, and I don't know whether asarray uses getdata, but it's worth a test.)

Default value to a parameter while passing by reference in C++

It's possible with const qualifier for State:

virtual const ULONG Write(const ULONG &State = 0, bool sequence = true);

how to convert integer to string?

NSString* myNewString = [NSString stringWithFormat:@"%d", myInt];

Run bash command on jenkins pipeline

For multi-line shell scripts or those run multiple times, I would create a new bash script file (starting from #!/bin/bash), and simply run it with sh from Jenkinsfile:

sh 'chmod +x ./'
sh './'

Why is my Button text forced to ALL CAPS on Lollipop?

this one is working .... just in your code in your bottom code add this one :


it should deactivate the caps letter that U trying to type small .

How to print Two-Dimensional Array like table

A part from @djechlin answer, you should change the rows and columns. Since you are taken as 7 rows and 5 columns, but actually you want is 7 columns and 5 rows.

Do this way:-

int twoDm[][]= new int[5][7];

    for(j=0;j<7;j++) {
        System.out.print(twoDm[i][j]+" ");

AngularJS resource promise

You could also do:

Regions.query({}, function(response) {
    $scope.regions = response;
    // Do stuff that depends on $scope.regions here

How to declare a global variable in a .js file

As mentioned above, there are issues with using the top-most scope in your script file. Here is another issue: The script file might be run from a context that is not the global context in some run-time environment.

It has been proposed to assign the global to window directly. But that is also run-time dependent and does not work in Node etc. It goes to show that portable global variable management needs some careful consideration and extra effort. Maybe they will fix it in future ECMS versions!

For now, I would recommend something like this to support proper global management for all run-time environments:

 * Exports the given object into the global context.
var exportGlobal = function(name, object) {
    if (typeof(global) !== "undefined")  {
        // Node.js
        global[name] = object;
    else if (typeof(window) !== "undefined") {
        // JS with GUI (usually browser)
        window[name] = object;
    else {
        throw new Error("Unkown run-time environment. Currently only browsers and Node.js are supported.");

// export exportGlobal itself
exportGlobal("exportGlobal", exportGlobal);

// create a new global namespace
exportGlobal("someothernamespace", {});

It's a bit more typing, but it makes your global variable management future-proof.

Disclaimer: Part of this idea came to me when looking at previous versions of stacktrace.js.

I reckon, one can also use Webpack or other tools to get more reliable and less hackish detection of the run-time environment.

How to fix syntax error, unexpected T_IF error in php?

Here is the issue

  $total_result = $result->num_rows;

try this

if ($result = $mysqli->query("SELECT * FROM players ORDER BY id"))
    if ($result->num_rows > 0)
        $total_result = $result->num_rows;
        $total_pages = ceil($total_result / $per_page);

        if(isset($_GET['page']) && is_numeric($_GET['page']))
            $show_page = $_GET['page'];

            if ($show_page > 0 && $show_page <= $total_pages)
                $start = ($show_page - 1) * $per_page;
                $end = $start + $per_page;
                $start = 0;
                $end = $per_page;

            $start = 0;
            $end = $per_page;

        //display paginations
        echo "<p> View pages: ";
        for ($i=1; $i < $total_pages; $i++)
            if (isset($_GET['page']) && $_GET['page'] == $i)
                echo  $i . " ";
                echo "<a href='view-pag.php?$i'>" . $i . "</a> | ";

        echo "</p>";

        echo "No result to display.";

    echo "Error: " . $mysqli->error;


MySQL Error #1133 - Can't find any matching row in the user table

I encountered this error using MySQL in a different context (not within phpMyAdmin). GRANT and SET PASSWORD commands failed on a particular existing user, who was listed in the mysql.user table. In my case, it was fixed by running


The documentation for this command says

Reloads the privileges from the grant tables in the mysql database.

The server caches information in memory as a result of GRANT and CREATE USER statements. This memory is not released by the corresponding REVOKE and DROP USER statements, so for a server that executes many instances of the statements that cause caching, there will be an increase in memory use. This cached memory can be freed with FLUSH PRIVILEGES.

Apparently the user table cache had reached an inconsistent state, causing this weird error message. More information is available here.

C compile error: "Variable-sized object may not be initialized"

For C++ separate declaration and initialization like this..

int a[n][m] ;
a[n][m]= {0};

Eclipse+Maven src/main/java not visible in src folder in Package Explorer

If you are looking for Simple/quicker way, you can follow this solution.

  1. Right click on your project.
  2. Goto > Build Path > Configure Build Path > Java Build Path
  3. Goto 'Source' tab, there, you can see like <<your_project_name>>/src/main/java(missing).
  4. Click on it and remove.
  5. Click on Apply and Close.
  6. Now, right click on project and >New > Source folder > add source folder "src/main/java".

happy learning and do not forget to upvote :)

SQL Server AS statement aliased column within WHERE statement

Logical Processing Order of the SELECT statement

The following steps show the logical processing order, or binding order, for a SELECT statement. This order determines when the objects defined in one step are made available to the clauses in subsequent steps. For example, if the query processor can bind to (access) the tables or views defined in the FROM clause, these objects and their columns are made available to all subsequent steps. Conversely, because the SELECT clause is step 8, any column aliases or derived columns defined in that clause cannot be referenced by preceding clauses. However, they can be referenced by subsequent clauses such as the ORDER BY clause. Note that the actual physical execution of the statement is determined by the query processor and the order may vary from this list.

  1. FROM
  2. ON
  3. JOIN
  4. WHERE
  10. ORDER BY
  11. TOP


How to check if an object implements an interface?

In general for AnInterface and anInstance of any class:


Check if instance is of a type


c.getType() == typeOf(TForm)

PHP - cannot use a scalar as an array warning

Make sure that you don't declare it as a integer, float, string or boolean before.

How to run a function in jquery

Is this the most obfuscated solution possible? I don't believe the idea of jQuery was to create code like this.There's also the presumption that we don't want to bubble events, which is probably wrong.

Simple moving doosomething() outside of $(function(){} will cause it to have global scope and keep the code simple/readable.

How to parse JSON using Node.js?

Since you don't know that your string is actually valid, I would put it first into a try catch. Also since try catch blocks are not optimized by node, i would put the entire thing into another function:

function tryParseJson(str) {
    try {
        return JSON.parse(str);
    } catch (ex) {
        return null;

OR in "async style"

function tryParseJson(str, callback) {
    process.nextTick(function () {
      try {
          callback(null, JSON.parse(str));
      } catch (ex) {

What properties does @Column columnDefinition make redundant?

My Answer: All of the following should be overridden (i.e. describe them all within columndefinition, if appropriate):

  • length
  • precision
  • scale
  • nullable
  • unique

i.e. the column DDL will consist of: name + columndefinition and nothing else.

Rationale follows.

  1. Annotation containing the word "Column" or "Table" is purely physical - properties only used to control DDL/DML against database.

  2. Other annotation purely logical - properties used in-memory in java to control JPA processing.

  3. That's why sometimes it appears the optionality/nullability is set twice - once via @Basic(...,optional=true) and once via @Column(...,nullable=true). Former says attribute/association can be null in the JPA object model (in-memory), at flush time; latter says DB column can be null. Usually you'd want them set the same - but not always, depending on how the DB tables are setup and reused.

In your example, length and nullable properties are overridden and redundant.

So, when specifying columnDefinition, what other properties of @Column are made redundant?

  1. In JPA Spec & javadoc:

    • columnDefinition definition: The SQL fragment that is used when generating the DDL for the column.

    • columnDefinition default: Generated SQL to create a column of the inferred type.

    • The following examples are provided:

      @Column(name="DESC", columnDefinition="CLOB NOT NULL", table="EMP_DETAIL")
      @Column(name="EMP_PIC", columnDefinition="BLOB NOT NULL")
    • And, err..., that's it really. :-$ ?!

    Does columnDefinition override other properties provided in the same annotation?

    The javadoc and JPA spec don't explicity address this - spec's not giving great protection. To be 100% sure, test with your chosen implementation.

  2. The following can be safely implied from examples provided in the JPA spec

    • name & table can be used in conjunction with columnDefinition, neither are overridden
    • nullable is overridden/made redundant by columnDefinition
  3. The following can be fairly safely implied from the "logic of the situation" (did I just say that?? :-P ):

    • length, precision, scale are overridden/made redundant by the columnDefinition - they are integral to the type
    • insertable and updateable are provided separately and never included in columnDefinition, because they control SQL generation in-memory, before it is emmitted to the database.
  4. That leaves just the "unique" property. It's similar to nullable - extends/qualifies the type definition, so should be treated integral to type definition. i.e. should be overridden.

Test My Answer For columns "A" & "B", respectively:

  @Column(name="...", table="...", insertable=true, updateable=false,
          columndefinition="NUMBER(5,2) NOT NULL UNIQUE"

  @Column(name="...", table="...", insertable=false, updateable=true,
          columndefinition="NVARCHAR2(100) NULL"
  • confirm generated table has correct type/nullability/uniqueness
  • optionally, do JPA insert & update: former should include column A, latter column B

Visual Studio setup problem - 'A problem has been encountered while loading the setup components. Canceling setup.'

I had the same error message. For me it was happening because I was trying to run the installer from the DVD rather than running the installer from Add/Remove programs.

Get Value From Select Option in Angular 4

export class MyComponent implements OnInit {_x000D_
  items: any[] = [_x000D_
    { id: 1, name: 'one' },_x000D_
    { id: 2, name: 'two' },_x000D_
    { id: 3, name: 'three' },_x000D_
    { id: 4, name: 'four' },_x000D_
    { id: 5, name: 'five' },_x000D_
    { id: 6, name: 'six' }_x000D_
  selected: number = 1;_x000D_
  constructor() {_x000D_
  ngOnInit() {_x000D_
  selectOption(id: number) {_x000D_
    //getted from event_x000D_
    //getted from binding_x000D_
  <select (change)="selectOption($"_x000D_
  <option [value]="" *ngFor="let item of items">{{}}</option>_x000D_

APT command line interface-like yes/no input?

You can use click's confirm method.

import click

if click.confirm('Do you want to continue?', default=True):
    print('Do something')

This will print:

$ Do you want to continue? [Y/n]:

Should work for Python 2/3 on Linux, Mac or Windows.


How to uninstall a package installed with pip install --user

example to uninstall package 'oauth2client' on MacOS:

pip uninstall oauth2client

JavaScript Array Push key value

You have to use bracket notation:

var obj = {};
obj[a[i]] = 0;

The result will be:

x = [{left: 0}, {top: 0}];

Maybe instead of an array of objects, you just want one object with two properties:

var x = {};


x[a[i]] = 0;

This will result in x = {left: 0, top: 0}.

TypeError: 'builtin_function_or_method' object is not subscriptable

instead of writing listb.pop[0] write


How do I enable the column selection mode in Eclipse?

Additionally, you can change the keys view window -> preferences then type: 'keys' and when the key preference page opens you can type 'toggle block selection' and voila!

How to run a makefile in Windows?

Check out cygwin, a Unix alike environment for Windows

SQL Server 2008 Connection Error "No process is on the other end of the pipe"

Adding "user instance=False" to connection string solved the problem for me.

  <add name="NorthwindEntities" connectionString="metadata=res://*/Models.Northwind.csdl|res://*/Models.Northwind.ssdl|res://*/Models.Northwind.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=.\SQLEXPRESS2008R2;attachdbfilename=|DataDirectory|\Northwind.mdf;integrated security=True;user instance=False;multipleactiveresultsets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />

Javascript - remove an array item by value

If you're going to be using this often (and on multiple arrays), extend the Array object to create an unset function.

Array.prototype.unset = function(value) {
    if(this.indexOf(value) != -1) { // Make sure the value exists
        this.splice(this.indexOf(value), 1);


Is there an online application that automatically draws tree structures for phrases/sentences?

In short, yes. I assume you're looking to parse English: for that you can use the Link Parser from Carnegie Mellon.

It is important to remember that there are many theories of syntax, that can give completely different-looking phrase structure trees; further, the trees are different for each language, and tools may not exist for those languages.

As a note for the future: if you need a sentence parsed out and tag it as linguistics (and syntax or whatnot, if that's available), someone can probably parse it out for you and guide you through it.

Python decorators in classes

I found this question while researching a very similar problem. My solution is to split the problem into two parts. First, you need to capture the data that you want to associate with the class methods. In this case, handler_for will associate a Unix command with handler for that command's output.

class OutputAnalysis(object):
    "analyze the output of diagnostic commands"
    def handler_for(name):
        "decorator to associate a function with a command"
        def wrapper(func):
            func.handler_for = name
            return func
        return wrapper
    # associate mount_p with 'mount_-p.txt'
    @handler_for('mount -p')
    def mount_p(self, slurped):

Now that we've associated some data with each class method, we need to gather that data and store it in a class attribute.

OutputAnalysis.cmd_handler = {}
for value in OutputAnalysis.__dict__.itervalues():
        OutputAnalysis.cmd_handler[value.handler_for] = value
    except AttributeError:

Remove all multiple spaces in Javascript and replace with single space

There are a lot of options for regular expressions you could use to accomplish this. One example that will perform well is:

str.replace( /\s\s+/g, ' ' )

See this question for a full discussion on this exact problem: Regex to replace multiple spaces with a single space

Is there any way to kill a Thread?

This is based on thread2 -- killable threads (Python recipe)

You need to call PyThreadState_SetasyncExc(), which is only available through ctypes.

This has only been tested on Python 2.7.3, but it is likely to work with other recent 2.x releases.

import ctypes

def terminate_thread(thread):
    """Terminates a python thread from another thread.

    :param thread: a threading.Thread instance
    if not thread.isAlive():

    exc = ctypes.py_object(SystemExit)
    res = ctypes.pythonapi.PyThreadState_SetAsyncExc(
        ctypes.c_long(thread.ident), exc)
    if res == 0:
        raise ValueError("nonexistent thread id")
    elif res > 1:
        # """if it returns a number greater than one, you're in trouble,
        # and you should call it again with exc=NULL to revert the effect"""
        ctypes.pythonapi.PyThreadState_SetAsyncExc(thread.ident, None)
        raise SystemError("PyThreadState_SetAsyncExc failed")

How to start/stop/restart a thread in Java?

Once a thread stops you cannot restart it. However, there is nothing stopping you from creating and starting a new thread.

Option 1: Create a new thread rather than trying to restart.

Option 2: Instead of letting the thread stop, have it wait and then when it receives notification you can allow it to do work again. This way the thread never stops and will never need to be restarted.

Edit based on comment:

To "kill" the thread you can do something like the following.

yourThread.setIsTerminating(true); // tell the thread to stop
yourThread.join(); // wait for the thread to stop

C++, copy set to vector

Just use the constructor for the vector that takes iterators:

std::set<T> s;


std::vector v( s.begin(), s.end() );

Assumes you just want the content of s in v, and there's nothing in v prior to copying the data to it.

Check if checkbox is NOT checked on click - jQuery

$(document).ready(function() {
        $("#check1").click(function() {
            var checked = $(this).is(':checked');
            if (checked) {
            } else {

What does 'public static void' mean in Java?

It's three completely different things:

public means that the method is visible and can be called from other objects of other types. Other alternatives are private, protected, package and package-private. See here for more details.

static means that the method is associated with the class, not a specific instance (object) of that class. This means that you can call a static method without creating an object of the class.

void means that the method has no return value. If the method returned an int you would write int instead of void.

The combination of all three of these is most commonly seen on the main method which most tutorials will include.

Difference between try-catch and throw in java

Others have already given thorough answers, but if you're looking for even more information, the Oracle Java tutorials are always a good resource. Here's the Java tutorial for Exceptions, which covers all of your questions in great detail;

Recommended way of making React component/div draggable

I've updated the class using refs as all the solutions I see on here have things that are no longer supported or will soon be depreciated like ReactDOM.findDOMNode. Can be parent to a child component or a group of children :)

import React, { Component } from 'react';

class Draggable extends Component {

    constructor(props) {
        this.myRef = React.createRef();
        this.state = {
            counter: this.props.counter,
            pos: this.props.initialPos,
            dragging: false,
            rel: null // position relative to the cursor

    /*  we could get away with not having this (and just having the listeners on
     our div), but then the experience would be possibly be janky. If there's
     anything w/ a higher z-index that gets in the way, then you're toast,
    componentDidUpdate(props, state) {
        if (this.state.dragging && !state.dragging) {
            document.addEventListener('mousemove', this.onMouseMove);
            document.addEventListener('mouseup', this.onMouseUp);
        } else if (!this.state.dragging && state.dragging) {
            document.removeEventListener('mousemove', this.onMouseMove);
            document.removeEventListener('mouseup', this.onMouseUp);

    // calculate relative position to the mouse and set dragging=true
    onMouseDown = (e) => {
        if (e.button !== 0) return;
        let pos = { left: this.myRef.current.offsetLeft, top: this.myRef.current.offsetTop }
            dragging: true,
            rel: {
                x: e.pageX - pos.left,
                y: e.pageY -

    onMouseUp = (e) => {
        this.setState({ dragging: false });

    onMouseMove = (e) => {
        if (!this.state.dragging) return;

            pos: {
                x: e.pageX - this.state.rel.x,
                y: e.pageY - this.state.rel.y

    render() {
        return (
            <span ref={this.myRef} onMouseDown={this.onMouseDown} style={{ position: 'absolute', left: this.state.pos.x + 'px', top: this.state.pos.y + 'px' }}>

export default Draggable;

Node.js Logging

Observe that errorLogger is a wrapper around logger.trace. But the level of logger is ERROR so logger.trace will not log its message to logger's appenders.

The fix is to change logger.trace to logger.error in the body of errorLogger.

How many characters can a Java String have?

I believe they can be up to 2^31-1 characters, as they are held by an internal array, and arrays are indexed by integers in Java.

ASP.NET MVC Razor pass model to layout

Seems like you have modeled your viewmodels a bit wrong if you have this problem.

Personally I would never type a layout page. But if you want to do that you should have a base viewmodel that your other viewmodels inherits from and type your layout to the base viewmodel and you pages to the specific once.

Remove all the children DOM elements in div

If you are looking for a modern >1.7 Dojo way of destroying all node's children this is the way:

// Destroys all domNode's children nodes
// domNode can be a node or its id:

Safely empty the contents of a DOM element. empty() deletes all children but keeps the node there.

Check "dom-construct" documentation for more details.

// Destroys domNode and all it's children

Destroys a DOM element. destroy() deletes all children and the node itself.

Setting a backgroundImage With React Inline Styles

You can try this with by adding backticks on whole url

style={{backgroundImage:url(${val.image || ''} ) }}

php, mysql - Too many connections to database error

There are a bunch of different reasons for the "Too Many Connections" error.

Check out this FAQ page on

Check your my.cnf file for "max_connections". If none exist try:


However the default is 151, so you should be okay.

If you are on a shared host, it might be that other users are taking up too many connections.

Other problems to look out for is the use of persistent connections and running out of diskspace.

How to change symbol for decimal point in double.ToString()?

Some shortcut is to create a NumberFormatInfo class, set its NumberDecimalSeparator property to "." and use the class as parameter to ToString() method whenever u need it.

using System.Globalization;

NumberFormatInfo nfi = new NumberFormatInfo();
nfi.NumberDecimalSeparator = ".";


How to stick <footer> element at the bottom of the page (HTML5 and CSS3)?

Here is an example using css3:


html, body {
    height: 100%;
    margin: 0;
#wrap {
    padding: 10px;
    min-height: -webkit-calc(100% - 100px);     /* Chrome */
    min-height: -moz-calc(100% - 100px);     /* Firefox */
    min-height: calc(100% - 100px);     /* native */
.footer {
    position: relative;


<div id="wrap">
    body content....
<footer class="footer">
    footer content....


As @Martin pointed, the ´position: relative´ is not mandatory on the .footer element, the same for clear:both. These properties are only there as an example. So, the minimum css necessary to stick the footer on the bottom should be:

html, body {
    height: 100%;
    margin: 0;
#wrap {
    min-height: -webkit-calc(100% - 100px);     /* Chrome */
    min-height: -moz-calc(100% - 100px);     /* Firefox */
    min-height: calc(100% - 100px);     /* native */

Also, there is an excellent article at css-tricks showing different ways to do this:

PHP Date Time Current Time Add Minutes

I think one of the best solutions and easiest is:

strtotime("+30 minutes")

Maybe it's not the most efficient but is one of the more understandable.

Difference between [routerLink] and routerLink

Router Link

routerLink with brackets and none - simple explanation.

The difference between routerLink= and [routerLink] is mostly like relative and absolute path.

Similar to a href you may want to navigate to ./about.html or

When you use without brackets then you navigate relative and without params;

"jumping" from to

<a routerLink="client/{{ }}" .... rest the same

When you use routerLink with brackets then you execute app to navigate absolute and you can add params how is the puzzle of your new link

first of all it will not include the "jump" from dashboard/ to dashboard/client/client-id and bring you data of client/client-id which is more helpful for EDIT CLIENT

<a [routerLink]="['/client',]" ... rest the same

The absolute way or brackets routerLink require additional set up of you components and app.routing.module.ts

The code without error will "tell you more/what is the purpose of []" when you make the test. Just check this with or without []. Than you may experiments with selectors which - as mention above - helps with dynamics routing. Selectors

See whats the routerLink construct

Extreme wait-time when taking a SQL Server database offline

After some additional searching (new search terms inspired by gbn's answer and u07ch's comment on KMike's answer) I found this, which completed successfully in 2 seconds:



When this still fails with the following error, you can fix it as inspired by this blog post:

ALTER DATABASE failed because a lock could not be placed on database 'dbname' Try again later.

you can run the following command to find out who is keeping a lock on your database:

EXEC sp_who2

And use whatever SPID you find in the following command:


Then run the ALTER DATABASE command again. It should now work.

Convert a number range to another range, maintaining ratio

I personally use the helper class which supports generics (Swift 3, 4.x compatible)

struct Rescale<Type : BinaryFloatingPoint> {
    typealias RescaleDomain = (lowerBound: Type, upperBound: Type)

    var fromDomain: RescaleDomain
    var toDomain: RescaleDomain

    init(from: RescaleDomain, to: RescaleDomain) {
        self.fromDomain = from
        self.toDomain = to

    func interpolate(_ x: Type ) -> Type {
        return self.toDomain.lowerBound * (1 - x) + self.toDomain.upperBound * x;

    func uninterpolate(_ x: Type) -> Type {
        let b = (self.fromDomain.upperBound - self.fromDomain.lowerBound) != 0 ? self.fromDomain.upperBound - self.fromDomain.lowerBound : 1 / self.fromDomain.upperBound;
        return (x - self.fromDomain.lowerBound) / b

    func rescale(_ x: Type )  -> Type {
        return interpolate( uninterpolate(x) )


   let rescaler = Rescale<Float>(from: (-1, 1), to: (0, 100))
   print(rescaler.rescale(0)) // OUTPUT: 50

Convert date from 'Thu Jun 09 2011 00:00:00 GMT+0530 (India Standard Time)' to 'YYYY-MM-DD' in javascript

You can parse the date using the Date constructor, then spit out the individual time components:

function convert(str) {_x000D_
  var date = new Date(str),_x000D_
    mnth = ("0" + (date.getMonth() + 1)).slice(-2),_x000D_
    day = ("0" + date.getDate()).slice(-2);_x000D_
  return [date.getFullYear(), mnth, day].join("-");_x000D_
console.log(convert("Thu Jun 09 2011 00:00:00 GMT+0530 (India Standard Time)"))_x000D_
//-> "2011-06-08"

As you can see from the result though, this will parse the date into the local time zone. If you want to keep the date based on the original time zone, the easiest approach is to split the string and extract the parts you need:

function convert(str) {_x000D_
  var mnths = {_x000D_
      Jan: "01",_x000D_
      Feb: "02",_x000D_
      Mar: "03",_x000D_
      Apr: "04",_x000D_
      May: "05",_x000D_
      Jun: "06",_x000D_
      Jul: "07",_x000D_
      Aug: "08",_x000D_
      Sep: "09",_x000D_
      Oct: "10",_x000D_
      Nov: "11",_x000D_
      Dec: "12"_x000D_
    date = str.split(" ");_x000D_
  return [date[3], mnths[date[1]], date[2]].join("-");_x000D_
console.log(convert("Thu Jun 09 2011 00:00:00 GMT+0530 (India Standard Time)"))_x000D_
//-> "2011-06-09"

Getting "cannot find Symbol" in Java project in Intellij

I'm seeing a lot of answers proposing a build or a re-build but just in case this don't fix your problem just notice that IDEA can detect a method but it will not compile in case you have a new before as it will be expecting the instance.

enter image description here

how to convert object into string in php

You can tailor how your object is represented as a string by implementing a __toString() method in your class, so that when your object is type cast as a string (explicit type cast $str = (string) $myObject;, or automatic echo $myObject) you can control what is included and the string format.

If you only want to display your object's data, the method above would work. If you want to store your object in a session or database, you need to serialize it, so PHP knows how to reconstruct your instance.

Some code to demonstrate the difference:

class MyObject {

  protected $name = 'JJ';

  public function __toString() {
    return "My name is: {$this->name}\n";


$obj = new MyObject;

echo $obj;
echo serialize($obj);


My name is: JJ


Eclipse error: indirectly referenced from required .class files?

It sounds like this has been a known issue (Bug 67414)that was resolved in 3.0 ... someone has commented that it's occurring for them in 3.4 as well.

In the mean time, the work around is to remove the JRE System Library from the project and then add it back again.

Here are the steps:

Go to properties of project with the build error (right click > Properties)

View the "Libraries" tab in the "Build Path" section

Find the "JRE System Library" in the list (if this is missing then this error message is not an eclipse bug but a mis-configured project)

Remove the "JRE System Library"

Hit "Add Library ...", Select "JRE System Library" and add the appropriate JRE for the project (eg. 'Workspace default JRE')

Hit "Finish" in the library selection and "OK" in the project properties and then wait for the re-build of the project

Hopefully the error will be resolved ...

Laravel - Forbidden You don't have permission to access / on this server

This is solved my problem by adding this line:

DirectoryIndex index.php

javascript create array from for loop

even shorter if you can lose the yearStart value:

var yearStart = 2000;
var yearEnd = 2040;

var arr = [];

while(yearStart < yearEnd+1){

UPDATE: If you can use the ES6 syntax you can do it the way proposed here:

let yearStart = 2000;
let yearEnd = 2040;
let years = Array(yearEnd-yearStart+1)
    .map(() => yearStart++);

Remove part of string after "."

You just need to escape the period:

a <- c("NM_020506.1","NM_020519.1","NM_001030297.2","NM_010281.2","NM_011419.3", "NM_053155.2")

[1] "NM_020506"    "NM_020519"    "NM_001030297" "NM_010281"    "NM_011419"    "NM_053155" 

Deleting multiple columns based on column names in Pandas

This is probably a good way to do what you want. It will delete all columns that contain 'Unnamed' in their header.

for col in df.columns:
    if 'Unnamed' in col:
        del df[col]