Programs & Examples On #Wcf lob adapter

Does the Java &= operator apply & or &&?

see 15.22.2 of the JLS. For boolean operands, the & operator is boolean, not bitwise. The only difference between && and & for boolean operands is that for && it is short circuited (meaning that the second operand isn't evaluated if the first operand evaluates to false).

So in your case, if b is a primitive, a = a && b, a = a & b, and a &= b all do the same thing.

ArrayAdapter in android to create simple listview

The TextView resource id it needs is for a TextView layout file, so it won't be in the same activity.

You can create it by going to File > New > XML > XML Layout File, and enter the widget type, which is 'TextView' in the root tag field.


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

You didn't state your actual goal, but maybe this can help:

require 'matrix'  # bundled with Ruby
m = Matrix[
 [1, 2, 3],
 [4, 5, 6]

m.column(0) # ==> Vector[1, 4]

(and Vectors acts like arrays)

or, using a similar notation as you desire:

m.minor(0..1, 2..2) # => Matrix[[3], [6]]

How does the "position: sticky;" property work?

One of the most common mistakes when going about the position sticky is:

  1. Browser not supporting it
  2. Not including any top bottom right left properties. Bare in mind that the Browser won't know how to handle that properly if you don't give it enough information. It will be just be statically positioned without it.

I have written about that and more insides on this article. Just putting a reference so I don't repeat myself too much.

Tooltips with Twitter Bootstrap

I think your question boils down to what proper selector to use when setting up your tooltips, and the answer to that is almost whatever you want. If you want to use a class to trigger your tooltips you can do that, take the following for example:

<a href="#" class="link" data-original-title="first tooltip">Hover me for a tooltip</a>

Then you can trigger all links with the .link class attached as tooltips like so:


Now, to answer your question as to why the bootstrap developers did not use a class to trigger tooltips that is because it is not needed exactly, you can pretty much use any selectors you want to target your tooltips, such as (my personal favorite) the rel attribute. With this attribute you can target all links or elements with the rel property set to tooltip, like so:


And your links would look like something like this:

<a href="#" rel="tooltip" data-original-title="first tooltip">Hover me for a tooltip</a>

Of course, you can also use a container class or id to target your tooltips inside an specific container that you want to single out with an specific option or to separate from the rest of your content and you can use it like so:

    selector: "a[rel=tooltip]"

This selector will target all of your tooltips with the rel attribute "within" your #example div, this way you can add special styles or options to that section alone. In short, you can pretty much use any valid selector to target your tooltips and there is no need to dirty your markup with an extra class to target them.

jQuery append text inside of an existing paragraph tag

Try this...

$('p').append('<span id="add_here">new-dynamic-text</span>');

OR if there is an existing span, do this.



Upload Progress Bar in PHP

You would need to use Javascript to create a progress bar. A simple Google search led me to this article: WebAppers Simple Javascript Progress Bar with CSS.

Dojo File Upload Progress Bar Widget is another option using the Dojo Javascript framework.

EDIT: Assuming your uploading a large number of images (such as a photo album), and POSTing them to your PHP script, you could use javascript to read the results back from the post and update the progress bar based on the number of images uploaded / total number of images. This has the side effect of only updating after each post has completed. Check out here for some info on how to post with JS.

How to set width of mat-table column in angular?

You can easily do this one. In each column you will get a class with the field name prefixed with mat-column, so the class will be like mat-column-yourFieldName. So for that you can set the style like following

.mat-column-yourFieldName {
    flex: none;
    width: 100px;

So we can give fixed width for column as per our requirement.

Hope this helps for someone.

Difference between Static methods and Instance methods

If state of a method is not supposed to be changed or its not going to use any instance variables.

You want to call method without instance.

If it only works on arguments provided to it.

Utility functions are good instance of static methods. i.e math.pow(), this function is not going to change the state for different values. So it is static.

Get full query string in C# ASP.NET

Try Request.Url.Query if you want the raw querystring as a string.

What is the correct way to write HTML using Javascript?

There are many ways to write html with JavaScript.

document.write is only useful when you want to write to page before it has actually loaded. If you use document.write() after the page has loaded (at onload event) it will create new page and overwrite the old content. Also it doesn't work with XML, that includes XHTML.

From other hand other methods can't be used before DOM has been created (page loaded), because they work directly with DOM.

These methods are:

  • node.innerHTML = "Whatever";
  • document.createElement('div'); and node.appendChild(), etc..

In most cases node.innerHTML is better since it's faster then DOM functions. Most of the time it also make code more readable and smaller.

Max size of URL parameters in _GET

Ok, it seems that some versions of PHP have a limitation of length of GET params:

Please note that PHP setups with the suhosin patch installed will have a default limit of 512 characters for get parameters. Although bad practice, most browsers (including IE) supports URLs up to around 2000 characters, while Apache has a default of 8000.

To add support for long parameters with suhosin, add suhosin.get.max_value_length = <limit> in php.ini


PostgreSQL - fetch the row which has the Max value for a column

FROM    (
        SELECT DISTINCT usr_id
        FROM   lives
        ) lo, lives l
WHERE   l.ctid = (
        SELECT ctid
        FROM   lives li
        WHERE  li.usr_id = lo.usr_id
        ORDER BY
          time_stamp DESC, trans_id DESC
        LIMIT 1

Creating an index on (usr_id, time_stamp, trans_id) will greatly improve this query.

You should always, always have some kind of PRIMARY KEY in your tables.

How do I make my ArrayList Thread-Safe? Another approach to problem in Java?

You can change from ArrayList to Vector type, in which every method is synchronized.

private Vector finishingOrder;
//Make a Vector to hold RaceCar objects to determine winners
finishingOrder = new Vector(numberOfRaceCars);

How to get the cell value by column name not by index in GridView in

A little bug with indexcolumn in alexander's answer: We need to take care of "not found" column:

int GetColumnIndexByName(GridViewRow row, string columnName)
    int columnIndex = 0;
    int foundIndex=-1;
    foreach (DataControlFieldCell cell in row.Cells)
        if (cell.ContainingField is BoundField)
            if (((BoundField)cell.ContainingField).DataField.Equals(columnName))
        columnIndex++; // keep adding 1 while we don't have the correct name
    return foundIndex;


protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
    if (e.Row.RowType == DataControlRowType.DataRow)
        int index = GetColumnIndexByName(e.Row, "myDataField");
        if( index>0)
            string columnValue = e.Row.Cells[index].Text;

Only Add Unique Item To List

If your requirements are to have no duplicates, you should be using a HashSet.

HashSet.Add will return false when the item already exists (if that even matters to you).

You can use the constructor that @pstrjds links to below (or here) to define the equality operator or you'll need to implement the equality methods in RemoteDevice (GetHashCode & Equals).

What is the proper way to display the full InnerException?

I usually do like this to remove most of the noise:

void LogException(Exception error) {
    Exception realerror = error;
    while (realerror.InnerException != null)
        realerror = realerror.InnerException;


Edit: I forgot about this answer and is surprised no one pointed out that you can just do

void LogException(Exception error) {

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

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

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

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

shift + tab

Display short document and few params

enter image description here

shift + tab + tab

Expands document with scroll bar

enter image description here

shift + tab + tab + tab

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

enter image description here

shift + tab + tab + tab + tab

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

enter image description here

Django 1.7 throws django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet

Your is "wrong"; I don't know where you got it from, but that's not a 1.7 - were you using some funky pre-release build or something?

Reset your to the conventional, as below, and things Should Just Work:

#!/usr/bin/env python
import os
import sys

if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "{{ project_name }}.settings")

    from import execute_from_command_line


Bash: Echoing a echo command with a variable in bash

The immediate problem is you have is with quoting: by using double quotes ("..."), your variable references are instantly expanded, which is probably not what you want.

Use single quotes instead - strings inside single quotes are not expanded or interpreted in any way by the shell.

(If you want selective expansion inside a string - i.e., expand some variable references, but not others - do use double quotes, but prefix the $ of references you do not want expanded with \; e.g., \$var).

However, you're better off using a single here-doc[ument], which allows you to create multi-line stdin input on the spot, bracketed by two instances of a self-chosen delimiter, the opening one prefixed by <<, and the closing one on a line by itself - starting at the very first column; search for Here Documents in man bash or at

If you quote the here-doc delimiter (EOF in the code below), variable references are also not expanded. As @chepner points out, you're free to choose the method of quoting in this case: enclose the delimiter in single quotes or double quotes, or even simply arbitrarily escape one character in the delimiter with \:

echo "creating new script file."

cat <<'EOF'  > "$servfile"
read -p "Please enter a service: " ser
servicetest=`getsebool -a | grep ${ser}` 
if [ $servicetest > /dev/null ]; then 
  echo "we are now going to work with ${ser}"
  exit 1

As @BruceK notes, you can prefix your here-doc delimiter with - (applied to this example: <<-"EOF") in order to have leading tabs stripped, allowing for indentation that makes the actual content of the here-doc easier to discern. Note, however, that this only works with actual tab characters, not leading spaces.

Employing this technique combined with the afterthoughts regarding the script's content below, we get (again, note that actual tab chars. must be used to lead each here-doc content line for them to get stripped):

cat <<-'EOF' > "$servfile"
    read -p "Please enter a service name: " ser
    if [[ -n $(getsebool -a | grep "${ser}") ]]; then 
      echo "We are now going to work with ${ser}."
      exit 1

Finally, note that in bash even normal single- or double-quoted strings can span multiple lines, but you won't get the benefits of tab-stripping or line-block scoping, as everything inside the quotes becomes part of the string.

Thus, note how in the following #!/bin/bash has to follow the opening ' immediately in order to become the first line of output:

echo '#!/bin/bash
read -p "Please enter a service: " ser
servicetest=$(getsebool -a | grep "${ser}")
if [[ -n $servicetest ]]; then 
  echo "we are now going to work with ${ser}"
  exit 1
fi' > "$servfile"

Afterthoughts regarding the contents of your script:

  • The syntax $(...) is preferred over `...` for command substitution nowadays.
  • You should double-quote ${ser} in the grep command, as the command will likely break if the value contains embedded spaces (alternatively, make sure that the valued read contains no spaces or other shell metacharacters).
  • Use [[ -n $servicetest ]] to test whether $servicetest is empty (or perform the command substitution directly inside the conditional) - [[ ... ]] - the preferred form in bash - protects you from breaking the conditional if the $servicetest happens to have embedded spaces; there's NEVER a need to suppress stdout output inside a conditional (whether [ ... ] or [[ ... ]], as no stdout output is passed through; thus, the > /dev/null is redundant (that said, with a command substitution inside a conditional, stderr output IS passed through).

ImportError: no module named win32api

This is resolve my case as found on Where to find the win32api module for Python?

pip install pypiwin32

How can I know if a process is running?

Synchronous solution :

void DisplayProcessStatus(Process process)
    process.Refresh();  // Important


Asynchronous solution:

void RegisterProcessExit(Process process)
    // NOTE there will be a race condition with the caller here
    //   how to fix it is left as an exercise
    process.Exited += process_Exited;

static void process_Exited(object sender, EventArgs e)
   Console.WriteLine("Process has exited.");

Changing :hover to touch/click for mobile devices

Well I agree with above answers but still there can be an another way to do this and it is by using media queries.

Suppose this is what you want to do :

body.nontouch nav a:hover {
    background: yellow;

then you can do this by media query as :

@media(hover: hover) and (pointer: fine) {
    nav a:hover {
        background: yellow;

And for more details you can visit this page.

Visual Studio window which shows list of methods

Do you mean the class view window (View->Class View, or Ctrl+W,C)?

You also have the intellisence popup-window

Correct MySQL configuration for Ruby on Rails Database.yml file

If you can have an empty config/database.yml file then define ENV['DATABASE_URL'] variable, then It will work

$ cat config/database.yml
mysql://root:[email protected]:3306/my_db_name

for Heroku: heroku config:set DATABASE_URL='mysql://root:[email protected]/my_db_name'

'sprintf': double precision in C

From your question it seems like you are using C99, as you have used %lf for double.

To achieve the desired output replace:

sprintf(aa, "%lf", a);


sprintf(aa, "%0.7f", a);

The general syntax "%A.B" means to use B digits after decimal point. The meaning of the A is more complicated, but can be read about here.

CSS: Hover one element, effect for multiple elements?

You'd need to use JavaScript to accomplish this, I think.



Adjust the values and element id's accordingly :)

Extracting specific selected columns to new DataFrame as a copy

Generic functional form

def select_columns(data_frame, column_names):
    new_frame = data_frame.loc[:, column_names]
    return new_frame

Specific for your problem above

selected_columns = ['A', 'C', 'D']
new = select_columns(old, selected_columns)

Xcode - Warning: Implicit declaration of function is invalid in C99

should call the function properly; like- Fibonacci:input

Is there any difference between a GUID and a UUID?

Microsoft's GUID's textual representation can be in the form of a UUID being surrounded by two curly braces {}.

Use Font Awesome Icon in Placeholder

Use placeholder="&#xF002;" in your input. You can find unicode in FontAwesome page . But you have to make sure add style="font-family: FontAwesome;" in your input.

Vertical dividers on horizontal UL menu

I do it as Pekka says. Put an inline style on each <li>:

style="border-right: solid 1px #555; border-left: solid 1px #111;"

Take off first and last as appropriate.

Using SED with wildcard

So, the concept of a "wildcard" in Regular Expressions works a bit differently. In order to match "any character" you would use "." The "*" modifier means, match any number of times.

See what's in a stash without applying it

From the man git-stash page:

The modifications stashed away by this command can be listed with git stash list, inspected with git stash show

show [<stash>]
       Show the changes recorded in the stash as a diff between the stashed state and
       its original parent. When no <stash> is given, shows the latest one. By default,
       the command shows the diffstat, but it will accept any format known to git diff
       (e.g., git stash show -p stash@{1} to view the second most recent stash in patch

To list the stashed modifications

git stash list

To show files changed in the last stash

git stash show

So, to view the content of the most recent stash, run

git stash show -p

To view the content of an arbitrary stash, run something like

git stash show -p stash@{1}

How do I lowercase a string in C?

to convert to lower case is equivalent to rise bit 0x60 if you restrict yourself to ASCII:

for(char *p = pstr; *p; ++p)
    *p = *p > 0x40 && *p < 0x5b ? *p | 0x60 : *p;

Getting all types in a namespace via reflection

Following code prints names of classes in specified namespace defined in current assembly.
As other guys pointed out, a namespace can be scattered between different modules, so you need to get a list of assemblies first.

string nspace = "...";

var q = from t in Assembly.GetExecutingAssembly().GetTypes()
        where t.IsClass && t.Namespace == nspace
        select t;
q.ToList().ForEach(t => Console.WriteLine(t.Name));

How can I get the source code of a Python function?

The inspect module has methods for retrieving source code from python objects. Seemingly it only works if the source is located in a file though. If you had that I guess you wouldn't need to get the source from the object.

The following tests inspect.getsource(foo) using Python 3.6:

import inspect

def foo(arg1,arg2):
    #do something with args
    a = arg1 + arg2
    return a

source_foo = inspect.getsource(foo)  # foo is normal function

source_max = inspect.getsource(max)  # max is a built-in function

This first prints:

def foo(arg1,arg2):
    #do something with args
    a = arg1 + arg2
    return a

Then fails on inspect.getsource(max) with the following error:

TypeError: <built-in function max> is not a module, class, method, function, traceback, frame, or code object

Calculate summary statistics of columns in dataframe

To clarify one point in @EdChum's answer, per the documentation, you can include the object columns by using df.describe(include='all'). It won't provide many statistics, but will provide a few pieces of info, including count, number of unique values, top value. This may be a new feature, I don't know as I am a relatively new user.

The Android emulator is not starting, showing "invalid command-line parameter"

There is currently a problem with R12 where the SDK location cannot contain any spaces.

The default installation location is: C:\Programme Files(x86)\Android\android-sdk. They are currently fixing the problem but you can currently work around it by changing the SDK location path in eclipse to C:\PROGRA~2\Android\android-sdk.

If you are running 32-bit Windows, change the path to C:\PROGRA~1\Android\android-sdk.

npm throws error without sudo

sudo chown -R `whoami` /usr/local/lib

os.walk without digging into directories below

I think the solution is actually very simple.



to only do first iteration of the for loop, there must be a more elegant way.

for root, dirs, files in os.walk(dir_name):
    for f in files:

The first time you call os.walk, it returns tulips for the current directory, then on next loop the contents of the next directory.

Take original script and just add a break.

def _dir_list(self, dir_name, whitelist):
    outputList = []
    for root, dirs, files in os.walk(dir_name):
        for f in files:
            if os.path.splitext(f)[1] in whitelist:
                outputList.append(os.path.join(root, f))
    return outputList

Delete rows with blank values in one particular column

 df[!($start_pc) | df$start_pc==""), ]

Using "like" wildcard in prepared statement

PreparedStatement ps = cn.prepareStatement("Select * from Users where User_FirstName LIKE ?");
ps.setString(1, name + '%');

Try this out.

Get the current year in JavaScript

Instantiate the class Date and call upon its getFullYear method to get the current year in yyyy format. Something like this:

let currentYear = new Date().getFullYear;

The currentYear variable will hold the value you are looking out for.

How can I force gradle to redownload dependencies?

Instead of removing your entire gradle cache, like some answers here are suggesting, you can delete the cache for a specific group or artifact id. I added the following function to my .bash_profile:

deleteGradleCache() {
  local id=$1
  if [ -z "$id" ]; then
    echo "Please provide an group or artifact id to delete"
    return 1
  find ~/.gradle/caches/ -type d -name "$id" -prune -exec rm -rf "{}" \; -print


$ deleteGradleCache

Then, on the next build or if you resync, gradle will re-download dependencies.

RESTful call in Java

There are several RESTful APIs around. I would recommend Jersey;

Client API documentation is here;

Location for the OAuth docs in the comment below is a dead link and has moved to

How to write LaTeX in IPython Notebook?

Using LaTeX syntax directly in a Markdown cell works for me. I'm using Jypiter 4.4.0.

I don't have to use %%latex magic command, I insist, simply a markdown cell:

\nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} & = \frac{4\pi}{c}\vec{\mathbf{j}} \\
\nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\
\nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} & = \vec{\mathbf{0}} \\
\nabla \cdot \vec{\mathbf{B}} & = 0

Renders to:

enter image description here

How should I copy Strings in Java?

Since strings are immutable, both versions are safe. The latter, however, is less efficient (it creates an extra object and in some cases copies the character data).

With this in mind, the first version should be preferred.

Is there a naming convention for MySQL?

Consistency is what everyone strongly suggest, the rest is upto you as long as it works.

For beginners its easy to get carried away and we name whatever we want at that time. This make sense at that point but a headache later.

foo foobar or foo_bar is great. We name our table straight forward as much as possible and only use underscore if they are two different words. studentregistration to student_registration

like @Zbyszek says, having a simple id is more than enough for the auto-increment. The simplier the better. Why do you need foo_id? We had the same problem early on, we named all our columns with the table prefix. like foo_id, foo_name, foo_age. We dropped the tablename now and kept only the col as short as possible.

Since we are using just an id for PK we will be using foo_bar_fk (tablename is unique, folowed by the unique PK, followed by the _fk) as foreign key. We don't add id to the col name because it is said that the name 'id' is always the PK of the given table. So we have just the tablename and the _fk at the end.

For constrains we remove all underscores and join with camelCase (tablename + Colname + Fk) foobarUsernameFk (for username_fk col). It's just a way we are following. We keep a documentation for every names structures.

When keeping the col name short, we should also keep an eye on the RESTRICTED names.

|               foobar               |
| id (PK for the current table)      |
| username_fk (PK of username table) |
| location (other column)            |
| tel (other column)                 |

java.sql.SQLException: - ORA-01000: maximum open cursors exceeded

If your application is a Java EE application running on Oracle WebLogic as the application server, a possible cause for this issue is the Statement Cache Size setting in WebLogic.

If the Statement Cache Size setting for a particular data source is about equal to, or greater than, the Oracle database maximum open cursor count setting, then all of the open cursors can be consumed by cached SQL statements that are held open by WebLogic, resulting in the ORA-01000 error.

To address this, reduce the Statement Cache Size setting for each WebLogic datasource that points to the Oracle database to be significantly less than the maximum cursor count setting on the database.

In the WebLogic 10 Admin Console, the Statement Cache Size setting for each data source can be found at Services (left nav) > Data Sources > (individual data source) > Connection Pool tab.

Trying to SSH into an Amazon Ec2 instance - permission error

BY default permission are not allowing the pem key. You just have to change the permission:

chmod 400 xyz.pem

and if ubuntu instance then connect using:

ssh -i xyz.pem [email protected]

How to Concatenate Numbers and Strings to Format Numbers in T-SQL?

You must cast your integers as string when trying to concatenate them into a varchar.


 SELECT  @ActualWeightDIMS = CAST(@Actual_Dims_Lenght AS varchar(10)) 
                              + 'x' + 
                             CAST(@Actual_Dims_Width as varchar(10)) 
                             + 'x' + CAST(@Actual_Dims_Height as varchar(10));

In SQL Server 2008, you can use the STR function:

   SELECT  @ActualWeightDIMS = STR(@Actual_Dims_Lenght) 
                              + 'x' + STR(@Actual_Dims_Width) 
                              + 'x' + STR(@Actual_Dims_Height);

How to use jQuery with TypeScript

In my case I had to do this

npm install @types/jquery --save-dev // install jquery type as dev dependency so TS can compile properly
npm install jquery --save // save jquery as a dependency

Then in the script file A.ts

import * as $ from "jquery";
... jquery code ...

Best way to detect Mac OS X or Windows computers with JavaScript or jQuery

Is this what you are looking for? Otherwise, let me know and I will remove this post.

Try this jQuery plugin:


This is based on quirksmode BrowserDetect a wrap for jQuery browser/os detection plugin.

For keen readers:

And more code around the plugin resides here:

How do I do a Date comparison in Javascript?

JavaScript's dates can be compared using the same comparison operators the rest of the data types use: >, <, <=, >=, ==, !=, ===, !==.

If you have two dates A and B, then A < B if A is further back into the past than B.

But it sounds like what you're having trouble with is turning a string into a date. You do that by simply passing the string as an argument for a new Date:

var someDate = new Date("12/03/2008");

or, if the string you want is the value of a form field, as it seems it might be:

var someDate = new Date(document.form1.Textbox2.value);

Should that string not be something that JavaScript recognizes as a date, you will still get a Date object, but it will be "invalid". Any comparison with another date will return false. When converted to a string it will become "Invalid Date". Its getTime() function will return NaN, and calling isNaN() on the date itself will return true; that's the easy way to check if a string is a valid date.

Are multiple `.gitignore`s frowned on?

I can think of at least two situations where you would want to have multiple .gitignore files in different (sub)directories.

  • Different directories have different types of file to ignore. For example the .gitignore in the top directory of your project ignores generated programs, while Documentation/.gitignore ignores generated documentation.

  • Ignore given files only in given (sub)directory (you can use /sub/foo in .gitignore, though).

Please remember that patterns in .gitignore file apply recursively to the (sub)directory the file is in and all its subdirectories, unless pattern contains '/' (so e.g. pattern name applies to any file named name in given directory and all its subdirectories, while /name applies to file with this name only in given directory).

What is the different between RESTful and RESTless

'RESTless' is a term not often used.

You can define 'RESTless' as any system that is not RESTful. For that it is enough to not have one characteristic that is required for a RESTful system.

Most systems are RESTless by this definition because they don't implement HATEOAS.

MySQL - Using If Then Else in MySQL UPDATE or SELECT Queries

Here's a query to update a table based on a comparison of another table. If record is not found in tableB, it will update the "active" value to "n". If it's found, will set the value to NULL

SET active = IF( IS NULL, 'n', NULL)";

Hope this helps someone else.

RedirectToAction with parameter

This might be years ago but anyways, this also depends on your Global.asax map route since you may add or edit parameters to fit what you want.



    public static void RegisterRoutes(RouteCollection routes)

            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            //new { controller = "Home", action = "Index", id = UrlParameter.Optional 
            new { controller = "Home", action = "Index", id = UrlParameter.Optional,
                  extraParam = UrlParameter.Optional // extra parameter you might need

then the parameters you'll need to pass will change to:

return RedirectToAction( "Main", new RouteValueDictionary( 
    new { controller = controllerName, action = "Main", Id = Id, extraParam = someVariable } ) );

How to get substring of NSString?

Here's a simple function that lets you do what you are looking for:

- (NSString *)getSubstring:(NSString *)value betweenString:(NSString *)separator
    NSRange firstInstance = [value rangeOfString:separator];
    NSRange secondInstance = [[value substringFromIndex:firstInstance.location + firstInstance.length] rangeOfString:separator];
    NSRange finalRange = NSMakeRange(firstInstance.location + separator.length, secondInstance.location);

    return [value substringWithRange:finalRange];


NSString *myName = [self getSubstring:@"This is my :name:, woo!!" betweenString:@":"];

php - push array into array - key issue

Use this..

$res_arr_values = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
    $res_arr_values[] = $row;

How do I update the GUI from another thread?

The easiest way I think:

   void Update()
           //do your update

download and install visual studio 2008

Microsoft Visual Studio 2008 Service Pack 1 (iso)

Version: SP1 File Name: VS2008SP1ENUX1512962.iso Date Published: 8/11/2008 File Size: 831.3 MB

Supported Operating System

    Windows Server 2003, Windows Server 2008, Windows Vista, Windows XP
    Minimum: 1.6 GHz CPU, 384 MB RAM, 1024x768 display, 5400 RPM hard disk
    Recommended: 2.2 GHz or higher CPU, 1024 MB or more RAM, 1280x1024 display, 7200 RPM or higher hard disk
    On Windows Vista: 2.4 GHz CPU, 768 MB RAM
    Maintain Internet connectivity during the installation of the service pack until seeing the “Installation Completed Successfully” message before disconnecting.

How to send Request payload to REST API in java?

I tried with a rest client.

Headers :

  • POST /r/gerrit/rpc/ChangeDetailService HTTP/1.1
  • Host:
  • User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:18.0) Gecko/20100101 Firefox/18.0
  • Accept: application/json
  • Accept-Language: null
  • Accept-Encoding: gzip,deflate,sdch
  • accept-charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
  • Content-Type: application/json; charset=UTF-8
  • Content-Length: 73
  • Connection: keep-alive

it works fine. I retrieve 200 OK with a good body.

Why do you set a status code in your request? and multiple declaration "Accept" with Accept:application/json,application/json,application/jsonrequest. just a statement is enough.

Delete a row in DataGridView Control in VB.NET

For Each row As DataGridViewRow In yourDGV.SelectedRows

This will delete all rows that had been selected.

proper name for python * operator?

For a colloquial name there is "splatting".

For arguments (list type) you use single * and for keyword arguments (dictionary type) you use double **.

Both * and ** is sometimes referred to as "splatting".

See for reference of this name being used:

How to JUnit test that two List<E> contain the same elements in the same order?

The equals() method on your List implementation should do elementwise comparison, so

assertEquals(argumentComponents, returnedComponents);

is a lot easier.

Modify XML existing content in C#

Using LINQ to xml if you are using framework 3.5

using System.Xml.Linq;

XDocument xmlFile = XDocument.Load("books.xml"); 
var query = from c in xmlFile.Elements("catalog").Elements("book")    
            select c; 
foreach (XElement book in query) 
    book.Attribute("attr1").Value = "MyNewValue";

How to display and hide a div with CSS?

Html Code :

    <a id="f">Show First content!</a>
    <a id="s">Show Second content!!</a>
    <div class="a">Default Content</div>
    <div class="ab hideDiv">First content</div>
    <div class="abc hideDiv">Second content</div>

Script code:

$(document).ready(function() {
    }).mouseout(function() {

    }).mouseout(function() {

css code:


Add colorbar to existing axis

The colorbar has to have its own axes. However, you can create an axes that overlaps with the previous one. Then use the cax kwarg to tell fig.colorbar to use the new axes.

For example:

import numpy as np
import matplotlib.pyplot as plt

data = np.arange(100, 0, -1).reshape(10, 10)

fig, ax = plt.subplots()
cax = fig.add_axes([0.27, 0.8, 0.5, 0.05])

im = ax.imshow(data, cmap='gist_earth')
fig.colorbar(im, cax=cax, orientation='horizontal')

enter image description here

How to pass an ArrayList to a varargs method parameter?

Source article: Passing a list as an argument to a vararg method

Use the toArray(T[] arr) method.

.getMap(locations.toArray(new WorldLocation[locations.size()]))

(toArray(new WorldLocation[0]) also works, but you would allocate a zero-length array for no reason.)

Here's a complete example:

public static void method(String... strs) {
    for (String s : strs)

    List<String> strs = new ArrayList<String>();
    method(strs.toArray(new String[strs.size()]));
    //     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

What is function overloading and overriding in php?

Overloading Example

class overload {
    public $name;
    public function __construct($agr) {
        $this->name = $agr;
    public function __call($methodname, $agrument) {
         if($methodname == 'sum2') {

          if(count($agrument) == 2) {
              $this->sum($agrument[0], $agrument[1]);
          if(count($agrument) == 3) {

              echo $this->sum1($agrument[0], $agrument[1], $agrument[2]);
    public function sum($a, $b) {
        return $a + $b;
    public function sum1($a,$b,$c) {

        return $a + $b + $c;
$object = new overload('Sum');
echo $object->sum2(1,2,3);

Apache: Restrict access to specific source IP inside virtual host

If you are using apache 2.2 inside your virtual host you should add following directive (mod_authz_host):

Order deny,allow
Deny from all
Allow from

You can even specify a subnet

Allow from 10.0.0

Apache 2.4 looks like a little different as configuration. Maybe better you specify which version of apache are you using.

`getchar()` gives the same output as the input string

There is an underlying buffer/stream that getchar() and friends read from. When you enter text, the text is stored in a buffer somewhere. getchar() can stream through it one character at a time. Each read returns the next character until it reaches the end of the buffer. The reason it's not asking you for subsequent characters is that it can fetch the next one from the buffer.

If you run your script and type directly into it, it will continue to prompt you for input until you press CTRL+D (end of file). If you call it like ./program < myInput where myInput is a text file with some data, it will get the EOF when it reaches the end of the input. EOF isn't a character that exists in the stream, but a sentinel value to indicate when the end of the input has been reached.

As an extra warning, I believe getchar() will also return EOF if it encounters an error, so you'll want to check ferror(). Example below (not tested, but you get the idea).

main() {
    int c;
    do {
        c = getchar();
        if (c == EOF && ferror()) {
        else {
    while(c != EOF);

Access denied; you need (at least one of) the SUPER privilege(s) for this operation

Full Solution

All the above solutions are fine. And here I'm gonna combine all the solutions so that it should work for all the situations.

  1. Fixed DEFINER

For Linux and Mac

sed -i old 's/\DEFINER\=`[^`]*`@`[^`]*`//g' file.sql

For Windows
download atom or notepad++, open your dump sql file with atom or notepad++, press Ctrl+F
search the word DEFINER, and remove the line DEFINER=admin@% (or may be little different for you) from everywhere and save the file.
As for example
before removing that line: CREATE DEFINER=admin@% PROCEDURE MyProcedure
After removing that line: CREATE PROCEDURE MyProcedure

  1. Remove the 3 lines Remove all these 3 lines from the dump file. You can use sed command or open the file in Atom editor and search for each line and then remove the line.
    Example: Open Dump2020.sql in Atom, Press ctrl+F, search SET @@SESSION.SQL_LOG_BIN= 0, remove that line.
SET @@GLOBAL.GTID_PURGED=/*!80000 '+'*/ '';
  1. There an issue with your generated file You might face some issue if your generated dump.sql file is not proper. But here, I'm not gonna explain how to generate a dump file. But you can ask me (_)

Searching a string in eclipse workspace

For Mac:

Quick Text Search: Shift + Cmd + L

enter image description here

All other search (like File Search, Git Search, Java Search etc): Ctrl + H

enter image description here

Completely uninstall PostgreSQL 9.0.4 from Mac OSX Lion?

Uninstallation :

sudo /Library/PostgreSQL/9.6/

Removing the data file :

sudo rm -rf /Library/PostgreSQL

Removing the configs :

sudo rm /etc/postgres-reg.ini

And thats it.

How to disable XDebug

Inspired by PHPStorm right click on a file -> debug -> ...


the important stuff is -dxdebug.remote_enable=0 -dxdebug.default_enable=0

Behaviour of increment and decrement operators in Python

In Python, a distinction between expressions and statements is rigidly enforced, in contrast to languages such as Common Lisp, Scheme, or Ruby.


So by introducing such operators, you would break the expression/statement split.

For the same reason you can't write

if x = 0:
  y = 1

as you can in some other languages where such distinction is not preserved.

Find Process Name by its Process ID

SET /a pid=1600
FOR /f "skip=3delims=" %%a IN ('tasklist') DO (
 SET "found=%%a"
 SET /a foundpid=!found:~26,8!
 IF %pid%==!foundpid! echo found %pid%=!found:~0,24%!


...set PID to suit your circumstance.

How can I get the content of CKEditor using JQuery?

Using Pure Vanilla Javascript / Jquery or in any javascript library :

If you have Ckeditor loaded in below text-area:

 <textarea name="editor1" id="editor1"></textarea>

Then you can get content inside textarea as below:

var txtNotes = document.getElementsByClassName('ck-content')[0].innerHTML;

JavaScript file upload size validation

Using jquery:

<form action="upload" enctype="multipart/form-data" method="post">
    Upload image:
    <input id="image-file" type="file" name="file" />
    <input type="submit" value="Upload" />

    <script type="text/javascript">
        $('#image-file').bind('change', function() {
            alert('This file size is: ' + this.files[0].size/1024/1024 + "MiB");


C program to check little vs. big endian

In short, yes.

Suppose we are on a 32-bit machine.

If it is little endian, the x in the memory will be something like:

       higher memory

so (char*)(&x) == 1, and *y+48 == '1'.

If it is big endian, it will be:


so this one will be '0'.

List of all unique characters in a string?

For completeness sake, here's another recipe that sorts the letters as a byproduct of the way it works:

>>> from itertools import groupby
>>> ''.join(k for k, g in groupby(sorted("aaabcabccd")))

SQL "between" not inclusive

Just use the time stamp as date:

SELECT * FROM Cases WHERE date(created_at)='2013-05-01' 

Removing leading zeroes from a field in a SQL statement

In case you want to remove the leading zeros from a string with a unknown size.

You may consider using the STUFF command.

Here is an example of how it would work.


See in fiddler various scenarios it will cover

Regex to accept alphanumeric and some special character in Javascript?


/^[ A-Za-z0-9_@./#&+-]*$/

You can also use the character class \w to replace A-Za-z0-9_

Linq to Entities join vs groupjoin

Let's suppose you have two different classes:

public class Person
    public string Name, Email;
    public Person(string name, string email)
        Name = name;
        Email = email;
class Data
    public string Mail, SlackId;
    public Data(string mail, string slackId)
        Mail = mail;
        SlackId = slackId;

Now, let's Prepare data to work with:

var people = new Person[]
        new Person("Sudi", "[email protected]"),
        new Person("Simba", "[email protected]"),
        new Person("Sarah", string.Empty)
    var records = new Data[]
        new Data("[email protected]", "Sudi_Try"),
        new Data("[email protected]", "Sudi@Test"),
        new Data("[email protected]", "SimbaLion")

You will note that [email protected] has got two slackIds. I have made that for demonstrating how Join works.

Let's now construct the query to join Person with Data:

var query = people.Join(records,
        x => x.Email,
        y => y.Mail,
        (person, record) => new { Name = person.Name, SlackId = record.SlackId});

After constructing the query, you could also iterate over it with a foreach like so:

foreach (var item in query)
        Console.WriteLine($"{item.Name} has Slack ID {item.SlackId}");

Let's also output the result for GroupJoin:

            x => x.Email,
            y => y.Mail,
            (person, recs) => new {
                Name = person.Name,
                SlackIds = recs.Select(r => r.SlackId).ToArray() // You could materialize //whatever way you want.

You will notice that the GroupJoin will put all SlackIds in a single group.

how to download file using AngularJS and calling MVC API?

Here you have the angularjs http request to the API that any client will have to do. Just adapt the WS url and params (if you have) to your case. It's a mixture between Naoe's answer and this one:

    url: '/path/to/your/API',
    method: 'POST',
    params: {},
    headers: {
        'Content-type': 'application/pdf',
    responseType: 'arraybuffer'
}).success(function (data, status, headers, config) {
    // TODO when WS success
    var file = new Blob([data], {
        type: 'application/csv'
    //trick to download store a file having its URL
    var fileURL = URL.createObjectURL(file);
    var a = document.createElement('a');
    a.href = fileURL; = '_blank'; = 'yourfilename.pdf';
    document.body.appendChild(a); //create the link "a"; //click the link "a"
    document.body.removeChild(a); //remove the link "a"
}).error(function (data, status, headers, config) {
    //TODO when WS error

Explanation of the code:

  1. Angularjs request a file.pdf at the URL: /path/to/your/API.
  2. Success is received on the response
  3. We execute a trick with JavaScript on the front-end:
    • Create an html link ta: <a>.
    • Click the hyperlink <a> tag, using the JS click() function
  4. Remove the html <a> tag, after its click.

Python 3 Online Interpreter / Shell

Ideone supports Python 2.6 and Python 3

How can I display an RTSP video stream in a web page?

One option would be to use some sort of streaming server/gateway. I tried various solutions (vlc, ffmpeg and a few more) and the one that worked best for me was Janus WebRTC server. It is somewhat difficult to set up, and you will have to compile it from source(when I tried it the version in Ubuntu repos didn't have RTSP support), but they have detailed compiling instructions and documentation on how to set everything up.

I managed to get video and audio feed from 3 FullHD cameras on local network with very little delay. I can confirm it works with Dahua and Hikvision cameras (not sure if all models).

What I used was Ubuntu Server 18.04 running Apache web server, and Chrome as a browser (it did not work on Firefox by default but perhaps there are workarounds for it).

SQL Server: How to check if CLR is enabled?

This is @Jason's answer but with simplified output

SELECT name, CASE WHEN value = 1 THEN 'YES' ELSE 'NO' END AS 'Enabled'
FROM sys.configurations WHERE name = 'clr enabled'

The above returns the following:

| name        | Enabled |
| clr enabled | YES     |

Tested on SQL Server 2017

Counting Number of Letters in a string variable

If you don't need the leading and trailing spaces :


Streaming a video file to an html5 video player with Node.js so that the video controls continue to work?

The accepted answer to this question is awesome and should remain the accepted answer. However I ran into an issue with the code where the read stream was not always being ended/closed. Part of the solution was to send autoClose: true along with start:start, end:end in the second createReadStream arg.

The other part of the solution was to limit the max chunksize being sent in the response. The other answer set end like so:

var end = positions[1] ? parseInt(positions[1], 10) : total - 1;

...which has the effect of sending the rest of the file from the requested start position through its last byte, no matter how many bytes that may be. However the client browser has the option to only read a portion of that stream, and will, if it doesn't need all of the bytes yet. This will cause the stream read to get blocked until the browser decides it's time to get more data (for example a user action like seek/scrub, or just by playing the stream).

I needed this stream to be closed because I was displaying the <video> element on a page that allowed the user to delete the video file. However the file was not being removed from the filesystem until the client (or server) closed the connection, because that is the only way the stream was getting ended/closed.

My solution was just to set a maxChunk configuration variable, set it to 1MB, and never pipe a read a stream of more than 1MB at a time to the response.

// same code as accepted answer
var end = positions[1] ? parseInt(positions[1], 10) : total - 1;
var chunksize = (end - start) + 1;

// poor hack to send smaller chunks to the browser
var maxChunk = 1024 * 1024; // 1MB at a time
if (chunksize > maxChunk) {
  end = start + maxChunk - 1;
  chunksize = (end - start) + 1;

This has the effect of making sure that the read stream is ended/closed after each request, and not kept alive by the browser.

I also wrote a separate StackOverflow question and answer covering this issue.

Rendering HTML inside textarea

An addendum to this. You can use character entities (such as changing <div> to &lt;div&gt;) and it will render in the textarea. But when it is saved, the value of the textarea is the text as rendered. So you don't need to de-encode. I just tested this across browsers (ie back to 11).

How to delete an SVN project from SVN repository

Disposing of a Working Copy

Subversion doesn't track either the state or the existence of working copies on the server, so there's no server overhead to keeping working copies around. Likewise, there's no need to let the server know that you're going to delete a working copy.

If you're likely to use a working copy again, there's nothing wrong with just leaving it on disk until you're ready to use it again, at which point all it takes is an svn update to bring it up to date and ready for use.

However, if you're definitely not going to use a working copy again, you can safely delete the entire thing using whatever directory removal capabilities your operating system offers. We recommend that before you do so you run svn status and review any files listed in its output that are prefixed with a ? to make certain that they're not of importance.


How to use putExtra() and getExtra() for string data

Best Method...


Intent intent = new Intent(SendingActivity.this, RecievingActivity.class);
intent.putExtra("keyName", value);  // pass your values and retrieve them in the other Activity using keyName


 Bundle extras = intent.getExtras();
    if(extras != null)
    String data = extras.getString("keyName"); // retrieve the data using keyName 

/// shortest way to recieve data..

String data = getIntent().getExtras().getString("keyName","defaultKey");

//This requires api 12. //the second parameter is optional . If keyName is null then use the defaultkey as data.

Get a random boolean in python?

u could try this it produces randomly generated array of true and false :

a=[bool(i) for i in np.array(np.random.randint(0,2,10))]

out: [True, True, True, True, True, False, True, False, True, False]

Using Javascript in CSS

IE supports CSS expressions:

width:expression(document.body.clientWidth > 955 ? "955px": "100%" );

but they are not standard and are not portable across browsers. Avoid them if possible. They are deprecated since IE8.

Install gitk on Mac

I just had the same problem and solved it as follows:

  1. Download the official git package for Mac from
  2. Install the package. This places all the binaries in /usr/local/git/bin.
  3. Optionally run the included script to make gitk accessible outside of terminals
  4. Either add /usr/local/git/bin to your PATH or use an alias (alias gitk='/usr/local/git/bin/gitk')

Best way to check for nullable bool in a condition expression (if ...)

If you only want to test for true against null/false, One I've just used and reads quite well is

bool? someCondition = null
if (someCondition.Equals(true))

Update a table using JOIN in SQL Server?

Seems like SQL Server 2012 can handle the old update syntax of Teradata too:

SET a.CalculatedColumn= b.[Calculated Column]
FROM table1 a, table2 b 
    b.[common field]= a.commonfield
AND a.BatchNO = '110'

If I remember correctly, 2008R2 was giving error when I tried similar query.

java.lang.IllegalStateException: The specified child already has a parent

I had this problem and couldn't solve it in Java code. The problem was with my xml.

I was trying to add a textView to a container, but had wrapped the textView inside a LinearLayout.

This was the original xml file:

<?xml version="1.0" encoding="utf-8"?>_x000D_
<LinearLayout xmlns:android=""_x000D_
    <TextView xmlns:android=""_x000D_

Now with the LinearLayout removed:

<TextView xmlns:android=""_x000D_

This didn't seem like much to me but it did the trick, and I didn't change my Java code at all. It was all in the xml.

How to search all loaded scripts in Chrome Developer Tools?

In Widows it is working for me. Control Shift F and then it opens a search window at the bottom. Make sure you expand the bottom area to see the new search window.

enter image description here

Working with dictionaries/lists in R

Shorter variation of Dirk's answer:

# Create a Color Palette Dictionary 
> color <- c('', 'gold', 'dark.gray')
> hex <- c('#336A91', '#F3C117', '#7F7F7F')

> # Create List
> color_palette <- as.list(hex)
> # Name List Items
> names(color_palette) <- color
> color_palette
[1] "#336A91"

[1] "#F3C117"

[1] "#7F7F7F"

Remove non-utf8 characters from string

From recent patch to Drupal's Feeds JSON parser module:

//remove everything except valid letters (from any language)
$raw = preg_replace('/(?:\\\\u[\pL\p{Zs}])+/', '', $raw);

If you're concerned yes it retains spaces as valid characters.

Did what I needed. It removes widespread nowadays emoji-characters that don't fit into MySQL's 'utf8' character set and that gave me errors like "SQLSTATE[HY000]: General error: 1366 Incorrect string value".

For details see

Large Numbers in Java

You can use the BigInteger class for integers and BigDecimal for numbers with decimal digits. Both classes are defined in java.math package.


BigInteger reallyBig = new BigInteger("1234567890123456890");
BigInteger notSoBig = new BigInteger("2743561234");
reallyBig = reallyBig.add(notSoBig);

Add data to JSONObject

The answer is to use a JSONArray as well, and to dive "deep" into the tree structure:

JSONArray arr = new JSONArray();
arr.put (...); // a new JSONObject()
arr.put (...); // a new JSONObject()

JSONObject json = new JSONObject();
json.put ("aoColumnDefs",arr);

How to validate a date?

var isDate_ = function(input) {
        var status = false;
        if (!input || input.length <= 0) {
          status = false;
        } else {
          var result = new Date(input);
          if (result == 'Invalid Date') {
            status = false;
          } else {
            status = true;
        return status;

this function returns bool value of whether the input given is a valid date or not. ex:

if(isDate_(var_date)) {
  // statements if the date is valid
} else {
  // statements if not valid

Advantages of using display:inline-block vs float:left in CSS

In 3 words: inline-block is better.

Inline Block

The only drawback to the display: inline-block approach is that in IE7 and below an element can only be displayed inline-block if it was already inline by default. What this means is that instead of using a <div> element you have to use a <span> element. It's not really a huge drawback at all because semantically a <div> is for dividing the page while a <span> is just for covering a span of a page, so there's not a huge semantic difference. A huge benefit of display:inline-block is that when other developers are maintaining your code at a later point, it is much more obvious what display:inline-block and text-align:right is trying to accomplish than a float:left or float:right statement. My favorite benefit of the inline-block approach is that it's easy to use vertical-align: middle, line-height and text-align: center to perfectly center the elements, in a way that is intuitive. I found a great blog post on how to implement cross-browser inline-block, on the Mozilla blog. Here is the browser compatibility.


The reason that using the float method is not suited for layout of your page is because the float CSS property was originally intended only to have text wrap around an image (magazine style) and is, by design, not best suited for general page layout purposes. When changing floated elements later, sometimes you will have positioning issues because they are not in the page flow. Another disadvantage is that it generally requires a clearfix otherwise it may break aspects of the page. The clearfix requires adding an element after the floated elements to stop their parent from collapsing around them which crosses the semantic line between separating style from content and is thus an anti-pattern in web development.

Any white space problems mentioned in the link above could easily be fixed with the white-space CSS property.


SitePoint is a very credible source for web design advice and they seem to have the same opinion that I do:

If you’re new to CSS layouts, you’d be forgiven for thinking that using CSS floats in imaginative ways is the height of skill. If you have consumed as many CSS layout tutorials as you can find, you might suppose that mastering floats is a rite of passage. You’ll be dazzled by the ingenuity, astounded by the complexity, and you’ll gain a sense of achievement when you finally understand how floats work.

Don’t be fooled. You’re being brainwashed.

2015 Update - Flexbox is a good alternative for modern browsers:

.container {
  display: flex; /* or inline-flex */

.item {
  flex: none | [ <'flex-grow'> <'flex-shrink'>? || <'flex-basis'> ]

More info

Dec 21, 2016 Update

Bootstrap 4 is removing support for IE9, and thus is getting rid of floats from rows and going full Flexbox.

Pull request #21389

Illegal string offset Warning PHP


You're trying to access a string as if it were an array, with a key that's a string. string will not understand that. In code we can see the problem:

// PHP Warning:  Illegal string offset 'hello' in php shell code on line 1

// No errors.

array("hello" => "val")["hello"];
// No errors. This is *probably* what you wanted.

In depth

Let's see that error:

Warning: Illegal string offset 'port' in ...

What does it say? It says we're trying to use the string 'port' as an offset for a string. Like this:

$a_string = "string";

// This is ok:
echo $a_string[0]; // s
echo $a_string[1]; // t
echo $a_string[2]; // r
// ...

// !! Not good:
echo $a_string['port'];
// !! Warning: Illegal string offset 'port' in ...

What causes this?

For some reason you expected an array, but you have a string. Just a mix-up. Maybe your variable was changed, maybe it never was an array, it's really not important.

What can be done?

If we know we should have an array, we should do some basic debugging to determine why we don't have an array. If we don't know if we'll have an array or string, things become a bit trickier.

What we can do is all sorts of checking to ensure we don't have notices, warnings or errors with things like is_array and isset or array_key_exists:

$a_string = "string";
$an_array = array('port' => 'the_port');

if (is_array($a_string) && isset($a_string['port'])) {
    // No problem, we'll never get here.
    echo $a_string['port'];

if (is_array($an_array) && isset($an_array['port'])) {
    // Ok!
    echo $an_array['port']; // the_port

if (is_array($an_array) && isset($an_array['unset_key'])) {
    // No problem again, we won't enter.
    echo $an_array['unset_key'];

// Similar, but with array_key_exists
if (is_array($an_array) && array_key_exists('port', $an_array)) {
    // Ok!
    echo $an_array['port']; // the_port

There are some subtle differences between isset and array_key_exists. For example, if the value of $array['key'] is null, isset returns false. array_key_exists will just check that, well, the key exists.

Convert a numpy.ndarray to string(or bytes) and convert it back to numpy.ndarray

I know, I am late but here is the correct way of doing it. using base64. This technique will convert the array to string.

import base64
import numpy as np
random_array = np.random.randn(32,32)
string_repr = base64.binascii.b2a_base64(random_array).decode("ascii")
array = np.frombuffer(base64.binascii.a2b_base64(string_repr.encode("ascii"))) 

For array to string

Convert binary data to a line of ASCII characters in base64 coding and decode to ASCII to get string repr.

For string to array

First, encode the string in ASCII format then Convert a block of base64 data back to binary and return the binary data.

Execution failed for task :':app:mergeDebugResources'. Android Studio

click here for the image

  1. Click Gradle in the right side tab

  2. Click the toggle offline icon (enable the Gradle online)

  3. Now try building the project

    And that's it!

Monitoring the Full Disclosure mailinglist

Two generic ways to do the same thing... I'm not aware of any specific open solutions to do this, but it'd be rather trivial to do.

You could write a daily or weekly cron/jenkins job to scrape the previous time period's email from the archive looking for your keyworkds/combinations. Sending a batch digest with what it finds, if anything.

But personally, I'd Setup a specific email account to subscribe to the various security lists you're interested in. Add a simple automated script to parse the new emails for various keywords or combinations of keywords, when it finds a match forward that email on to you/your team. Just be sure to keep the keywords list updated with new products you're using.

You could even do this with a gmail account and custom rules, which is what I currently do, but I have setup an internal inbox in the past with a simple python script to forward emails that were of interest.

Integer to IP Address - C

Here's a simple method to do it: The (ip >> 8), (ip >> 16) and (ip >> 24) moves the 2nd, 3rd and 4th bytes into the lower order byte, while the & 0xFF isolates the least significant byte at each step.

void print_ip(unsigned int ip)
    unsigned char bytes[4];
    bytes[0] = ip & 0xFF;
    bytes[1] = (ip >> 8) & 0xFF;
    bytes[2] = (ip >> 16) & 0xFF;
    bytes[3] = (ip >> 24) & 0xFF;   
    printf("%d.%d.%d.%d\n", bytes[3], bytes[2], bytes[1], bytes[0]);        

There is an implied bytes[0] = (ip >> 0) & 0xFF; at the first step.

Use snprintf() to print it to a string.

What primitive data type is time_t?

You could always use something like mktime to create a known time (midnight, last night) and use difftime to get a double-precision time difference between the two. For a platform-independant solution, unless you go digging into the details of your libraries, you're not going to do much better than that. According to the C spec, the definition of time_t is implementation-defined (meaning that each implementation of the library can define it however they like, as long as library functions with use it behave according to the spec.)

That being said, the size of time_t on my linux machine is 8 bytes, which suggests a long int or a double. So I did:

int main()
        printf ("%ld\n", time(NULL));
        printf ("%f\n", time(NULL));
    return 0;

The time given by the %ld increased by one each step and the float printed 0.000 each time. If you're hell-bent on using printf to display time_ts, your best bet is to try your own such experiment and see how it work out on your platform and with your compiler.

ImproperlyConfigured: You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings

In my case it was the use of the call_command module that posed a problem.
I added set DJANGO_SETTINGS_MODULE=mysite.settings but it didn't work.

I finally found it:

add these lines at the top of the script, and the order matters.

import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")

import django

from import call_command

Sort Java Collection

To be super clear, Collection.sort(list, compartor) does not return anything so something like this list = Collection.sort(list, compartor); will throw an error (void cannot be converted to [list type]) and should instead be Collection.sort(list, compartor)

Best way to encode Degree Celsius symbol into web page?

I'm not sure why this hasn't come up yet but why don't you use &#8451; (?) or &#8457; (?) for Celsius and Fahrenheit respectively!

Check if a value is in an array or not with Excel VBA

Use Match() function in excel VBA to check whether the value exists in an array.

Sub test()
    Dim x As Long

    vars1 = Array("Abc", "Xyz", "Examples")
    vars2 = Array("Def", "IJK", "MNO")

    If IsNumeric(Application.Match(Range("A1").Value, vars1, 0)) Then
        x = 1
    ElseIf IsNumeric(Application.Match(Range("A1").Value, vars2, 0)) Then
        x = 1
    End If

    MsgBox x
End Sub

how to pass value from one php page to another using session

Solution using just POST - no $_SESSION


<form action="page2.php" method="post">
    <textarea name="textarea1" id="textarea1"></textarea><br />
    <input type="submit" value="submit" />


    // this page outputs the contents of the textarea if posted
    $textarea1 = ""; // set var to avoid errors
        $textarea1 = $_POST['textarea1']
<textarea><?php echo $textarea1;?></textarea>

Solution using $_SESSION and POST



    session_start(); // needs to be before anything else on page to use $_SESSION
    $textarea1 = "";
        $_SESSION['textarea1'] = $_POST['textarea1'];


<form action="page1.php" method="post">
    <textarea name="textarea1" id="textarea1"></textarea><br />
    <input type="submit" value="submit" />
<br /><br />
<a href="page2.php">Go to page2</a>


    session_start(); // needs to be before anything else on page to use $_SESSION
    // this page outputs the textarea1 from the session IF it exists
    $textarea1 = ""; // set var to avoid errors
        $textarea1 = $_SESSION['textarea1']
<textarea><?php echo $textarea1;?></textarea>

WARNING!!! - This contains no validation!!!

Convert Time DataType into AM PM Format:

    select right(convert(varchar(20),getdate(),100),7)

How do I compute the intersection point of two lines?

img And You can use this kode

class Nokta:
def __init__(self,x,y):
class Dogru:
def __init__(self,a,b):

def Kesisim(self,Dogru_b):
    x1= self.a.x
    y1= self.a.y
    #Notlardaki denklemleri kullandim
    pay1=((x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3))      
    pay2=((x2-x1) * (y1 - y3) - (y2 - y1) * (x1 - x3))
    payda=((y4 - y3) *(x2-x1)-(x4 - x3)*(y2 - y1))        

    if pay1==0 and pay2==0 and payda==0:

    elif payda==0:               
        print("DOGRULAR BIRBIRNE PARALELDIR")        
        ua=pay1/payda if payda else 0                   
        ub=pay2/payda  if payda else 0  
        #x ve y buldum 
        print("DOGRULAR {},{} NOKTASINDA KESISTI".format(x,y))

How to find a whole word in a String in java

A much simpler way to do this is to use split():

String match = "123woods";
String text = "I will come and meet you at the 123woods";

String[] sentence = text.split();
for(String word: sentence)
        return true;
return false;

This is a simpler, less elegant way to do the same thing without using tokens, etc.

How do I disable the resizable property of a textarea?

You can simply disable the textarea property like this:

textarea {
    resize: none;

To disable vertical or horizontal resizing, use

resize: vertical;


resize: horizontal;

HTTP Request in Kotlin

You can use kohttp library. It is a Kotlin DSL HTTP client. It supports the features of square.okhttp and provides a clear DSL for them. KoHttp async calls are powered by coroutines.

httpGet extension function

val response: Response = "".httpGet()

you can also use async call with coroutines

val response: Deferred<Response> = "".asyncHttpGet()

or DSL function for more complex requests

val response: Response = httpGet {
    host = ""
    path = "/search"
    param {
       "q" to "iphone"
       "safe" to "off"

You can find more details in docs

To get it with gradle use

implementation 'io.github.rybalkinsd:kohttp:0.12.0'

Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. The statement has been terminated

You could set the CommandTimeout property of the SQL Command to allow for the long running SQL transaction.

You might also need to look at the SQL Query that is causing the timeout.

How to determine if a String has non-alphanumeric characters?

Though it won't work for numbers, you can check if the lowercase and uppercase values are same or not, For non-alphabetic characters they will be same, You should check for number before this for better usability

To compare two elements(string type) in XSLT?

First of all, the provided long code:

        <xsl:when test="OU_NAME='OU_ADDR1'">   --comparing two elements coming from XML             
            <!--remove if  adrees already contain  operating unit name <xsl:value-of select="OU_NAME"/> <fo:block/>-->
            <xsl:if test="OU_ADDR1 !='' ">
                <xsl:value-of select="OU_ADDR1"/>
            <xsl:if test="LE_ADDR2 !='' ">
                <xsl:value-of select="OU_ADDR2"/>
            <xsl:if test="LE_ADDR3 !='' ">
                <xsl:value-of select="OU_ADDR3"/>
            <xsl:if test="OU_TOWN_CITY !=''">
                <xsl:value-of select="OU_TOWN_CITY"/>,
                <fo:leader leader-pattern="space" leader-length="2.0pt"/>
            <xsl:value-of select="OU_REGION2"/>
            <fo:leader leader-pattern="space" leader-length="3.0pt"/>
            <xsl:value-of select="OU_POSTALCODE"/>
            <xsl:value-of select="OU_COUNTRY"/>
            <xsl:value-of select="OU_NAME"/>
            <xsl:if test="OU_ADDR1 !='' ">
                <xsl:value-of select="OU_ADDR1"/>
            <xsl:if test="LE_ADDR2 !='' ">
                <xsl:value-of select="OU_ADDR2"/>
            <xsl:if test="LE_ADDR3 !='' ">
                <xsl:value-of select="OU_ADDR3"/>
            <xsl:if test="OU_TOWN_CITY !=''">
                <xsl:value-of select="OU_TOWN_CITY"/>,
                <fo:leader leader-pattern="space" leader-length="2.0pt"/>
            <xsl:value-of select="OU_REGION2"/>
            <fo:leader leader-pattern="space" leader-length="3.0pt"/>
            <xsl:value-of select="OU_POSTALCODE"/>
            <xsl:value-of select="OU_COUNTRY"/>

is equivalent to this, much shorter code:

<xsl:if test="not(OU_NAME='OU_ADDR1)'">
              <xsl:value-of select="OU_NAME"/>
            <xsl:if test="OU_ADDR1 !='' ">
                <xsl:value-of select="OU_ADDR1"/>
            <xsl:if test="LE_ADDR2 !='' ">
                <xsl:value-of select="OU_ADDR2"/>
            <xsl:if test="LE_ADDR3 !='' ">
                <xsl:value-of select="OU_ADDR3"/>
            <xsl:if test="OU_TOWN_CITY !=''">
                <xsl:value-of select="OU_TOWN_CITY"/>,
                <fo:leader leader-pattern="space" leader-length="2.0pt"/>
            <xsl:value-of select="OU_REGION2"/>
            <fo:leader leader-pattern="space" leader-length="3.0pt"/>
            <xsl:value-of select="OU_POSTALCODE"/>
            <xsl:value-of select="OU_COUNTRY"/>

Now, to your question:

how to compare two elements coming from xml as string

In Xpath 1.0 strings can be compared only for equality (or inequality), using the operator = and the function not() together with the operator =.

$str1 = $str2

evaluates to true() exactly when the string $str1 is equal to the string $str2.

not($str1 = $str2)

evaluates to true() exactly when the string $str1 is not equal to the string $str2.

There is also the != operator. It generally should be avoided because it has anomalous behavior whenever one of its operands is a node-set.

Now, the rules for comparing two element nodes are similar:

$el1 = $el2

evaluates to true() exactly when the string value of $el1 is equal to the string value of $el2.

not($el1 = $el2)

evaluates to true() exactly when the string value of $el1 is not equal to the string value of $el2.

However, if one of the operands of = is a node-set, then

 $ns = $str

evaluates to true() exactly when there is at least one node in the node-set $ns1, whose string value is equal to the string $str

$ns1 = $ns2

evaluates to true() exactly when there is at least one node in the node-set $ns1, whose string value is equal to the string value of some node from $ns2

Therefore, the expression:


evaluates to true() only when there is at least one element child of the current node that is named OU_NAME and whose string value is the string 'OU_ADDR1'.

This is obviously not what you want!

Most probably you want:


This expression evaluates to true exactly there is at least one OU_NAME child of the current node and one OU_ADDR1 child of the current node with the same string value.

Finally, in XPath 2.0, strings can be compared also using the value comparison operators lt, le, eq, gt, ge and the inherited from XPath 1.0 general comparison operator =.

Trying to evaluate a value comparison operator when one or both of its arguments is a sequence of more than one item results in error.

How to check if element is visible after scrolling?

Simple modification for scrollable div (container)

var isScrolledIntoView = function(elem, container) {
    var containerHeight = $(container).height();
    var elemTop = $(elem).position().top;
    var elemBottom = elemTop + $(elem).height();
    return (elemBottom > 0 && elemTop < containerHeight);

NOTE: this does not work if the element is larger than the scrollable div.

For each row in an R dataframe

I was curious about the time performance of the non-vectorised options. For this purpose, I have used the function f defined by knguyen

f <- function(x, output) {
  wellName <- x[1]
  plateName <- x[2]
  wellID <- 1
  print(paste(wellID, x[3], x[4], sep=","))
  cat(paste(wellID, x[3], x[4], sep=","), file= output, append = T, fill = T)

and a dataframe like the one in his example:

n = 100; #number of rows for the data frame
d <- data.frame( name = LETTERS[ 25, n, replace=T ) ],
                  plate = paste0( "P", 1:n ),
                  value1 = 1:n,
                  value2 = (1:n)*10 )

I included two vectorised functions (for sure quicker than the others) in order to compare the cat() approach with a write.table() one...

library( "microbenchmark" )
library( foreach )
library( iterators )

tm <- microbenchmark(S1 =
                       apply(d, 1, f, output = 'outputfile1'),
                     S2 = 
                       for(i in 1:nrow(d)) {
                         row <- d[i,]
                         # do stuff with row
                         f(row, 'outputfile2')
                     S3 = 
                       foreach(d1=iter(d, by='row'), .combine=rbind) %dopar% f(d1,"outputfile3"),
                     S4= {
                       print( paste(wellID=rep(1,n), d[,3], d[,4], sep=",") )
                       cat( paste(wellID=rep(1,n), d[,3], d[,4], sep=","), file= 'outputfile4', sep='\n',append=T, fill = F)                           
                     S5 = {
                       print( (paste(wellID=rep(1,n), d[,3], d[,4], sep=",")) )
                       write.table(data.frame(rep(1,n), d[,3], d[,4]), file='outputfile5', row.names=F, col.names=F, sep=",", append=T )

The resulting image shows that apply gives the best performance for a non-vectorised version, whereas write.table() seems to outperform cat(). ForEachRunningTime

How to Call a Function inside a Render in React/Jsx

To call the function you have to add ()


Convert IEnumerable to DataTable

To all:

Note that the accepted answer has a bug in it relating to nullable types and the DataTable. The fix is available at the linked site ( or in my modified code below:

    /// <summary>
    /// Convert a List to a DataTable.
    /// </summary>
    /// <remarks>
    /// Based on MIT-licensed code presented at as "ToDataTable"
    /// <para/>Code modifications made by Nick Campbell.
    /// <para/>Source code provided on this web site ( is under the MIT license.
    /// <para/>Copyright © 2010 Chinh Do
    /// <para/>Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
    /// <para/>The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
    /// <para/>(As per
    /// </remarks>
    /// <typeparam name="T">Type representing the type to convert.</typeparam>
    /// <param name="l_oItems">List of requested type representing the values to convert.</param>
    /// <returns></returns>
    /// <LastUpdated>February 15, 2010</LastUpdated>
    public static DataTable ToDataTable<T>(List<T> l_oItems) {
        DataTable oReturn = new DataTable(typeof(T).Name);
        object[] a_oValues;
        int i;

            //#### Collect the a_oProperties for the passed T
        PropertyInfo[] a_oProperties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

            //#### Traverse each oProperty, .Add'ing each .Name/.BaseType into our oReturn value
            //####     NOTE: The call to .BaseType is required as DataTables/DataSets do not support nullable types, so it's non-nullable counterpart Type is required in the .Column definition
        foreach(PropertyInfo oProperty in a_oProperties) {
            oReturn.Columns.Add(oProperty.Name, BaseType(oProperty.PropertyType));

            //#### Traverse the l_oItems
        foreach (T oItem in l_oItems) {
                //#### Collect the a_oValues for this loop
            a_oValues = new object[a_oProperties.Length];

                //#### Traverse the a_oProperties, populating each a_oValues as we go
            for (i = 0; i < a_oProperties.Length; i++) {
                a_oValues[i] = a_oProperties[i].GetValue(oItem, null);

                //#### .Add the .Row that represents the current a_oValues into our oReturn value

            //#### Return the above determined oReturn value to the caller
        return oReturn;

    /// <summary>
    /// Returns the underlying/base type of nullable types.
    /// </summary>
    /// <remarks>
    /// Based on MIT-licensed code presented at as "GetCoreType"
    /// <para/>Code modifications made by Nick Campbell.
    /// <para/>Source code provided on this web site ( is under the MIT license.
    /// <para/>Copyright © 2010 Chinh Do
    /// <para/>Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
    /// <para/>The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
    /// <para/>(As per
    /// </remarks>
    /// <param name="oType">Type representing the type to query.</param>
    /// <returns>Type representing the underlying/base type.</returns>
    /// <LastUpdated>February 15, 2010</LastUpdated>
    public static Type BaseType(Type oType) {
            //#### If the passed oType is valid, .IsValueType and is logicially nullable, .Get(its)UnderlyingType
        if (oType != null && oType.IsValueType &&
            oType.IsGenericType && oType.GetGenericTypeDefinition() == typeof(Nullable<>)
        ) {
            return Nullable.GetUnderlyingType(oType);
            //#### Else the passed oType was null or was not logicially nullable, so simply return the passed oType
        else {
            return oType;

Note that both of these example are NOT extension methods like the example above.

Lastly... apologies for my extensive/excessive comments (I had a anal/mean prof that beat it into me! ;)

how to return a char array from a function in C

Lazy notes in comments.

#include <stdio.h>
// for malloc
#include <stdlib.h>

// you need the prototype
char *substring(int i,int j,char *ch);

int main(void /* std compliance */)
  int i=0,j=2;
  char s[]="String";
  char *test;
  // s points to the first char, S
  // *s "is" the first char, S
  test=substring(i,j,s); // so s only is ok
  // if test == NULL, failed, give up
  free(test); // you should free it
  return 0;

char *substring(int i,int j,char *ch)
  int k=0;
  // avoid calc same things several time
  int n = j-i+1; 
  char *ch1;
  // you can omit casting - and sizeof(char) := 1
  // if (!ch1) error...; return NULL;

  // any kind of check missing:
  // are i, j ok? 
  // is n > 0... ch[i] is "inside" the string?...

  return ch1;

Excel function to make SQL-like queries on worksheet data?

If you want run formula on worksheet by function that execute SQL statement then use Add-in A-Tools

Example, function BS_SQL("SELECT ..."):

enter image description here

How to make a variable accessible outside a function?

Your variable declarations and their scope are correct. The problem you are facing is that the first AJAX request may take a little bit time to finish. Therefore, the second URL will be filled with the value of sID before the its content has been set. You have to remember that AJAX request are normally asynchronous, i.e. the code execution goes on while the data is being fetched in the background.

You have to nest the requests:

$.getJSON(""+input+"?api_key=API_KEY_HERE"  , function(name){   obj = name;   // sID is only now available!   sID =;   console.log(sID); }); 

Clean up your code!

  • Put the second request into a function
  • and let it accept sID as a parameter, so you don't have to declare it globally anymore! (Global variables are almost always evil!)
  • Remove sID and obj variables - is sufficient unless you really need the other variables outside the function.

$.getJSON(""+input+"?api_key=API_KEY_HERE"  , function(name){   // We don't need sID or obj here - is sufficient   console.log(;    doSecondRequest(; });  /// TODO Choose a better name function doSecondRequest(sID) {   $.getJSON("" + sID + "/summary?api_key=API_KEY_HERE", function(stats){         console.log(stats);   }); } 

Hapy New Year :)

Why I am Getting Error 'Channel is unrecoverably broken and will be disposed!'

In my case, I was using Glide library and the image passed to it was null. So it was throwing this error. I put a check like this:

if (imageData != null) {
    // add value in View here 

And it worked fine. Hope this helps someone.

Adjust UILabel height depending on the text

Problem is that none of mentioned functions is realiable and for some string and font will return incorrect height value. Especially will fail for attributed texts.

The only realiable solution is here: and the point is to use CoreText to manually calculate height of every line to get right size. There is no other known way to do this.

What's a simple way to get a text input popup dialog box on an iPhone

Add views to a UIAlertView like this. In iOS 5 there are some "magic" things that do it for you (but that's all under NDA).

How to prevent "The play() request was interrupted by a call to pause()" error?

I have the same issue, finally i solve by:

video.src = 'xxxxx';
setTimeout(function() {;
}, 0);

Can gcc output C code after preprocessing?

I'm using gcc as a preprocessor (for html files.) It does just what you want. It expands "#--" directives, then outputs a readable file. (NONE of the other C/HTML preprocessors I've tried do this- they concatenate lines, choke on special characters, etc.) Asuming you have gcc installed, the command line is:

gcc -E -x c -P -C -traditional-cpp code_before.cpp > code_after.cpp

(Doesn't have to be 'cpp'.) There's an excellent description of this usage at

The "-traditional-cpp" preserves whitespace & tabs.

How do I fix the indentation of selected lines in Visual Studio

Selecting the text to fix, and CtrlK, CtrlF shortcut certainly works. However, I generally find that if a particular method (for instance) has it's indentation messed up, simply removing the closing brace of the method, and re-adding, in fact fixes the indentation anyway, thereby doing without the need to select the code before hand, ergo is quicker. ymmv.

How to Decode Json object in laravel and apply foreach loop on that in laravel

you can use json_decode function

foreach (json_decode($response) as $area)
 print_r($area); // this is your area from json response

See this fiddle

What is the difference between compileSdkVersion and targetSdkVersion?

The compileSdkVersion should be newest stable version. The targetSdkVersion should be fully tested and less or equal to compileSdkVersion.

Generating UNIQUE Random Numbers within a range

This is how I would do it.

$randnum1 = mt_rand(1,20);

$nomatch = 0;

while($nomatch == 0){

$randnum2 = mt_rand(1,20);

if($randnum2 != $randnum1){

$nomatch = 1;



$nomatch = 0;

while($nomatch == 0){

$randnum3 = mt_rand(1,20);

if(($randnum3 != $randnum1)and($randnum3 != $randnum2)){

$nomatch = 1;



Then you can echo the results to check

echo "Random numbers are " . $randnum1 . "," . $randnum2 . ", and " . $randnum3 . "\n";

PowerShell: Format-Table without headers

The -HideTableHeaders parameter unfortunately still causes the empty lines to be printed (and table headers appearently are still considered for column width). The only way I know that could reliably work here would be to format the output yourself:

| % { '{0,10} {1,20} {2,20}' -f $_.Operation,$_.AttributeName,$_.AttributeValue }

Adding elements to object

This is an old question, anyway today the best practice is by using Object.defineProperty

const object1 = {};

Object.defineProperty(object1, 'property1', {
  value: 42,
  writable: false

object1.property1 = 77;
// throws an error in strict mode

// expected output: 42

Name [jdbc/mydb] is not bound in this Context

You need a ResourceLink in your META-INF/context.xml file to make the global resource available to the web application.

 <ResourceLink name="jdbc/mydb"
              type="javax.sql.DataSource" />

Get current batchfile directory

System read-only variable %CD% keeps the path of the caller of the batch, not the batch file location.

You can get the name of the batch script itself as typed by the user with %0 (e.g. scripts\mybatch.bat). Parameter extensions can be applied to this so %~dp0 will return the Drive and Path to the batch script (e.g. W:\scripts\) and %~f0 will return the full pathname (e.g. W:\scripts\mybatch.cmd).

You can refer to other files in the same folder as the batch script by using this syntax:

CALL %0\..\SecondBatch.cmd

This can even be used in a subroutine, Echo %0 will give the call label but, echo "%~nx0" will give you the filename of the batch script.

When the %0 variable is expanded, the result is enclosed in quotation marks.

More on batch parameters.

Creating a new column based on if-elif-else condition

df.loc[df['A'] == df['B'], 'C'] = 0
df.loc[df['A'] > df['B'], 'C'] = 1
df.loc[df['A'] < df['B'], 'C'] = -1

Easy to solve using indexing. The first line of code reads like so, if column A is equal to column B then create and set column C equal to 0.

How do I exit a foreach loop in C#?

Use break.

Unrelated to your question, I see in your code the line:

Violated = !(name.firstname == null) ? false : true;

In this line, you take a boolean value (name.firstname == null). Then, you apply the ! operator to it. Then, if the value is true, you set Violated to false; otherwise to true. So basically, Violated is set to the same value as the original expression (name.firstname == null). Why not use that, as in:

Violated = (name.firstname == null);

Making a flex item float right

You can't use float inside flex container and the reason is that float property does not apply to flex-level boxes as you can see here Fiddle.

So if you want to position child element to right of parent element you can use margin-left: auto but now child element will also push other div to the right as you can see here Fiddle.

What you can do now is change order of elements and set order: 2 on child element so it doesn't affect second div

.parent {_x000D_
  display: flex;_x000D_
.child {_x000D_
  margin-left: auto;_x000D_
  order: 2;_x000D_
<div class="parent">_x000D_
  <div class="child">Ignore parent?</div>_x000D_
  <div>another child</div>_x000D_

How to give a time delay of less than one second in excel vba?

You can use an API call and Sleep:

Put this at the top of your module:

Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)

Then you can call it in a procedure like this:

Sub test()
Dim i As Long

For i = 1 To 10
    Debug.Print Now()
    Sleep 500    'wait 0.5 seconds
Next i
End Sub

How to use PHP OPCache?

OPcache replaces APC

Because OPcache is designed to replace the APC module, it is not possible to run them in parallel in PHP. This is fine for caching PHP opcode as neither affects how you write code.

However it means that if you are currently using APC to store other data (through the apc_store() function) you will not be able to do that if you decide to use OPCache.

You will need to use another library such as either APCu or Yac which both store data in shared PHP memory, or switch to use something like memcached, which stores data in memory in a separate process to PHP.

Also, OPcache has no equivalent of the upload progress meter present in APC. Instead you should use the Session Upload Progress.

Settings for OPcache

The documentation for OPcache can be found here with all of the configuration options listed here. The recommended settings are:

; Sets how much memory to use

;Sets how much memory should be used by OPcache for storing internal strings 
;(e.g. classnames and the files they are contained in)

; The maximum number of files OPcache will cache

;How often (in seconds) to check file timestamps for changes to the shared
;memory storage allocation.

;If enabled, a fast shutdown sequence is used for the accelerated code
;The fast shutdown sequence doesn't free each allocated block, but lets
;the Zend Engine Memory Manager do the work.

;Enables the OPcache for the CLI version of PHP.

If you use any library or code that uses code annotations you must enable save comments:


If disabled, all PHPDoc comments are dropped from the code to reduce the size of the optimized code. Disabling "Doc Comments" may break some existing applications and frameworks (e.g. Doctrine, ZF2, PHPUnit)

jquery to validate phone number

Your regex should be something like


It matches numbers, dashes, parentheses and space.

If you need something more strict, matching just your example, try this:


How to read AppSettings values from a .json file in ASP.NET Core

Get it inside controller as an object via call Get<YourType>():

public IActionResult Index([FromServices] IConfiguration config)
    BillModel model = config.GetSection("Yst.Requisites").Get<BillModel>();
    return View(model);

How to push changes to github after jenkins build completes?

Actually, the "Checkout to specific local branch" from Claus's answer isn't needed as well.

You can just do changes, execute git commit -am "message" and then use "Git Publisher" with "Branch to push" = /refs/heads/master (or develop or whatever branch you need to push to), "Target remote name" = origin.

Best Way to Refresh Adapter/ListView on Android

Best Way to Refresh Adapter/ListView on Android

Not only calling notifyDataSetChanged() will refresh the ListView data, setAdapter() must be called before to load the information correctly:


Connection Java-MySql : Public Key Retrieval is not allowed

This also can be happened due to wrong user name or password. As solutions I've added allowPublicKeyRetrieval=true&useSSL=false part but still I got error then I checked the password and it was wrong.

PHP, display image with Header()

There is a better why to determine type of an image. with exif_imagetype

If you use this function, you can tell image's real extension.

with this function filename's extension is completely irrelevant, which is good.

function setHeaderContentType(string $filePath): void
    $numberToContentTypeMap = [
        '1' => 'image/gif',
        '2' => 'image/jpeg',
        '3' => 'image/png',
        '6' => 'image/bmp',
        '17' => 'image/ico'

    $contentType = $numberToContentTypeMap[exif_imagetype($filePath)] ?? null;
    if ($contentType === null) {
        throw new Exception('Unable to determine content type of file.');

    header("Content-type: $contentType");

You can add more types from the link.

Hope it helps.

How do I set a ViewModel on a window in XAML using DataContext property?

You need to instantiate the MainViewModel and set it as datacontext. In your statement it just consider it as string value.

     <Window x:Class="BuildAssistantUI.BuildAssistantWindow"

Bash syntax error: unexpected end of file

Another thing to check (just occured to me):

  • terminate bodies of single-line functions with semicolon

I.e. this innocent-looking snippet will cause the same error:

die () { test -n "$@" && echo "$@"; exit 1 }

To make the dumb parser happy:

die () { test -n "$@" && echo "$@"; exit 1; }

How do I convert date/time from 24-hour format to 12-hour AM/PM?

Use smaller h

// 24 hrs 
// output 14:20

// 12 hrs 
// output 2:20

How to list files in an android directory?

Updated working method

My minSdkversion is 21, so I'm using ContextCompat.checkSelfPermission() method to grant permissions apart from also adding the <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> in manifest. Thus, to get rid of the NullPointerException in spite of having files in your targeted directory, grant permissions as follows:-

public class MainActivity extends AppCompatActivity {
    /*Other variables & constants here*/  
    private final int READ_EXTERNAL_STORAGE=100;

    protected void onCreate(Bundle savedInstanceState) {

        // ignore the button code

        Button btn = (Button) findViewById(;
        btn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

         /*---------------------------- GRANT PERMISSIONS START-------------------------*/
        // Main part to grant permission. Handle other cases of permission denied
       //   yourself.
        if(ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
            ActivityCompat.requestPermissions(this,new String[] {Manifest.permission.READ_EXTERNAL_STORAGE},READ_EXTERNAL_STORAGE);

         /*---------------------------- GRANT PERMISSIONS OVER-------------------------*/

And the function that list all the files (in, thanks to @Yury:-
public void getDownloadedFile() {
        String path = Environment.getExternalStorageDirectory().toString()+"/Download/";
        Log.d("Files", "Path: " + path);
        File directory = new File(path);
        File[] files = directory.listFiles();
        if(directory.canRead() && files!=null) {
            Log.d("Files", "Size: " + files.length);
            for(File file: files)
            Log.d("Null?", "it is null");

How to handle an IF STATEMENT in a Mustache template?

I have a simple and generic hack to perform key/value if statement instead of boolean-only in mustache (and in an extremely readable fashion!) :

function buildOptions (object) {
    var validTypes = ['string', 'number', 'boolean'];
    var value;
    var key;
    for (key in object) {
        value = object[key];
        if (object.hasOwnProperty(key) && validTypes.indexOf(typeof value) !== -1) {
            object[key + '=' + value] = true;
    return object;

With this hack, an object like this:

var contact = {
  "id": 1364,
  "author_name": "Mr Nobody",
  "notified_type": "friendship",
  "action": "create"

Will look like this before transformation:

var contact = {
  "id": 1364,
  "id=1364": true,
  "author_name": "Mr Nobody",
  "author_name=Mr Nobody": true,
  "notified_type": "friendship",
  "notified_type=friendship": true,
  "action": "create",
  "action=create": true

And your mustache template will look like this:



How do I detect a click outside an element?

If you are scripting for IE and FF 3.* and you just want to know if the click occured within a certain box area, you could also use something like:

this.outsideElementClick = function(objEvent, objElement){   
var objCurrentElement = || objEvent.srcElement;
var blnInsideX = false;
var blnInsideY = false;

if (objCurrentElement.getBoundingClientRect().left >= objElement.getBoundingClientRect().left && objCurrentElement.getBoundingClientRect().right <= objElement.getBoundingClientRect().right)
    blnInsideX = true;

if (objCurrentElement.getBoundingClientRect().top >= objElement.getBoundingClientRect().top && objCurrentElement.getBoundingClientRect().bottom <= objElement.getBoundingClientRect().bottom)
    blnInsideY = true;

if (blnInsideX && blnInsideY)
    return false;
    return true;}

Change background image opacity

What I did is:

<div id="bg-image"></div>
<div class="container">
    <h1>Hello World!</h1>


html {
    height: 100%;
    width: 100%;
body {
    height: 100%;
    width: 100%;
#bg-image {
    height: 100%;
    width: 100%;
    position: absolute;
    background-image: url(images/background.jpg);
    background-position: center center;
    background-repeat: no-repeat;
    background-size: cover;
    opacity: 0.3;

What exactly is an instance in Java?

Objects, which are also called instances, are self-contained elements of a program with related features and data. For the most part, you use the class merely to create instances and then work with those instances.

-Definition taken from the book "Sams Teach Yourself Java in 21 days".

Say you have 2 Classes, public class MainClass and public class Class_2 and you want to make an instance of Class_2 in MainClass.

This is a very simple and basic way to do it:

public MainClass()      /*******this is the constructor of MainClass*******/


 Class_2 nameyouwant = new Class_2();


I hope this helps!

Website screenshots

Yes it is. If you only need image of URL try this

<img src=''>

Pass the url as argument and you'll get the image for more details check this link

UIWebView open links in Safari

The accepted answer does not work.

If your page loads URLs via Javascript, the navigationType will be UIWebViewNavigationTypeOther. Which, unfortunately, also includes background page loads such as analytics.

To detect page navigation, you need to compare the [request URL] to the [request mainDocumentURL].

This solution will work in all cases:

- (BOOL)webView:(UIWebView *)view shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)type
    if ([[request URL] isEqual:[request mainDocumentURL]])
        [[UIApplication sharedApplication] openURL:[request URL]];
        return NO;
        return YES;

How to redirect to another page using PHP

Although not secure, (no offense or anything), just stick the header function after you set the session variable

 while($row = mysql_fetch_assoc($result))
            $_SESSION["user"] = $username;
header('Location: /profile.php');

HTML/CSS - Adding an Icon to a button

Here's what you can do using font-awesome library.

button.btn.add::before {_x000D_
  font-family: fontAwesome;_x000D_
  content: "\f067\00a0";_x000D_
button.btn.edit::before {_x000D_
  font-family: fontAwesome;_x000D_
  content: "\f044\00a0";_x000D_
_x000D_ {_x000D_
  font-family: fontAwesome;_x000D_
  content: "\f00c\00a0";_x000D_
button.btn.cancel::before {_x000D_
  font-family: fontAwesome;_x000D_
  content: "\f00d\00a0";_x000D_
<script src=""></script>_x000D_
<script src=""></script>_x000D_
<link href="" rel="stylesheet"/>_x000D_
<link href="" rel="stylesheet"/>_x000D_
<!--FA unicodes here:>_x000D_
<h4>Buttons with text</h4>_x000D_
<button class="btn cancel btn-default">Close</button>_x000D_
<button class="btn add btn-primary">Add</button>_x000D_
<button class="btn add btn-success">Insert</button>_x000D_
<button class="btn save btn-primary">Save</button>_x000D_
<button class="btn save btn-warning">Submit Changes</button>_x000D_
<button class="btn cancel btn-link">Delete</button>_x000D_
<button class="btn edit btn-info">Edit</button>_x000D_
<button class="btn edit btn-danger">Modify</button>_x000D_
<h4>Buttons without text</h4>_x000D_
<button class="btn edit btn-primary" />_x000D_
<button class="btn cancel btn-danger" />_x000D_
<button class="btn add btn-info" />_x000D_
<button class="btn save btn-success" />_x000D_
<button class="btn edit btn-link"/>_x000D_
<button class="btn cancel btn-link"/>

Fiddle here.

Is it possible to have SSL certificate for IP address, not domain name?

The short answer is yes, as long as it is a public IP address.

Issuance of certificates to reserved IP addresses is not allowed, and all certificates previously issued to reserved IP addresses were revoked as of 1 October 2016.

According to the CA Browser forum, there may be compatibility issues with certificates for IP addresses unless the IP address is in both the commonName and subjectAltName fields. This is due to legacy SSL implementations which are not aligned with RFC 5280, notably, Windows OS prior to Windows 10.


  1. Guidance on IP Addresses In Certificates CA Browser Forum
  2. Baseline Requirements 1.4.1 CA Browser Forum
  3. The (soon to be) not-so Common Name
  4. RFC 5280 IETF

Note: an earlier version of this answer stated that all IP address certificates would be revoked on 1 October 2016. Thanks to Navin for pointing out the error.

How do I test which class an object is in Objective-C?

To test if object is an instance of class a:

[yourObject isKindOfClass:[a class]]
// Returns a Boolean value that indicates whether the receiver is an instance of 
// given class or an instance of any class that inherits from that class.


[yourObject isMemberOfClass:[a class]]
// Returns a Boolean value that indicates whether the receiver is an instance of a 
// given class.

To get object's class name you can use NSStringFromClass function:

NSString *className = NSStringFromClass([yourObject class]);

or c-function from objective-c runtime api:

#import <objc/runtime.h>

/* ... */

const char* className = class_getName([yourObject class]);
NSLog(@"yourObject is a: %s", className);

EDIT: In Swift

if touch.view is UIPickerView {
    // touch.view is of type UIPickerView

Implement Validation for WPF TextBoxes

When it comes to DiSaSteR's answer, I noticed a different behavior. textBox.Text shows the text in the TextBox as it was before the user entered a new character, while e.Text shows the single character the user just entered. One challenge is that this character might not get appended to the end, but it will be inserted at the carret position:

private void salary_texbox_PreviewTextInput(object sender, TextCompositionEventArgs e){
  Regex regex = new Regex ( "[^0-9]+" );

  string text;
  if (textBox.CaretIndex==textBox.Text.Length) {
    text = textBox.Text + e.Text;
  } else {
    text = textBox.Text.Substring(0, textBox.CaretIndex)  + e.Text + textBox.Text.Substring(textBox.CaretIndex);


How to connect to LocalDB in Visual Studio Server Explorer?

In Visual Studio 2012 all I had to do was enter:


Visual Studio 2015 and Visual Studio 2017 changed to:


as the server name when adding a Microsoft SQL Server Data source in:

View/Server Explorer/(Right click) Data Connections/Add Connection

and then the database names were populated. I didn't need to do all the other steps in the accepted answer, although it would be nice if the server name was available automatically in the server name combo box.

You can also browse the LocalDB database names available on your machine using:

View/SQL Server Object Explorer.

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

You can concatenate the strings...

h1.innerHTML += "...I would like to insert a carriage return here...<br />";
h1.innerHTML += "Ant the other line here... <br />";
h1.innerHTML += "And so on...<br />";


Add "Appendix" before "A" in thesis TOC

You can easily achieve what you want using the appendix package. Here's a sample file that shows you how. The key is the titletoc option when calling the package. It takes whatever value you've defined in \appendixname and the default value is Appendix.


\chapter{Lorem ipsum}
\section{Dolor sit amet}
  \chapter{Consectetur adipiscing elit}
  \chapter{Mauris euismod}

The output looks like

enter image description here

How do I set session timeout of greater than 30 minutes

Setting the timeout in the web.xml is the correct way to set the timeout.

Best practice for using assert?

For what it's worth, if you're dealing with code which relies on assert to function properly, then adding the following code will ensure that asserts are enabled:

    assert False
    raise Exception('Python assertions are not working. This tool relies on Python assertions to do its job. Possible causes are running with the "-O" flag or running a precompiled (".pyo" or ".pyc") module.')
except AssertionError:

CSS transition when class removed

In my case i had some problem with opacity transition so this one fix it:

#dropdown {
    transition:.6s opacity;
#dropdown.ns {
    transition:.6s all;
#dropdown.fade {

Mouse Enter


Mouse Leave


Running vbscript from batch file

This is the command for the batch file and it can run the vbscript.

C:\Windows\SysWOW64\cmd.exe /c cscript C:\Windows\SysWOW64\...\necdaily.vbs

What is the difference between x86 and x64

x86 is a 32 bit instruction set, x86_64 is a 64 bit instruction set... the difference is simple architecture. in case of windows os you better use the x86/32bit version for compatibility issues. in case of Linux you will not be able to use a 64 bit s/w if the os does not have the long mode flag.

Whatever I recommend if you have a windows 7 32 bit OS then go for 32bit or x86 binaries and as for Ubuntu 12.04 use command uname -a or grep lm /proc/cpuinfo (grep lm /proc/cpuinfo does not return value for 32 bit as 32 bit os does not has the cpuinfo flag) to know the architecture OS your OS then use the binaries according to your OS.

** Note. Remember you can always install 64 bit os in 32 bit system as long as it supports enhanced 64 bit.. 64 bit os works better some times for multi purpose work and also supports more ram than 32bits. also you can install 32bit s/w in 64 bit os..

** OS = Operating system.

How can I output UTF-8 from Perl?

Thanks, finally got an solution to not put utf8::encode all over code. To synthesize and complete for other cases, like write and read files in utf8 and also works with LoadFile of an YAML file in utf8

use utf8;
use open ':encoding(utf8)';
binmode(STDOUT, ":utf8");

open(FH, ">test.txt"); 
print FH "something éá";

use YAML qw(LoadFile Dump);
my $PUBS = LoadFile("cache.yaml");
my $f = "2917";
my $ref = $PUBS->{$f};
print "$f \"".$ref->{name}."\" ". $ref->{primary_uri}." ";

where cache.yaml is:

  id: 2917
  name: Semanário
  primary_uri: 2917.xml

Creating a Custom Event

Yes, provided you have access to the object definition and can modify it to declare the custom event

public event EventHandler<EventArgs> ModelChanged;

And normally you'd back this up with a private method used internally to invoke the event:

private void OnModelChanged(EventArgs e)
    if (ModelChanged != null)
        ModelChanged(this, e);

Your code simply declares a handler for the declared myMethod event (you can also remove the constructor), which would get invoked every time the object triggers the event.

myObject.myMethod += myNameEvent;

Similarly, you can detach a handler using

myObject.myMethod -= myNameEvent;

Also, you can write your own subclass of EventArgs to provide specific data when your event fires.

How do I pass an object to HttpClient.PostAsync and serialize as a JSON body?

The straight up answer to your question is: No. The signature for the PostAsync method is as follows:

public Task PostAsync(Uri requestUri, HttpContent content)

So, while you can pass an object to PostAsync it must be of type HttpContent and your anonymous type does not meet that criteria.

However, there are ways to accomplish what you want to accomplish. First, you will need to serialize your anonymous type to JSON, the most common tool for this is Json.NET. And the code for this is pretty trivial:

var myContent = JsonConvert.SerializeObject(data);

Next, you will need to construct a content object to send this data, I will use a ByteArrayContent object, but you could use or create a different type if you wanted.

var buffer = System.Text.Encoding.UTF8.GetBytes(myContent);
var byteContent = new ByteArrayContent(buffer);

Next, you want to set the content type to let the API know this is JSON.

byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

Then you can send your request very similar to your previous example with the form content:

var result = client.PostAsync("", byteContent).Result

On a side note, calling the .Result property like you're doing here can have some bad side effects such as dead locking, so you want to be careful with this.

Running a shell script through Cygwin on Windows

If you have access to the Notepad++ editor on Windows there is a feature that allows you to easily get around this problem:

  1. Open the file that's giving the error in Notepad++.
  2. Go under the "Edit" Menu and choose "EOL Conversion"
  3. There is an option there for "UNIX/OSX Format." Choose that option.
  4. Re-save the file.

I did this and it solved my problems.

Hope this helps!


How do I select a MySQL database through CLI?

Hope this helps.


When and why to 'return false' in JavaScript?

Why return false, or in fact, why return anything?

The code return(val); in a function returns the value of val to the caller of the function. Or, to quote MDN web docs, it...

...ends function execution and specifies a value to be returned to the function caller. (Source: MDN Web Docs: return.)

return false; then is useful in event handlers, because this will value is used by the event-handler to determine further action. return false; cancels events that normally take place with a handler, while return true; lets those events to occur. To quote MDN web docs again...

The return value from the handler determines if the event is canceled. (Source: MDN Web Docs: DOM OnEvent Handlers.)

If you are cancelling an event, return false; by itself is insufficient.

You should also use Event.preventDefault(); and Event.stopPropagation();.

The Event interface's preventDefault() method tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be. (Source: MDN Webdocs.)

  • Event.stopPropagation(); : To stop the event from clicking a link within the containing parent's DOM (i.e., if two links overlapped visually in the UI).

The stopPropagation() method of the Event interface prevents further propagation of the current event in the capturing and bubbling phases. (Source: MDN Webdocs.)

Working Demos

In this demo, we cancel an onclick function of a link and prevent the link from being clicked with return false;, preventDefault(), and stopPropagation().

Full Working JSBin Demo.

StackOverflow Demo...

document.getElementById('my-link').addEventListener('click', function(e) {
  console.log('Click happened for: ' +;
  return false;
<a href="" id="my-link" target="_blank">Link</a>

Checking if a collection is null or empty in Groovy

There is indeed a Groovier Way.

    //Some work

does everything if members is a collection. Null check as well as empty check (Empty collections are coerced to false). Hail Groovy Truth. :)

How to close a GUI when I push a JButton?

You may use Window#dispose() method to release all of the native screen resources, subcomponents, and all of its owned children.

The System.exit(0) will terminates the currently running Java Virtual Machine.

How to have the cp command create any necessary folders for copying a file to a destination

For those that are on Mac OSX, perhaps the easiest way to work around this is to use ditto (only on the mac, AFAIK, though). It will create the directory structure that is missing in the destination.

For instance, I did this

ditto 6.3.2/6.3.2/macosx/bin/mybinary ~/work/binaries/macosx/6.3.2/

where ~/work did not contain the binaries directory before I ran the command.

I thought rsync should work similarly, but it seems it only works for one level of missing directories. That is,

rsync 6.3.3/6.3.3/macosx/bin/mybinary ~/work/binaries/macosx/6.3.3/

worked, because ~/work/binaries/macosx existed but not ~/work/binaries/macosx/6.3.2/

React Native Change Default iOS Simulator Device

change line code of /node_modules/react-native/local-cli/runIOS/findMatchingSimulator.js

line 55

  if (
    simulator.availability !== '(available)' &&
    simulator.isAvailable !== true
  ) {

replace which:

   if (
                simulator.availability !== '(available)' &&
                simulator.isAvailable !== true
              ) {

Loop code for each file in a directory

Check out the DirectoryIterator class.

From one of the comments on that page:

// output all files and directories except for '.' and '..'
foreach (new DirectoryIterator('../moodle') as $fileInfo) {
    if($fileInfo->isDot()) continue;
    echo $fileInfo->getFilename() . "<br>\n";

The recursive version is RecursiveDirectoryIterator.

How to delete a workspace in Eclipse?

For Eclipse PDT in Mac OS, once you have deleted the actual workspace directory the option to select and switch to that workspace will still be available unless you delete the entry from Preferences >> General >> Startup and Shutdown >> Workspaces.

Finding duplicate rows in SQL Server

i think i know what you need i needed to mix between the answers and i think i got the solution he wanted:

select,o.orgName, oc.dupeCount,,oc.orgName
from organizations o
inner join (
    SELECT MAX(id) as id, orgName, COUNT(*) AS dupeCount
    FROM organizations
    GROUP BY orgName
    HAVING COUNT(*) > 1
) oc on o.orgName = oc.orgName

having the max id will give you the id of the dublicate and the one of the original which is what he asked for:

id org name , dublicate count (missing out in this case) 
id doublicate org name , doub count (missing out again because does not help in this case)

only sad thing you get it put out in this form

id , name , dubid , name

hope it still helps

How to know/change current directory in Python shell?

you want

import os