Programs & Examples On #Inherited resources

Inherited Resources speeds up development by making your controllers inherit all restful actions so you just have to focus on what is important.

Returning JSON object from an ASP.NET page

With ASP.NET Web Pages you can do this on a single page as a basic GET example (the simplest possible thing that can work.

var json = Json.Encode(new {
    orientation = Cache["orientation"],
    alerted = Cache["alerted"] as bool?,
    since = Cache["since"] as DateTime?

shell script. how to extract string using regular expressions

One way would be with sed. For example:

echo $name | sed -e 's?http://www\.??'

Normally the sed regular expressions are delimited by `/', but you can use '?' since you're searching for '/'. Here's another bash trick. @DigitalTrauma's answer reminded me that I ought to suggest it. It's similar:

echo ${name#http://www.}

(DigitalTrauma also gets credit for reminding me that the "http://" needs to be handled.)


CONVERT(DATA_TYPE , Your_Column) is the syntax for CONVERT method in SQL. From this convert function we can convert the data of the Column which is on the right side of the comma (,) to the data type in the left side of the comma (,) Please see below example.


Select count(*) from result query

This counts the rows of the inner query:

select count(*) from (
    select count(SID) 
    from Test 
    where Date = '2012-12-10' 
    group by SID
) t

However, in this case the effect of that is the same as this:

select count(distinct SID) from Test where Date = '2012-12-10'

Room persistance library. Delete all

As of Room 1.1.0 you can use clearAllTables() which:

Deletes all rows from all the tables that are registered to this database as entities().

Printing Batch file results to a text file

Have you tried moving DEL %FILE%.txt% to after @echo %FILE% deleted. >> results.txt so that it looks like this?

@echo %FILE% deleted. >> results.txt
DEL %FILE%.txt

How to maintain a Unique List in Java?

HashSet<String> (or) any Set implementation may does the job for you. Set don't allow duplicates.

Here is javadoc for HashSet.

Python Database connection Close

Connections have a close method as specified in PEP-249 (Python Database API Specification v2.0):

import pyodbc
conn = pyodbc.connect('DRIVER=MySQL ODBC 5.1 driver;SERVER=localhost;DATABASE=spt;UID=who;PWD=testest') 

csr = conn.cursor()  
conn.close()     #<--- Close the connection

Since the pyodbc connection and cursor are both context managers, nowadays it would be more convenient (and preferable) to write this as:

import pyodbc
conn = pyodbc.connect('DRIVER=MySQL ODBC 5.1 driver;SERVER=localhost;DATABASE=spt;UID=who;PWD=testest') 
with conn:
    crs = conn.cursor()
    # conn.commit() will automatically be called when Python leaves the outer `with` statement
    # Neither crs.close() nor conn.close() will be called upon leaving the `with` statement!! 

See for an explanation for why conn.close() is not called.

Note that unlike the original code, this causes conn.commit() to be called. Use the outer with statement to control when you want commit to be called.

Also note that regardless of whether or not you use the with statements, per the docs,

Connections are automatically closed when they are deleted (typically when they go out of scope) so you should not normally need to call [conn.close()], but you can explicitly close the connection if you wish.

and similarly for cursors (my emphasis):

Cursors are closed automatically when they are deleted (typically when they go out of scope), so calling [csr.close()] is not usually necessary.

Example on ToggleButton

Try this Toggle Buttons



public class Test extends Activity {

private ToggleButton togglebutton;

public void onCreate(Bundle savedInstanceState) {
    togglebutton = (ToggleButton) findViewById(;

public void toggleclick(View v){
        Toast.makeText(TestActivity.this, "ON", Toast.LENGTH_SHORT).show();
        Toast.makeText(TestActivity.this, "OFF", Toast.LENGTH_SHORT).show();

Ways to implement data versioning in MongoDB

If you're looking for a ready-to-roll solution -

Mongoid has built in simple versioning

mongoid-history is a Ruby plugin that provides a significantly more complicated solution with auditing, undo and redo

Creating your own header file in C

#ifndef MY_HEADER_H
# define MY_HEADER_H

//put your function headers here


MY_HEADER_H serves as a double-inclusion guard.

For the function declaration, you only need to define the signature, that is, without parameter names, like this:

int foo(char*);

If you really want to, you can also include the parameter's identifier, but it's not necessary because the identifier would only be used in a function's body (implementation), which in case of a header (parameter signature), it's missing.

This declares the function foo which accepts a char* and returns an int.

In your source file, you would have:

#include "my_header.h"

int foo(char* name) {
   //do stuff
   return 0;

How do I get the path of the assembly the code is in?

The only solution that worked for me when using CodeBase and UNC Network shares was:

System.IO.Path.GetDirectoryName(new System.Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).LocalPath);

It also works with normal URIs too.

Could not connect to SMTP host: localhost, port: 25; nested exception is: Connection refused: connect

The mail server on CentOS 6 and other IPv6 capable server platforms may be bound to IPv6 localhost (::1) instead of IPv4 localhost (

Typical symptoms:

[root@host /]# telnet 25
telnet: connect to address Connection refused

[root@host /]# telnet localhost 25
Trying ::1...
Connected to localhost.
Escape character is '^]'.
220 host ESMTP Exim 4.72 Wed, 14 Aug 2013 17:02:52 +0100

[root@host /]# netstat -plant | grep 25
tcp        0      0 :::25                       :::*                        LISTEN      1082/exim           

If this happens, make sure that you don't have two entries for localhost in /etc/hosts with different IP addresses, like this (bad) example:

[root@host /]# cat /etc/hosts localhost.localdomain localhost localhost4.localdomain4 localhost4
::1       localhost localhost.localdomain localhost6 localhost6.localdomain6

To avoid confusion, make sure you only have one entry for localhost, preferably an IPv4 address, like this:

[root@host /]# cat /etc/hosts localhost  localhost.localdomain   localhost4.localdomain4 localhost4
::1       localhost6 localhost6.localdomain6

ERROR Source option 1.5 is no longer supported. Use 1.6 or later

I think this means that

  • You are using JDK9 or later
  • Your project uses maven-compiler-plugin with an old version which defaults to Java 5.

You have three options to solve this

  1. Downgrade to JDK7 or JDK8 (meh)
  2. Use maven-compiler-plugin version or later, because

    NOTE: Since 3.8.0 the default value has changed from 1.5 to 1.6 See

  3. Indicate to the maven-compiler-plugin to use source level 6 and target 6 (or later).

    Best practice recommended by

    Also note that at present the default source setting is 1.6 and the default target setting is 1.6, independently of the JDK you run Maven with. You are highly encouraged to change these defaults by setting source and target as described in Setting the -source and -target of the Java Compiler.


    or use


What is the difference between buffer and cache memory in Linux?

Explained by Red Hat:

Cache Pages:

A cache is the part of the memory which transparently stores data so that future requests for that data can be served faster. This memory is utilized by the kernel to cache disk data and improve i/o performance.

The Linux kernel is built in such a way that it will use as much RAM as it can to cache information from your local and remote filesystems and disks. As the time passes over various reads and writes are performed on the system, kernel tries to keep data stored in the memory for the various processes which are running on the system or the data that of relevant processes which would be used in the near future. The cache is not reclaimed at the time when process get stop/exit, however when the other processes requires more memory then the free available memory, kernel will run heuristics to reclaim the memory by storing the cache data and allocating that memory to new process.

When any kind of file/data is requested then the kernel will look for a copy of the part of the file the user is acting on, and, if no such copy exists, it will allocate one new page of cache memory and fill it with the appropriate contents read out from the disk.

The data that is stored within a cache might be values that have been computed earlier or duplicates of original values that are stored elsewhere in the disk. When some data is requested, the cache is first checked to see whether it contains that data. The data can be retrieved more quickly from the cache than from its source origin.

SysV shared memory segments are also accounted as a cache, though they do not represent any data on the disks. One can check the size of the shared memory segments using ipcs -m command and checking the bytes column.


Buffers are the disk block representation of the data that is stored under the page caches. Buffers contains the metadata of the files/data which resides under the page cache. Example: When there is a request of any data which is present in the page cache, first the kernel checks the data in the buffers which contain the metadata which points to the actual files/data contained in the page caches. Once from the metadata the actual block address of the file is known, it is picked up by the kernel for processing.

Oracle Add 1 hour in SQL

You can use INTERVAL type or just add calculated number value - "1" is equal "1 day".

first way:

select date_column + INTERVAL '0 01:00:00' DAY TO SECOND from dual;

second way:

select date_column + 1/24 from dual;

First way is more convenient when you need to add a complicated value - for example, "1 day 3 hours 25 minutes 49 seconds". See also:

Also you have to remember that oracle have two interval types - DAY TO SECOND and YEAR TO MONTH. As for me, one interval type would be better, but I hope people in oracle knows, what they do ;)

Styling Form with Label above Inputs

I'd prefer not to use an HTML5 only element such as <section>. Also grouping the input fields might painful if you try to generate the form with code. It's always better to produce similar markup for each one and only change the class names. Therefore I would recommend a solution that looks like this :


label, input {
    display: block;
ul.form {
    width  : 500px;
    padding: 0px;
    margin : 0px;
    list-style-type: none;
ul.form li  {
    width : 500px;
ul.form li input {
    width : 200px;
ul.form li textarea {
    width : 450px;
    height: 150px;
ul.form li.twoColumnPart {
    float : left;
    width : 250px;


<form name="message" method="post">
    <ul class="form">
        <li class="twoColumnPart">
            <label for="name">Name</label>
            <input id="name" type="text" value="" name="name">
        <li class="twoColumnPart">
            <label for="email">Email</label>
            <input id="email" type="text" value="" name="email">
            <label for="subject">Subject</label>
            <input id="subject" type="text" value="" name="subject">
            <label for="message">Message</label>
            <textarea id="message" type="text" name="message"></textarea>

How do I resize a Google Map with JavaScript after it has loaded?

If you're using Google Maps v2, call checkResize() on your map after resizing the container. link


Google Maps JavaScript API v2 was deprecated in 2011. It is not available anymore.

Use LINQ to get items in one List<>, that are not in another List<>

first, extract ids from the collection where condition

List<int> indexes_Yes = this.Contenido.Where(x => x.key == 'TEST').Select(x => x.Id).ToList();

second, use "compare" estament to select ids diffent to the selection

List<int> indexes_No = this.Contenido.Where(x => !indexes_Yes.Contains(x.Id)).Select(x => x.Id).ToList();

Obviously you can use x.key != "TEST", but is only a example

Make a phone call programmatically

Tried the Swift 3 option above, but it didnt work. I think you need the following if you are to run against iOS 10+ on Swift 3:

Swift 3 (iOS 10+):

let phoneNumber = mymobileNO.titleLabel.text phoneNumber)!, options: [:], completionHandler: nil)

node.js remove file

you can use del module to remove one or more files in the current directory. what's nice about it is that protects you against deleting the current working directory and above.

const del = require('del');
del(['<your pathere here>/*']).then( (paths: any) => {
   console.log('Deleted files and folders:\n', paths.join('\n'));

How to test if string exists in file with Bash?

A grep-less solution, works for me:

MY_LIST=$( cat /path/to/my_list.txt )

if [[ "${MY_LIST}" == *"${NEW_DIRECTORY_NAME}"* ]]; then
  echo "It's there!"
echo "its not there"

based on:

Ordering by the order of values in a SQL IN() clause

Give this a shot:

SELECT name, description, ...
    (SELECT id FROM table1 WHERE...)
    (SELECT display_order FROM table1 WHERE...),
    (SELECT name FROM table1 WHERE...)

The WHEREs will probably take a little tweaking to get the correlated subqueries working properly, but the basic principle should be sound.

Extract source code from .jar file

-Covert .jar file to .zip (In windows just change the extension) -Unzip the .zip folder -You will get complete .java files

A monad is just a monoid in the category of endofunctors, what's the problem?

I came to this post by way of better understanding the inference of the infamous quote from Mac Lane's Category Theory For the Working Mathematician.

In describing what something is, it's often equally useful to describe what it's not.

The fact that Mac Lane uses the description to describe a Monad, one might imply that it describes something unique to monads. Bear with me. To develop a broader understanding of the statement, I believe it needs to be made clear that he is not describing something that is unique to monads; the statement equally describes Applicative and Arrows among others. For the same reason we can have two monoids on Int (Sum and Product), we can have several monoids on X in the category of endofunctors. But there is even more to the similarities.

Both Monad and Applicative meet the criteria:

  • endo => any arrow, or morphism that starts and ends in the same place
  • functor => any arrow, or morphism between two Categories

    (e.g., in day to day Tree a -> List b, but in Category Tree -> List)

  • monoid => single object; i.e., a single type, but in this context, only in regards to the external layer; so, we can't have Tree -> List, only List -> List.

The statement uses "Category of..." This defines the scope of the statement. As an example, the Functor Category describes the scope of f * -> g *, i.e., Any functor -> Any functor, e.g., Tree * -> List * or Tree * -> Tree *.

What a Categorical statement does not specify describes where anything and everything is permitted.

In this case, inside the functors, * -> * aka a -> b is not specified which means Anything -> Anything including Anything else. As my imagination jumps to Int -> String, it also includes Integer -> Maybe Int, or even Maybe Double -> Either String Int where a :: Maybe Double; b :: Either String Int.

So the statement comes together as follows:

  • functor scope :: f a -> g b (i.e., any parameterized type to any parameterized type)
  • endo + functor :: f a -> f b (i.e., any one parameterized type to the same parameterized type) ... said differently,
  • a monoid in the category of endofunctor

So, where is the power of this construct? To appreciate the full dynamics, I needed to see that the typical drawings of a monoid (single object with what looks like an identity arrow, :: single object -> single object), fails to illustrate that I'm permitted to use an arrow parameterized with any number of monoid values, from the one type object permitted in Monoid. The endo, ~ identity arrow definition of equivalence ignores the functor's type value and both the type and value of the most inner, "payload" layer. Thus, equivalence returns true in any situation where the functorial types match (e.g., Nothing -> Just * -> Nothing is equivalent to Just * -> Just * -> Just * because they are both Maybe -> Maybe -> Maybe).

Sidebar: ~ outside is conceptual, but is the left most symbol in f a. It also describes what "Haskell" reads-in first (big picture); so Type is "outside" in relation to a Type Value. The relationship between layers (a chain of references) in programming is not easy to relate in Category. The Category of Set is used to describe Types (Int, Strings, Maybe Int etc.) which includes the Category of Functor (parameterized Types). The reference chain: Functor Type, Functor values (elements of that Functor's set, e.g., Nothing, Just), and in turn, everything else each functor value points to. In Category the relationship is described differently, e.g., return :: a -> m a is considered a natural transformation from one Functor to another Functor, different from anything mentioned thus far.

Back to the main thread, all in all, for any defined tensor product and a neutral value, the statement ends up describing an amazingly powerful computational construct born from its paradoxical structure:

  • on the outside it appears as a single object (e.g., :: List); static
  • but inside, permits a lot of dynamics
    • any number of values of the same type (e.g., Empty | ~NonEmpty) as fodder to functions of any arity. The tensor product will reduce any number of inputs to a single value... for the external layer (~fold that says nothing about the payload)
    • infinite range of both the type and values for the inner most layer

In Haskell, clarifying the applicability of the statement is important. The power and versatility of this construct, has absolutely nothing to do with a monad per se. In other words, the construct does not rely on what makes a monad unique.

When trying to figure out whether to build code with a shared context to support computations that depend on each other, versus computations that can be run in parallel, this infamous statement, with as much as it describes, is not a contrast between the choice of Applicative, Arrows and Monads, but rather is a description of how much they are the same. For the decision at hand, the statement is moot.

This is often misunderstood. The statement goes on to describe join :: m (m a) -> m a as the tensor product for the monoidal endofunctor. However, it does not articulate how, in the context of this statement, (<*>) could also have also been chosen. It truly is a an example of six/half dozen. The logic for combining values are exactly alike; same input generates the same output from each (unlike the Sum and Product monoids for Int because they generate different results when combining Ints).

So, to recap: A monoid in the category of endofunctors describes:

   ~t :: m * -> m * -> m *
   and a neutral value for m *

(<*>) and (>>=) both provide simultaneous access to the two m values in order to compute the the single return value. The logic used to compute the return value is exactly the same. If it were not for the different shapes of the functions they parameterize (f :: a -> b versus k :: a -> m b) and the position of the parameter with the same return type of the computation (i.e., a -> b -> b versus b -> a -> b for each respectively), I suspect we could have parameterized the monoidal logic, the tensor product, for reuse in both definitions. As an exercise to make the point, try and implement ~t, and you end up with (<*>) and (>>=) depending on how you decide to define it forall a b.

If my last point is at minimum conceptually true, it then explains the precise, and only computational difference between Applicative and Monad: the functions they parameterize. In other words, the difference is external to the implementation of these type classes.

In conclusion, in my own experience, Mac Lane's infamous quote provided a great "goto" meme, a guidepost for me to reference while navigating my way through Category to better understand the idioms used in Haskell. It succeeds at capturing the scope of a powerful computing capacity made wonderfully accessible in Haskell.

However, there is irony in how I first misunderstood the statement's applicability outside of the monad, and what I hope conveyed here. Everything that it describes turns out to be what is similar between Applicative and Monads (and Arrows among others). What it doesn't say is precisely the small but useful distinction between them.

- E

Get commit list between tags in git

If your team uses descriptive commit messages (eg. "Ticket #12345 - Update dependencies") on this project, then generating changelog since the latest tag can de done like this:

git log --no-merges --pretty=format:"%s" 'old-tag^' > /path/to/
  • --no-merges omits the merge commits from the list
  • old-tag^ refers to the previous commit earlier than the tagged one. Useful if you want to see the tagged commit at the bottom of the list by any reason. (Single quotes needed only for iTerm on mac OS).

How to turn a String into a JavaScript function call?

Seeing as I hate eval, and I am not alone:

var fn = window[settings.functionName];
if(typeof fn === 'function') {

Edit: In reply to @Mahan's comment: In this particular case, settings.functionName would be "clickedOnItem". This would, at runtime translate var fn = window[settings.functionName]; into var fn = window["clickedOnItem"], which would obtain a reference to function clickedOnItem (nodeId) {}. Once we have a reference to a function inside a variable, we can call this function by "calling the variable", i.e. fn(, which equals clickedOnItem(, which was what the OP wanted.

More full example:

/* Somewhere: */
window.settings = {
  /* [..] Other settings */
  functionName: 'clickedOnItem'
  /* , [..] More settings */

/* Later */
function clickedOnItem (nodeId) {
  /* Some cool event handling code here */

/* Even later */
var fn = window[settings.functionName]; 
/* note that settings.functionName could also be written
   as window.settings.functionName. In this case, we use the fact that window
   is the implied scope of global variables. */
if(typeof fn === 'function') {

Error: EACCES: permission denied, access '/usr/local/lib/node_modules'

Below command worked for me:

sudo npm install -g appium --unsafe-perm=true --allow-root

"Failed to install the following Android SDK packages as some licences have not been accepted" error

To add to the answers, you can also change to the sdkmanager directory and in a sub shell and accept the licenses there

    cd /home/user/android-sdk-linux/tools/bin
    yes | ./sdkmanager --licenses

ORA-01882: timezone region not found

You may also try to check the version of the Oracle jdbc driver and Oracle database. Just today I had this issue when using ojdbc6.jar (version to connect to an Oracle server. Replacing it with ojdbc6.jar version solved the issue.

I also managed to make ojdbc6.jar version connect without error, by adding oracle.jdbc.timezoneAsRegion=false in file oracle/jdbc/ (inside the jar). Found this solution here (broken link)

Then, one can add -Doracle.jdbc.timezoneAsRegion=false to the command line, or AddVMOption -Doracle.jdbc.timezoneAsRegion=false in config files that use this notation.

You can also do this programmatically, e.g. with System.setProperty.

In some cases you can add the environment variable on a per-connection basis if that's allowed (SQL Developer allows this in the "Advanced" connection properties; I verified it to work when connecting to a database that doesn't have the problem and using a database link to a database which has).

How do I exit the Vim editor?

If you want to quit without saving in Vim and have Vim return a non-zero exit code, you can use :cq.

I use this all the time because I can't be bothered to pinky shift for !. I often pipe things to Vim which don't need to be saved in a file. We also have an odd SVN wrapper at work which must be exited with a non-zero value in order to abort a checkin.

Best way to copy a database (SQL Server 2008)

Easiest way is actually a script.

Run this on production:


TO DISK = 'C:\temp\MyDatabase1.bak' -- some writeable folder. 

This one command makes a complete backup copy of the database onto a single file, without interfering with production availability or backup schedule, etc.

To restore, just run this on your dev or test SQL Server:


FROM DISK = 'C:\temp\MyDatabase1.bak'
MOVE 'MyDatabase'   TO 'C:\Sql\MyDatabase.mdf', -- or wherever these live on target
MOVE 'MyDatabase_log'   TO 'C:\Sql\MyDatabase_log.ldf',

Then save these scripts on each server. One-click convenience.

if you get an error when restoring that the logical names don't match, you can get them like this:

FROM disk = 'C:\temp\MyDatabaseName1.bak'

If you use SQL Server logins (not windows authentication) you can run this after restoring each time (on the dev/test machine):

use MyDatabaseName;
sp_change_users_login 'Auto_Fix', 'userloginname', null, 'userpassword';

Set drawable size programmatically

Use the post method to achieve the desired effect:

{your view}.post(new Runnable()
        public void run()
            Drawable image = context.getResources().getDrawable({drawable image resource id});
            image.setBounds(0, 0, {width amount in pixels}, {height amount in pixels});
            {your view}.setCompoundDrawables(image, null, null, null);

Using DataContractSerializer to serialize, but can't deserialize back

This best for XML Deserialize

 public static object Deserialize(string xml, Type toType)

        using (MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
            System.IO.StreamReader str = new System.IO.StreamReader(memoryStream);
            System.Xml.Serialization.XmlSerializer xSerializer = new System.Xml.Serialization.XmlSerializer(toType);
            return xSerializer.Deserialize(str);


FileSystemWatcher Changed event is raised twice

I've "fixed" that problem using the following strategy in my delegate:

// fsw_ is the FileSystemWatcher instance used by my application.

private void OnDirectoryChanged(...)
      fsw_.EnableRaisingEvents = false;

      /* do my stuff once asynchronously */

      fsw_.EnableRaisingEvents = true;

PHP memcached Fatal error: Class 'Memcache' not found

For OSX users:

Run the following command to install Memcached:

brew install memcached

Python os.path.join on Windows

Windows has a concept of current directory for each drive. Because of that, "c:sourcedir" means "sourcedir" inside the current C: directory, and you'll need to specify an absolute directory.

Any of these should work and give the same result, but I don't have a Windows VM fired up at the moment to double check:

os.path.join("/", "c:", "sourcedir")
os.path.join("c:/", "sourcedir")

jquery - return value using ajax result on success

Although all the approaches regarding the use of async: false are not good because of its deprecation and stuck the page untill the request comes back. Thus here are 2 ways to do it:

1st: Return whole ajax response in a function and then make use of done function to capture the response when the request is completed.(RECOMMENDED, THE BEST WAY)

function getAjax(url, data){
    return $.ajax({
        type: 'POST',
        url : url,              
        data: data,
        dataType: 'JSON',
        //async: true,  //NOT NEEDED
        success: function(response) {
            //Data = response;


getAjax(youUrl, yourData).done(function(response){


$.when( getAjax(youUrl, yourData), getAjax2(yourUrl2, yourData2) ).done(function(response){

2nd: Store the response in a cookie and then outside of the ajax call get that cookie value.(NOT RECOMMENDED)

            type: 'POST',
            url : url,              
            data: data,
            //async: false,    // No need to use this
            success: function(response) {
                Cookies.set(name, response);

        // Outside of the ajax call
        var response = Cookies.get(name);

NOTE: In the exmple above jquery cookies library is used.It is quite lightweight and works as snappy. Here is the link

What are some good Python ORM solutions?

Storm has arguably the simplest API:

from storm.locals import *

class Foo:
    __storm_table__ = 'foos'
    id = Int(primary=True)

class Thing:
    __storm_table__ = 'things'
    id = Int(primary=True)
    name = Unicode()
    description = Unicode()
    foo_id = Int()
    foo = Reference(foo_id,

db = create_database('sqlite:')
store = Store(db)

foo = Foo()
thing = Thing() = foo

And it makes it painless to drop down into raw SQL when you need to:

store.execute('UPDATE bars SET bar_name=? WHERE bar_id like ?', []) 

Check whether an input string contains a number in javascript

One way to check it is to loop through the string and return true (or false depending on what you want) when you hit a number.

function checkStringForNumbers(input){
    let str = String(input);
    for( let i = 0; i < str.length; i++){
        if(!isNaN(str.charAt(i))){           //if the string is a number, do the following
            return true;

How to break lines in PowerShell?

Just in case someone else comes across this, to clarify the answer `n is grave accent n, not single tick n

What is the most effective way for float and double comparison?

As others have pointed out, using a fixed-exponent epsilon (such as 0.0000001) will be useless for values away from the epsilon value. For example, if your two values are 10000.000977 and 10000, then there are NO 32-bit floating-point values between these two numbers -- 10000 and 10000.000977 are as close as you can possibly get without being bit-for-bit identical. Here, an epsilon of less than 0.0009 is meaningless; you might as well use the straight equality operator.

Likewise, as the two values approach epsilon in size, the relative error grows to 100%.

Thus, trying to mix a fixed point number such as 0.00001 with floating-point values (where the exponent is arbitrary) is a pointless exercise. This will only ever work if you can be assured that the operand values lie within a narrow domain (that is, close to some specific exponent), and if you properly select an epsilon value for that specific test. If you pull a number out of the air ("Hey! 0.00001 is small, so that must be good!"), you're doomed to numerical errors. I've spent plenty of time debugging bad numerical code where some poor schmuck tosses in random epsilon values to make yet another test case work.

If you do numerical programming of any kind and believe you need to reach for fixed-point epsilons, READ BRUCE'S ARTICLE ON COMPARING FLOATING-POINT NUMBERS.

Comparing Floating Point Numbers

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

Python is very sensitive to indentation, with the code below I got the same error:

    except IntegrityError as e:
        if 'unique constraint' in e.args:
            return render(request, "calender.html")

The correct indentation is:

    except IntegrityError as e:
        if 'unique constraint' in e.args:
        return render(request, "calender.html")

How do you completely remove the button border in wpf?

You may already know that putting your Button inside of a ToolBar gives you this behavior, but if you want something that will work across ALL current themes with any sort of predictability, you'll need to create a new ControlTemplate.

Prashant's solution does not work with a Button not in a toolbar when the Button has focus. It also doesn't work 100% with the default theme in XP -- you can still see faint gray borders when your container Background is white.

PHP Parse HTML code

Use PHP Document Object Model:

   $str = '<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG';
   $DOM = new DOMDocument;

   //get all H1
   $items = $DOM->getElementsByTagName('h1');

   //display all H1 text
   for ($i = 0; $i < $items->length; $i++)
        echo $items->item($i)->nodeValue . "<br/>";

This outputs as:


[EDIT]: After OP Clarification:

If you want the content like Lorem ipsum. etc, you can directly use this regex:

   $str = '<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG';
   echo preg_replace("#<h1.*?>.*?</h1>#", "", $str);

this outputs:

Lorem ipsum.The quick red fox...... jumps over the lazy brown FROG

How to implement class constants?

For this you can use the readonly modifier. Object properties which are readonly can only be assigned during initialization of the object.

Example in classes:

class Circle {
  readonly radius: number;

  constructor(radius: number) {
    this.radius = radius;

  get area() {
    return Math.PI * this.radius * 2;

const circle = new Circle(12);
circle.radius = 12; // Cannot assign to 'radius' because it is a read-only property.

Example in Object literals:

type Rectangle = {
  readonly height: number;
  readonly width: number;

const square: Rectangle = { height: 1, width: 2 };
square.height = 5 // Cannot assign to 'height' because it is a read-only property

It's also worth knowing that the readonly modifier is purely a typescript construct and when the TS is compiled to JS the construct will not be present in the compiled JS. When we are modifying properties which are readonly the TS compiler will warn us about it (it is valid JS).

How to resume Fragment from BackStack if exists

getFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {

    public void onBackStackChanged() {

        if(getFragmentManager().getBackStackEntryCount()==0) {

Read file As String

The code finally used is the following from:

public static String convertStreamToString(InputStream is) throws Exception {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
    return sb.toString();

public static String getStringFromFile (String filePath) throws Exception {
    File fl = new File(filePath);
    FileInputStream fin = new FileInputStream(fl);
    String ret = convertStreamToString(fin);
    //Make sure you close all streams.
    return ret;

Detecting iOS / Android Operating system

Solution 1: User Agent Sniffing

For Android and iPhone:

if( /Android|webOS|iPhone|iPad|iPod|Opera Mini/i.test(navigator.userAgent) ) {
 // run your code here

If you wanna detect all mobile devices including blackberry and Windows phone then you can use this comprehensive version:

var deviceIsMobile = false; //At the beginning we set this flag as false. If we can detect the device is a mobile device in the next line, then we set it as true.

if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|ipad|iris|kindle|Android|Silk|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(navigator.userAgent) 
    || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(navigator.userAgent.substr(0,4))) {
   deviceIsMobile = true;

    // run your code here

Cons: User agent strings are changing and getting updated as new phones and brands are coming day by day. So you need to keep this list updated if you wanna support all mobile devices.

Solution 2: mobile detect JS library

You can use the mobile detect JS library to do this.

Cons: These JavaScript-based device detection features may ONLY work for the newest generation of smartphones, such as the iPhone, Android and Palm WebOS devices. These device detection features may NOT work for older smartphones which had poor support for JavaScript, including older BlackBerry, PalmOS, and Windows Mobile devices.

Finding the median of an unsorted array

It can be done using Quickselect Algorithm in O(n), do refer to Kth order statistics (randomized algorithms).

How to delete projects in Intellij IDEA 14?

You will have to manually delete from the project explorer (your local machine hard drive), then delete the project in IntelliJ when it asks to re-open recent projects.

Difference between onCreate() and onStart()?

onCreate() method gets called when activity gets created, and its called only once in whole Activity life cycle. where as onStart() is called when activity is stopped... I mean it has gone to background and its onStop() method is called by the os. onStart() may be called multiple times in Activity life cycle.More details here

Why Doesn't C# Allow Static Methods to Implement an Interface?

Interfaces are abstract sets of defined available functionality.

Whether or not a method in that interface behaves as static or not is an implementation detail that should be hidden behind the interface. It would be wrong to define an interface method as static because you would be unnecessarily forcing the method to be implemented in a certain way.

If methods were defined as static, the class implementing the interface wouldn't be as encapsulated as it could be. Encapsulation is a good thing to strive for in object oriented design (I won't go into why, you can read that here: For this reason, static methods aren't permitted in interfaces.

How to keep form values after post

you can save them into a $_SESSION variable and then when the user calls that page again populate all the inputs with their respective session variables.

How to read a file into vector in C++?

Just to expand on juanchopanza's answer a bit...

for (int i=0; i=((Main.size())-1); i++) {
    cout << Main[i] << '\n';

does this:

  1. Create i and set it to 0.
  2. Set i to Main.size() - 1. Since Main is empty, Main.size() is 0, and i gets set to -1.
  3. Main[-1] is an out-of-bounds access. Kaboom.

Make a negative number positive


Math.abs(arr[i]);  //1st way (taking absolute value)

arr[i]=-(arr[i]); //2nd way (taking -ve of -ve no. yields a +ve no.)

arr[i]= ~(arr[i]-1);   //3rd way (taking negation)

Spring: @Component versus @Bean

1. About @Component
@Component functs similarily to @Configuration.

They both indicate that the annotated class has one or more beans need to be registered to Spring-IOC-Container.

The class annotated by @Component, we call it Component of Spring. It is a concept that contains several beans.

Component class needs to be auto-scanned by Spring for registering those beans of the component class.

2. About @Bean
@Bean is used to annotate the method of component-class(as mentioned above). It indicate the instance retured by the annotated method needs to be registered to Spring-IOC-Container.

3. Conclusion
The difference between them two is relatively obivious, they are used in different circumstances. The general usage is:

    // @Configuration is implemented by @Component
    public ComponentClass {

      public FirstBean FirstBeanMethod() {
        return new FirstBean();

      public SecondBean SecondBeanMethod() {
        return new SecondBean();

What exactly is OAuth (Open Authorization)?

OAuth happened when we sign up SO account with Facebook/ Google button.

  1. Application (SO) redirecting user to the provider's authorization URL. ( Displaying a web page asking the user if he or she wishes to grant the application access to read and update their data).
  2. User agree to grant the application process.
  3. Service provider redirects user back to application (SO), passing authorization code as parameter.
  4. SO exchanges the code for an access grant.

Source : OAuth1 service providers

Laravel view not found exception

If your path to view is true first try to config:cache and route:cache if nothing changed check your resource path permission are true.

example: your can do it in ubuntu with :

sudo chgrp -R www-data resources/views
sudo usermod -a -G www-data $USER

How the single threaded non blocking IO model works in Node.js

Node.js is built upon libuv, a cross-platform library that abstracts apis/syscalls for asynchronous (non-blocking) input/output provided by the supported OSes (Unix, OS X and Windows at least).

Asynchronous IO

In this programming model open/read/write operation on devices and resources (sockets, filesystem, etc.) managed by the file-system don't block the calling thread (as in the typical synchronous c-like model) and just mark the process (in kernel/OS level data structure) to be notified when new data or events are available. In case of a web-server-like app, the process is then responsible to figure out which request/context the notified event belongs to and proceed processing the request from there. Note that this will necessarily mean you'll be on a different stack frame from the one that originated the request to the OS as the latter had to yield to a process' dispatcher in order for a single threaded process to handle new events.

The problem with the model I described is that it's not familiar and hard to reason about for the programmer as it's non-sequential in nature. "You need to make request in function A and handle the result in a different function where your locals from A are usually not available."

Node's model (Continuation Passing Style and Event Loop)

Node tackles the problem leveraging javascript's language features to make this model a little more synchronous-looking by inducing the programmer to employ a certain programming style. Every function that requests IO has a signature like function (... parameters ..., callback) and needs to be given a callback that will be invoked when the requested operation is completed (keep in mind that most of the time is spent waiting for the OS to signal the completion - time that can be spent doing other work). Javascript's support for closures allows you to use variables you've defined in the outer (calling) function inside the body of the callback - this allows to keep state between different functions that will be invoked by the node runtime independently. See also Continuation Passing Style.

Moreover, after invoking a function spawning an IO operation the calling function will usually return control to node's event loop. This loop will invoke the next callback or function that was scheduled for execution (most likely because the corresponding event was notified by the OS) - this allows the concurrent processing of multiple requests.

You can think of node's event loop as somewhat similar to the kernel's dispatcher: the kernel would schedule for execution a blocked thread once its pending IO is completed while node will schedule a callback when the corresponding event has occured.

Highly concurrent, no parallelism

As a final remark, the phrase "everything runs in parallel except your code" does a decent job of capturing the point that node allows your code to handle requests from hundreds of thousands open socket with a single thread concurrently by multiplexing and sequencing all your js logic in a single stream of execution (even though saying "everything runs in parallel" is probably not correct here - see Concurrency vs Parallelism - What is the difference?). This works pretty well for webapp servers as most of the time is actually spent on waiting for network or disk (database / sockets) and the logic is not really CPU intensive - that is to say: this works well for IO-bound workloads.

no operator "<<" matches these operands

It looks like you're comparing strings incorrectly. To compare a string to another, use the std::string::compare function.


     while ((wrong < MAX_WRONG) && ( != 0)) 

Sending POST parameters with Postman doesn't work, but sending GET parameters does

Sorry if this is thread Necromancy, but this is still relevant today, especially with how much APIs are used!

An issue I had was: I didn't know that under the 'Key' column you need to put: 'Content-Type'; I thought this was a User Key for when it came back in the request, which it isn't.

So something as simple as that may help you, I think Postman could word that column better, because I didn't even have to read the Documentation when it came to using Fiddler; whereas I did with Postman.

Postman picture

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

I'll try and answer several different things, however my contribution may not cover all of your questions. Maybe several of us can take different chunks out of this. However, this info should be helpful for you. Here we go..

Opening A Seperate File:

ChDir "[Path here]"                          'get into the right folder here
Workbooks.Open Filename:= "[Path here]"      'include the filename in this path

'copy data into current workbook or whatever you want here

ActiveWindow.Close                          'closes out the file

Opening A File With Specified Date If It Exists:

I'm not sure how to search your directory to see if a file exists, but in my case I wouldn't bother to search for it, I'd just try to open it and put in some error checking so that if it doesn't exist then display this message or do xyz.

Some common error checking statements:

On Error Resume Next   'if error occurs continues on to the next line (ignores it)

ChDir "[Path here]"                         
Workbooks.Open Filename:= "[Path here]"      'try to open file here

Or (better option):

if one doesn't exist then bring up either a message box or dialogue box to say "the file does not exist, would you like to create a new one?

you would most likely want to use the GoTo ErrorHandler shown below to achieve this

On Error GoTo ErrorHandler:

ChDir "[Path here]"                         
Workbooks.Open Filename:= "[Path here]"      'try to open file here

'Display error message or any code you want to run on error here

Much more info on Error handling here:

Also if you want to learn more or need to know more generally in VBA I would recommend Siddharth Rout's site, he has lots of tutorials and example code here:

Hope this helps!

Example on how to ensure error code doesn't run EVERYtime:

if you debug through the code without the Exit Sub BEFORE the error handler you'll soon realize the error handler will be run everytime regarldess of if there is an error or not. The link below the code example shows a previous answer to this question.

  Sub Macro

    On Error GoTo ErrorHandler:

    ChDir "[Path here]"                         
    Workbooks.Open Filename:= "[Path here]"      'try to open file here

    Exit Sub      'Code will exit BEFORE ErrorHandler if everything goes smoothly
                  'Otherwise, on error, ErrorHandler will be run

    'Display error message or any code you want to run on error here

  End Sub

Also, look at this other question in you need more reference to how this works: goto block not working VBA

How to convert float to varchar in SQL Server

cast(replace(convert(decimal(15,2),acs_daily_debit), '.', ',') as varchar(20))

from acs_balance_details

Checking if an Android application is running in the background

The only one correct solution:

public class MainActivity extends AppCompatActivity {

    protected void onCreate(Bundle savedInstanceState) {
        MyApp.mainActivity = this;

public class MyApp extends Application implements LifecycleObserver {

    public static MainActivity mainActivity = null;

    public void onCreate() {

    void onAppBackgrounded() {
        // app in background
        if (mainActivity != null) {

    void onAppForegrounded() {
        // app in foreground
        if (mainActivity != null) {


Hibernate problem - "Use of @OneToMany or @ManyToMany targeting an unmapped class"

I had the same problem and I could solve it by adding the entity into persistence.xml. The problem was caused due to the fact that the entity was not added to the persistence config. Edit your persistence file:

<persistence-unit name="MY_PU" transaction-type="RESOURCE_LOCAL">
<provider>`enter code here`


How to store the hostname in a variable in a .bat file?

Just create a .bat file with the line


in it. That's it. Windows also supports the hostname command.

How can I get an int from stdio in C?

I'm not fully sure that this is what you're looking for, but if your question is how to read an integer using <stdio.h>, then the proper syntax is

int myInt;
scanf("%d", &myInt);

You'll need to do a lot of error-handling to ensure that this works correctly, of course, but this should be a good start. In particular, you'll need to handle the cases where

  1. The stdin file is closed or broken, so you get nothing at all.
  2. The user enters something invalid.

To check for this, you can capture the return code from scanf like this:

int result = scanf("%d", &myInt);

If stdin encounters an error while reading, result will be EOF, and you can check for errors like this:

int myInt;
int result = scanf("%d", &myInt);

if (result == EOF) {
    /* ... you're not going to get any input ... */

If, on the other hand, the user enters something invalid, like a garbage text string, then you need to read characters out of stdin until you consume all the offending input. You can do this as follows, using the fact that scanf returns 0 if nothing was read:

int myInt;
int result = scanf("%d", &myInt);

if (result == EOF) {
    /* ... you're not going to get any input ... */
if (result == 0) {
    while (fgetc(stdin) != '\n') // Read until a newline is found

Hope this helps!

EDIT: In response to the more detailed question, here's a more appropriate answer. :-)

The problem with this code is that when you write

printf("got the number: %d", scanf("%d", &x));

This is printing the return code from scanf, which is EOF on a stream error, 0 if nothing was read, and 1 otherwise. This means that, in particular, if you enter an integer, this will always print 1 because you're printing the status code from scanf, not the number you read.

To fix this, change this to

int x;
scanf("%d", &x);
/* ... error checking as above ... */
printf("got the number: %d", x);

Hope this helps!

How to get an element's top position relative to the browser's viewport?

On my case, just to be safe regarding scrolling, I added the window.scroll to the equation:

var element = document.getElementById('myElement');
var topPos = element.getBoundingClientRect().top + window.scrollY;
var leftPos = element.getBoundingClientRect().left + window.scrollX;

That allows me to get the real relative position of element on document, even if it has been scrolled.

How to check if MySQL returns null/empty?

Use empty() and/or is_null()

Empty alone will achieve your current usage, is_null would just make more control possible if you wanted to distinguish between a field that is null and a field that is empty.

How to find out line-endings in a text file?

In the bash shell, try cat -v <filename>. This should display carriage-returns for windows files.

(This worked for me in rxvt via Cygwin on Windows XP).

Editor's note: cat -v visualizes \r (CR) chars. as ^M. Thus, line-ending \r\n sequences will display as ^M at the end of each output line. cat -e will additionally visualize \n, namely as $. (cat -et will additionally visualize tab chars. as ^I.)

How could I put a border on my grid control in WPF?

<Grid x:Name="outerGrid">
    <Grid x:Name="innerGrid">
        <Border BorderBrush="#FF179AC8" BorderThickness="2" />
        <other stuff></other stuff>
        <other stuff></other stuff>

This code Wrap a border inside the "innerGrid"

How do you receive a url parameter with a spring controller mapping

You should be using @RequestParam instead of @ModelAttribute, e.g.

public @ResponseBody int getAttr(@PathVariable(value="someID") String id, 
                                 @RequestParam String someAttr) {

You can even omit @RequestParam altogether if you choose, and Spring will assume that's what it is:

public @ResponseBody int getAttr(@PathVariable(value="someID") String id, 
                                 String someAttr) {

nodeJS - How to create and read session with express

It is cumbersome to interoperate and connect sessions support. The problem is not because "hijacks" request somehow, but because certain transports (I think flashsockets) don't support cookies. I could be wrong with cookies, but my approach is the following:

  1. Implement a separate session store for that stores data in the same format as connect-redis
  2. Make connect session cookie not http-only so it's accessible from client JS
  3. Upon a connection, send session cookie over from browser to server
  4. Store the session id in a connection, and use it to access session data from redis.

what is Ljava.lang.String;@

The method works if you provide an array. The output of

String[] helloWorld = {"Hello", "World"};


[Hello, World]

(the number after @ is almost always different)

Please tell us the return type of Employee.getSelectCancel()

What's the best way to send a signal to all members of a process group?

Modified version of zhigang's answer:

#!/usr/bin/env bash
set -eu

killtree() {
    local pid
    for pid; do
        kill -stop $pid
        local cpid
        for cpid in $(pgrep -P $pid); do
            killtree $cpid
        kill $pid
        kill -cont $pid
        wait $pid 2>/dev/null || true

cpids() {
    local pid=$1 options=${2:-} space=${3:-}
    local cpid
    for cpid in $(pgrep -P $pid); do
        echo "$space$cpid"
        if [[ "${options/a/}" != "$options" ]]; then
            cpids $cpid "$options" "$space  "

while true; do sleep 1; done &
for i in $(seq 1 2); do
    cpids $$ a
    sleep 1
killtree $cpid
echo ---
cpids $$ a

Git Symlinks in Windows

You can find the symlinks by looking for files that have a mode of 120000, possibly with this command:

git ls-files -s | awk '/120000/{print $4}'

Once you replace the links, I would recommend marking them as unchanged with git update-index --assume-unchanged, rather than listing them in .git/info/exclude.

What are the differences between type() and isinstance()?

For the real differences, we can find it in code, but I can't find the implement of the default behavior of the isinstance().

However we can get the similar one abc.__instancecheck__ according to __instancecheck__.

From above abc.__instancecheck__, after using test below:

# file tree
# /test/
# /test/aaa/
# /test/aaa/
class b():

# /test/aaa/
import sys

from aaa.aa import b
from aa import b as c

d = b()

print(b, c, d.__class__)
for i in [b, c, object]:
    print(i, '__subclasses__',  i.__subclasses__())
    print(i, '__mro__', i.__mro__)
    print(i, '__subclasshook__', i.__subclasshook__(d.__class__))
    print(i, '__subclasshook__', i.__subclasshook__(type(d)))
print(isinstance(d, b))
print(isinstance(d, c))

<class 'aaa.aa.b'> <class 'aa.b'> <class 'aaa.aa.b'>
<class 'aaa.aa.b'> __subclasses__ []
<class 'aaa.aa.b'> __mro__ (<class 'aaa.aa.b'>, <class 'object'>)
<class 'aaa.aa.b'> __subclasshook__ NotImplemented
<class 'aaa.aa.b'> __subclasshook__ NotImplemented
<class 'aa.b'> __subclasses__ []
<class 'aa.b'> __mro__ (<class 'aa.b'>, <class 'object'>)
<class 'aa.b'> __subclasshook__ NotImplemented
<class 'aa.b'> __subclasshook__ NotImplemented
<class 'object'> __subclasses__ [..., <class 'aaa.aa.b'>, <class 'aa.b'>]
<class 'object'> __mro__ (<class 'object'>,)
<class 'object'> __subclasshook__ NotImplemented
<class 'object'> __subclasshook__ NotImplemented

I get this conclusion, For type:

# according to `abc.__instancecheck__`, they are maybe different! I have not found negative one 
type(INSTANCE) ~= INSTANCE.__class__
type(CLASS) ~= CLASS.__class__

For isinstance:

# guess from `abc.__instancecheck__`
return any(c in cls.__mro__ or c in cls.__subclasses__ or cls.__subclasshook__(c) for c in {INSTANCE.__class__, type(INSTANCE)})

BTW: better not to mix use relative and absolutely import, use absolutely import from project_dir( added by sys.path)

What order are the Junit @Before/@After called?

This isn't an answer to the tagline question, but it is an answer to the problems mentioned in the body of the question. Instead of using @Before or @After, look into using @org.junit.Rule because it gives you more flexibility. ExternalResource (as of 4.7) is the rule you will be most interested in if you are managing connections. Also, If you want guaranteed execution order of your rules use a RuleChain (as of 4.10). I believe all of these were available when this question was asked. Code example below is copied from ExternalResource's javadocs.

 public static class UsesExternalResource {
  Server myServer= new Server();

  public ExternalResource resource= new ExternalResource() {
      protected void before() throws Throwable {

      protected void after() {

  public void testFoo() {
      new Client().run(myServer);

Linux bash script to extract IP address

Take your pick:

$ cat file
eth0      Link encap:Ethernet  HWaddr 08:00:27:a3:e3:b0
          inet addr:  Bcast:  Mask:
          inet6 addr: fe80::a00:27ff:fea3:e3b0/64 Scope:Link
          RX packets:1904 errors:0 dropped:0 overruns:0 frame:0
          TX packets:2002 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:1309425 (1.2 MiB)  T

$ awk 'sub(/inet addr:/,""){print $1}' file

$ awk -F'[ :]+' '/inet addr/{print $4}' file

XAMPP - MySQL shutdown unexpectedly

IMPORTANT Deleting this file may render any existing MySQL data unusable. Use with caution

Hey I just did this and it worked:

  1. exit Xampp server
  2. go to your C:\xampp\mysql\data directory
  3. delete the ibdata1 file
  4. restart xampp server

It should work

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

What about using checkout command :

  git diff --stat "$branch"
  git checkout --merge "$branch" "$file"
  git diff --stat "$branch"

Count number of lines in a git repository

: | git mktree | git diff --shortstat --stdin


git ls-tree @ | sed '1i\\' | git mktree --batch | xargs | git diff-tree --shortstat --stdin

Make Https call using HttpClient

For error:

The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.

I think that you need to accept certificate unconditionally with following code

ServicePointManager.ServerCertificateValidationCallback += 
    (sender, cert, chain, sslPolicyErrors) => true;

as Oppositional wrote in his answer to question .NET client connecting to ssl Web API.

Using Regular Expressions to Extract a Value in Java

This function collect all matching sequences from string. In this example it takes all email addresses from string.

static final String EMAIL_PATTERN = "[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
        + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})";

public List<String> getAllEmails(String message) {      
    List<String> result = null;
    Matcher matcher = Pattern.compile(EMAIL_PATTERN).matcher(message);

    if (matcher.find()) {
        result = new ArrayList<String>();

        while (matcher.find()) {

    return result;

For message = "[email protected], <[email protected]>>>> [email protected]" it will create List of 3 elements.

Comments in Markdown

I use standard HTML tags, like

your comment goes here
and here

Note the triple dash. The advantage is that it works with pandoc when generating TeX or HTML output. More information is available on the pandoc-discuss group.

How to make a node.js application run permanently?

First install pm2 globally

npm install -g pm2

then start

pm2 start bin/www 

Converting integer to binary in python

Just another idea:

>>> bin(6)[2:].zfill(8)

Shorter way via string interpolation (Python 3.6+):

>>> f'{6:08b}'

How to run a stored procedure in oracle sql developer?

Consider you've created a procedure like below.

) IS 

In Oracle SQL Developer, you can run this procedure in two ways.

1. Using SQL Worksheet

Create a SQL Worksheet and write PL/SQL anonymous block like this and hit f5

  FULL_NAME Varchar2(50);
  Dbms_Output.Put_Line('Full name is: ' || FULL_NAME);

2. Using GUI Controls

  • Expand Procedures

  • Right click on the procudure you've created and Click Run

  • In the pop-up window, Fill the parameters and Click OK.


Set Font Color, Font Face and Font Size in PHPExcel

I recommend you start reading the documentation (4.6.18. Formatting cells). When applying a lot of formatting it's better to use applyFromArray() According to the documentation this method is also suppose to be faster when you're setting many style properties. There's an annex where you can find all the possible keys for this function.

This will work for you:

$phpExcel = new PHPExcel();

$styleArray = array(
    'font'  => array(
        'bold'  => true,
        'color' => array('rgb' => 'FF0000'),
        'size'  => 15,
        'name'  => 'Verdana'

$phpExcel->getActiveSheet()->getCell('A1')->setValue('Some text');

To apply font style to complete excel document:

 $styleArray = array(
   'font'  => array(
        'bold'  => true,
        'color' => array('rgb' => 'FF0000'),
        'size'  => 15,
        'name'  => 'Verdana'

Instant run in Android Studio 2.0 (how to turn off)

the design in android 2.3 (stable version) is slightly changed.

File ? Settings ? Build, Execution, Deployment ? Instant Run and uncheck Enable Instant Run.

enter image description here

Initialize a string variable in Python: "" or None?

Python philosophy is to be readable.
That's why it's good practice to define your attributes in __init__() even if it's optional.
In the same spirit, you have to ask yourself what clearer for anyone who reads your code. In fact the type itself give much information about future use of your variable. So:

kind = None

Is syntaxically correct, but reader does not know much. Is it a string, a code as integer, a list, etc. ?

kind_str = None
kind = ""

Both say a little more, the first has the type in its name and the second in its declaration. I would go for the second, neater.

How do I get current URL in Selenium Webdriver 2 Python?

Selenium2Library has get_location():

import Selenium2Library
s = Selenium2Library.Selenium2Library()
url = s.get_location()

How to write a full path in a batch file having a folder name with space?

Put double quotes around the path that has spaces like this:

REGSVR32 "E:\Documents and Settings\All Users\Application Data\xyz.dll"

Looping from 1 to infinity in Python

def to_infinity():
    index = 0
    while True:
        yield index
        index += 1

for i in to_infinity():
    if i > 10:

Check if registry key exists using VBScript

The second of the two methods here does what you're wanting. I've just used it (after finding no success in this thread) and it's worked for me.

The code:

Const HKCR = &H80000000 'HKEY_CLASSES_ROOT
Const HKCU = &H80000001 'HKEY_CURRENT_USER
Const HKUS = &H80000003 'HKEY_USERS

Function KeyExists(Key, KeyPath)
    Dim oReg: Set oReg = GetObject("winmgmts:!root/default:StdRegProv")
    If oReg.EnumKey(Key, KeyPath, arrSubKeys) = 0 Then
        KeyExists = True
        KeyExists = False
   End If
End Function

Are members of a C++ struct initialized to 0 by default?

Since this is a POD (essentially a C struct) there is little harm in initialising it the C way:

Snapshot s;
memset(&s, 0, sizeof (s));

or similarly

Snapshot *sp = new Snapshot;
memset(sp, 0, sizeof (*sp));

I wouldn't go so far as to use calloc() in a C++ program though.

What does 'synchronized' mean?

What the other answers are missing is one important aspect: memory barriers. Thread synchronization basically consists of two parts: serialization and visibility. I advise everyone to google for "jvm memory barrier", as it is a non-trivial and extremely important topic (if you modify shared data accessed by multiple threads). Having done that, I advise looking at java.util.concurrent package's classes that help to avoid using explicit synchronization, which in turn helps keeping programs simple and efficient, maybe even preventing deadlocks.

One such example is ConcurrentLinkedDeque. Together with the command pattern it allows to create highly efficient worker threads by stuffing the commands into the concurrent queue -- no explicit synchronization needed, no deadlocks possible, no explicit sleep() necessary, just poll the queue by calling take().

In short: "memory synchronization" happens implicitly when you start a thread, a thread ends, you read a volatile variable, you unlock a monitor (leave a synchronized block/function) etc. This "synchronization" affects (in a sense "flushes") all writes done before that particular action. In the case of the aforementioned ConcurrentLinkedDeque, the documentation "says":

Memory consistency effects: As with other concurrent collections, actions in a thread prior to placing an object into a ConcurrentLinkedDeque happen-before actions subsequent to the access or removal of that element from the ConcurrentLinkedDeque in another thread.

This implicit behavior is a somewhat pernicious aspect because most Java programmers without much experience will just take a lot as given because of it. And then suddenly stumble over this thread after Java isn't doing what it is "supposed" to do in production where there is a different work load -- and it's pretty hard to test concurrency issues.

Popup window in winform c#

If you mean to create a new form when a button is clicked, the below code may be of some use to you:

private void settingsButton_Click(Object sender, EventArgs e)
    // Create a new instance of the Form2 class
    Form2 settingsForm = new Form2();

    // Show the settings form

From here, you could also use the 'Show Dialog' method

How to use global variables in React Native?

The global scope in React Native is variable global. Such as = foo, then you can use anywhere.

But do not abuse it! In my opinion, global scope may used to store the global config or something like that. Share variables between different views, as your description, you can choose many other solutions(use redux,flux or store them in a higher component), global scope is not a good choice.

A good practice to define global variable is to use a js file. For example global.js = foo; = bar;

Then, to make sure it is executed when project initialized. For example, import the file in index.js:

import './global.js'
// other code

Now, you can use the global variable anywhere, and don't need to import global.js in each file. Try not to modify them!

How to remove title bar from the android activity?

you just add this style in your style.xml file which is in your values folder

<style name="AppTheme.NoActionBar" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
    <item name="android:windowFullscreen">true</item>

After that set this style to your activity class in your AndroidManifest.xml file


Edit:- If you are going with programmatic way to hide ActionBar then use below code in your activity onCreate() method.


and if you want to hide ActionBar from Fragment then


AppCompat v7:- Use following theme in your Activities where you don't want actiobBar Theme.AppComat.NoActionBar or Theme.AppCompat.Light.NoActionBar or if you want to hide in whole app then set this theme in your <application... /> in your AndroidManifest.

In Kotlin:

add this line of code in your onCreate() method or you can use above theme.

if (supportActionBar != null)

i hope this will help you more.

How could I create a function with a completion handler in Swift?

I had trouble understanding the answers so I'm assuming any other beginner like myself might have the same problem as me.

My solution does the same as the top answer but hopefully a little more clear and easy to understand for beginners or people just having trouble understanding in general.

To create a function with a completion handler

func yourFunctionName(finished: () -> Void) {

     print("Doing something!")



to use the function

     override func viewDidLoad() {

          yourFunctionName {

          //do something here after running your function


Your output will be

Doing something


Hope this helps!

MySQL Stored procedure variables from SELECT statements

I am facing a strange behavior.

SELECT INTO and SET Both works for some variables and not for others. Event syntaxes are the same

SET @Invoice_UserId :=  (SELECT UserId FROM invoice WHERE InvoiceId = @Invoice_Id  LIMIT 1); -- Working
                SET @myamount := (SELECT amount FROM invoice WHERE InvoiceId = @Invoice_Id LIMIT 1); - Not working
SELECT  Amount INTO @myamount FROM invoice WHERE InvoiceId = 29  LIMIT 1; - Not working

If I run these queries directly then works, but not working in stored procedure.

What is the difference between RTP or RTSP in a streaming server?

I hear your pain. I'm going through this right now (years later). From what I've learned, you can think of RTSP as a "VCR controller", the protocol allows you to specify which streams (presentations) you want to play, it will then send you a description of the media, and then you can use RTSP to play, stop, pause, and record the remote stream. The media itself goes over RTP. RTSP is normally implemented over a different socket or communication layer. Although it is simply a protocol, most often it's implemented by a server over a socket. For live streams, the RTSP stream you request is simply a name of a stream. It doesn't need to refer to a file on the server, the server's RTSP implementation can parse that stream, put together a live graph, and then provide the SDP (description) for that stream name. But, this is of course specific to the way the RTSP server has been implemented. For "live" streams, it's probably simpler to just use RTP, but you'll need a way to transfer the SDP from the RTP server to the client that wants to play that stream.

Altering a column: null to not null

this worked for me:

Alter COLUMN [Column] VARCHAR(50) not null;

Get the latest record with filter in Django

You can do comparison with this down here.


latest('created') is same as order_by('-created').first() Please correct me if I am wrong

How to convert SQL Server's timestamp column to datetime format

Using cast you can get date from a timestamp field:

SELECT CAST(timestamp_field AS DATE) FROM tbl_name

how to convert milliseconds to date format in android?

i finally find normal code that works for me

Long longDate = Long.valueOf(date);

Calendar cal = Calendar.getInstance();
int offset = cal.getTimeZone().getOffset(cal.getTimeInMillis());
Date da = new Date(); 
da = new Date(longDate-(long)offset);

String time =cal.getTime().toLocaleString(); 
//this is full string        

time = DateFormat.getTimeInstance(DateFormat.MEDIUM).format(da);
//this is only time

time = DateFormat.getDateInstance(DateFormat.MEDIUM).format(da);
//this is only date

Homebrew install specific version of formula?

Update on the Library/Formula/postgresql.rb line 8 to

And MD5 on line 9 to


Save and exit.

brew install postgres
initdb /usr/local/var/postgres

Now in this stage you might face the postgresql could not create shared memory segment error, to work around that update the /etc/sysctl.conf like this:


Try initdb /usr/local/var/postgres again, and it should run smooth.

To run postgresql on start

launchctl load -w /usr/local/Cellar/postgresql/8.4.6/org.postgresql.postgres.plist

Hope that helps :)

AttributeError: 'dict' object has no attribute 'predictors'

#Try without dot notation
sample_dict = {'name': 'John', 'age': 29}
print(sample_dict['name']) # John
print(sample_dict['age']) # 29

Any way to clear python's IDLE window?

It seems it is impossible to do it without any external library.

An alternative way if you are using windows and don't want to open and close the shell everytime you want to clear it is by using windows command prompt.

  • Type python and hit enter to turn windows command prompt to python idle (make sure python is installed).

  • Type quit() and hit enter to turn it back to windows command prompt.

  • Type cls and hit enter to clear the command prompt/ windows shell.

How do I bind the enter key to a function in tkinter?

Another alternative is to use a lambda:

ent.bind("<Return>", (lambda event: name_of_function()))

Full code:

from tkinter import *
from tkinter.messagebox import showinfo

def reply(name):
    showinfo(title="Reply", message = "Hello %s!" % name)

top = Tk()

Label(top, text="Enter your name:").pack(side=TOP)
ent = Entry(top)
ent.bind("<Return>", (lambda event: reply(ent.get())))
btn = Button(top,text="Submit", command=(lambda: reply(ent.get())))


As you can see, creating a lambda function with an unused variable "event" solves the problem.

error C4996: 'scanf': This function or variable may be unsafe in c programming

You can add "_CRT_SECURE_NO_WARNINGS" in Preprocessor Definitions.

Right-click your project->Properties->Configuration Properties->C/C++ ->Preprocessor->Preprocessor Definitions.

enter image description here

ORDER BY date and time BEFORE GROUP BY name in mysql

Another method:

    SELECT * FROM table_name
    ORDER BY date ASC, time ASC 
) AS sub

GROUP BY groups on the first matching result it hits. If that first matching hit happens to be the one you want then everything should work as expected.

I prefer this method as the subquery makes logical sense rather than peppering it with other conditions.

PersistentObjectException: detached entity passed to persist thrown by JPA and Hibernate

If above solutions not work just one time comment the getter and setter methods of entity class and do not set the value of id.(Primary key) Then this will work.

Retrofit 2: Get JSON from Response body

If you don't have idea about What could be the response from the API. Follow the steps to convert the responsebody response value into bytes and print in the String format You can get the entire response printed in the console.

Then you can convert string to JSONObject easily.

      apiService.getFeeds(headerMap, map).enqueue(object : Callback, retrofit2.Callback<ResponseBody> {
            override fun onFailure(call: Call<ResponseBody>?, t: Throwable?) {

            override fun onResponse(call: Call<ResponseBody>?, response: Response<ResponseBody>?) {
                val bytes = (response!!.body()!!.bytes())
                Log.d("Retrofit Success : ", ""+ String(bytes))

oracle SQL how to remove time from date

When you convert your string to a date you need to match the date mask to the format in the string. This includes a time element, which you need to remove with truncation:

    p1.PA_VALUE as StartDate,
    p2.PA_VALUE as EndDate
from WP_Work p 
LEFT JOIN PARAMETER p1 on p1.WP_ID=p.WP_ID AND p1.NAME = 'StartDate'
WHERE p.TYPE = 'EventManagement2'
AND trunc(TO_DATE(p1.PA_VALUE, 'DD-MM-YYYY HH24:MI')) >= TO_DATE('25/10/2012', 'DD/MM/YYYY')
AND trunc(TO_DATE(p2.PA_VALUE, 'DD-MM-YYYY HH24:MI')) <= TO_DATE('26/10/2012', 'DD/MM/YYYY')

How to create a custom exception type in Java?

You can create you own exception by inheriting from java.lang.Exception Here is an example that can help you do that.

How to set the focus for a particular field in a Bootstrap modal, once it appears

A little cleaner and more modular solution might be:

    $('.modal').success(function() { 

Or using your ID as an example instead:

    $('#modal-content').modal('show').success(function() {

Hope that helps..

Printing the correct number of decimal points with cout

int main()


 double d=15.6464545347;



how to remove css property using javascript?

You have two options:


You can use removeProperty method. It will remove a style from an element.'zoom');


You can set it to the default value: = "";

The effective zoom will now be whatever follows from the definitions set in the stylesheets (through link and style tags). So this syntax will only modify the local style of this element.

How to determine if a number is positive or negative?

You say

we should not use conditional operators

But this is a trick requirement, because == is also a conditional operator. There is also one built into ? :, while, and for loops. So nearly everyone has failed to provide an answer meeting all the requirements.

The only way to build a solution without a conditional operator is to use lookup table vs one of a few other people's solutions that can be boiled down to 0/1 or a character, before a conditional is met.

Here are the answers that I think might work vs a lookup table:

  • Nabb
  • Steven Schlansker
  • Dennis Cheung
  • Gary Rowe

How to filter empty or NULL names in a QuerySet?

You could do this:


If you need to exclude null values and empty strings, the preferred way to do so is to chain together the conditions like so:


Chaining these methods together basically checks each condition independently: in the above example, we exclude rows where alias is either null or an empty string, so you get all Name objects that have a not-null, not-empty alias field. The generated SQL would look something like:

SELECT * FROM Name WHERE alias IS NOT NULL AND alias != ""

You can also pass multiple arguments to a single call to exclude, which would ensure that only objects that meet every condition get excluded:

Name.objects.exclude(some_field=True, other_field=True)

Here, rows in which some_field and other_field are true get excluded, so we get all rows where both fields are not true. The generated SQL code would look a little like this:

SELECT * FROM Name WHERE NOT (some_field = TRUE AND other_field = TRUE)

Alternatively, if your logic is more complex than that, you could use Django's Q objects:

from django.db.models import Q
Name.objects.exclude(Q(alias__isnull=True) | Q(alias__exact=''))

For more info see this page and this page in the Django docs.

As an aside: My SQL examples are just an analogy--the actual generated SQL code will probably look different. You'll get a deeper understanding of how Django queries work by actually looking at the SQL they generate.

Java get month string from integer

This has already been mentioned, but here is a way to place the code within a method:

    public static String getMonthName(int monthIndex) {
         return new DateFormatSymbols().getMonths()[monthIndex].toString();

or if you wanted to create a better error than an ArrayIndexOutOfBoundsException:

    public static String getMonthName(int monthIndex) {
        //since this is zero based, 11 = December
        if (monthIndex < 0 || monthIndex > 11 ) {
            throw new IllegalArgumentException(monthIndex + " is not a valid month index.");
        return new DateFormatSymbols().getMonths()[monthIndex].toString();

Adding a 'share by email' link to website

<a target="_blank" title="Share this page" href="[INSERT URL]&title=[INSERT TITLE]&summary=[INSERT SUMMARY]&img=[INSERT IMAGE URL]&pageInfo=%7B%22hostname%22%3A%22[INSERT DOMAIN NAME]%22%2C%22publisher%22%3A%22[INSERT PUBLISHERID]%22%7D"><img width="86" height="25" alt="Share this page" src=""></a>


First, insert these lines wherever you want within your newsletter code. Then:

  1. Change "INSERT URL" to whatever website holds the shared content.
  2. Change "INSERT TITLE" to the title of the article.
  3. Change "INSERT SUMMARY" to a short summary of the article.
  4. Change "INSERT IMAGE URL" to an image that will be shared with the rest of the content.
  5. Change "INSERT DOMAIN NAME" to your domain name.
  6. Change "INSERT PUBLISHERID" to your publisher ID (if you have an account, if not, remove "[INSERT PUBLISHERID]" or sign up!)

If you are using this on an email newsletter, make sure you add our sharing buttons to the destination page. This will ensure that you get complete sharing analytics for your page. Make sure you replace "INSERT PUBLISHERID" with your own.

Multiple radio button groups in MVC 4 Razor

I fixed a similar issue building a RadioButtonFor with pairs of text/value from a SelectList. I used a ViewBag to send the SelectList to the View, but you can use data from model too. My web application is a Blog and I have to build a RadioButton with some types of articles when he is writing a new post.

The code below was simplyfied.

List<SelectListItem> items = new List<SelectListItem>();

Dictionary<string, string> dictionary = new Dictionary<string, string>();

dictionary.Add("Texto", "1");
dictionary.Add("Foto", "2");
dictionary.Add("Vídeo", "3");

foreach (KeyValuePair<string, string> pair in objBLL.GetTiposPost())
    items.Add(new SelectListItem() { Text = pair.Key, Value = pair.Value, Selected = false });

ViewBag.TiposPost = new SelectList(items, "Value", "Text");

In the View, I used a foreach to build a radiobutton.

<div class="form-group">
    <div class="col-sm-10">
        @foreach (var item in (SelectList)ViewBag.TiposPost)
            @Html.RadioButtonFor(model => model.IDTipoPost, item.Value, false)
            <label class="control-label">@item.Text</label>


Notice that I used RadioButtonFor in order to catch the option value selected by user, in the Controler, after submit the form. I also had to put the item.Text outside the RadioButtonFor in order to show the text options.

Hope it's useful!

import android packages cannot be resolved

RightClick on the Project > Properties > Android > Fix project properties

This solved it for me. easy.

SQL error "ORA-01722: invalid number"

The ORA-01722 error is pretty straightforward. According to Tom Kyte:

We've attempted to either explicity or implicity convert a character string to a number and it is failing.

However, where the problem is is often not apparent at first. This page helped me to troubleshoot, find, and fix my problem. Hint: look for places where you are explicitly or implicitly converting a string to a number. (I had NVL(number_field, 'string') in my code.)

How do I implement interfaces in python?

My understanding is that interfaces are not that necessary in dynamic languages like Python. In Java (or C++ with its abstract base class) interfaces are means for ensuring that e.g. you're passing the right parameter, able to perform set of tasks.

E.g. if you have observer and observable, observable is interested in subscribing objects that supports IObserver interface, which in turn has notify action. This is checked at compile time.

In Python, there is no such thing as compile time and method lookups are performed at runtime. Moreover, one can override lookup with __getattr__() or __getattribute__() magic methods. In other words, you can pass, as observer, any object that can return callable on accessing notify attribute.

This leads me to the conclusion, that interfaces in Python do exist - it's just their enforcement is postponed to the moment in which they are actually used

Using std::max_element on a vector<double>

min_element and max_element return iterators, not values. So you need *min_element... and *max_element....

R for loop skip to next iteration ifelse

for(n in 1:5) {
  if(n==3) next # skip 3rd iteration and go to next iteration

Python: Passing variables between functions

return returns a value. It doesn't matter what name you gave to that value. Returning it just "passes it out" so that something else can use it. If you want to use it, you have to grab it from outside:

lst = defineAList()

Returning list from inside defineAList doesn't mean "make it so the whole rest of the program can use that variable". It means "pass this variable out and give the rest of the program one chance to grab it and use it". You need to assign that value to something outside the function in order to make use of it. Also, because of this, there is no need to define your list ahead of time with list = []. Inside defineAList, you create a new list and return it; this list has no relationship to the one you defined with list = [] at the beginning.

Incidentally, I changed your variable name from list to lst. It's not a good idea to use list as a variable name because that is already the name of a built-in Python type. If you make your own variable called list, you won't be able to access the builtin one anymore.

Have border wrap around text

Try putting it in a span element:

<div id='page' style='width: 600px'>_x000D_
  <h1><span style='border:2px black solid; font-size:42px;'>Title</span></h1>_x000D_

How to multiply a BigDecimal by an integer in Java

You have a lot of type-mismatches in your code such as trying to put an int value where BigDecimal is required. The corrected version of your code:

public class Payment
    BigDecimal itemCost  = BigDecimal.ZERO;
    BigDecimal totalCost = BigDecimal.ZERO;

    public BigDecimal calculateCost(int itemQuantity, BigDecimal itemPrice)
        itemCost  = itemPrice.multiply(new BigDecimal(itemQuantity));
        totalCost = totalCost.add(itemCost);
        return totalCost;

How to increase buffer size in Oracle SQL Developer to view all records?

Tools-> Preferences -> Database ->Worksheet

Enter desired size in "Max rows to print in a script"

Save changes.

Oracle - How to create a readonly user

you can create user and grant privilege

create user read_only identified by read_only; grant create session,select any table to read_only;

What happens to C# Dictionary<int, int> lookup if the key does not exist?

You should probably use:

  // do something

The reason why you can't check for null is that the key here is a value type.

Access parent's parent from javascript object

If you want get all parents key of a node in a literal object ({}), you can to do that:

(function ($) {
    "use strict";

    $.defineProperties($, {
        parentKeys: {
            value: function (object) {
                    traces = [],
                    queue = [{trace: [], node: object}],

                    block = function () {

                        // clean the queue
                        queue = [];
                        return function (map) {
                            node = map.node;
                            nodeKeys = Object.keys(node);

                            nodeKeys.forEach(function (nodeKey) {
                                if (typeof node[nodeKey] == "object") {
                                    trace = map.trace.concat(nodeKey);
                                    // put on queue
                                    queue.push({trace: trace, node: node[nodeKey]});

                                    // traces.unshift(trace);

                while(true) {
                    if (queue.length) {
                    } else {

                return traces;

            writable: true



This algorithm uses the FIFO concept for iterate the graphs using the BFS method. This code extend the class Object adding the static method parentKeys that expects a literal Object (hash table - associative array...) of the Javacript, as parameter.

I hope I have helped.

SQL Delete Records within a specific Range

You gave a condition ID (>79 and < 296) then the answer is:

delete from tab
where id > 79 and id < 296

this is the same as:

delete from tab
where id between 80 and 295

if id is an integer.

All answered:

delete from tab
where id between 79 and 296

this is the same as:

delete from tab
where id => 79 and id <= 296

Mind the difference.

How to install Java 8 on Mac

In the year 2021 you have only use brew

brew install jenv openjdk@8
jenv add /usr/local/opt/openjdk@8

And then add into Intellij IDEA a new SDK with the following path:


I will also suggest to add in your .zshrc (or .bashrc)

export PATH="$HOME/.jenv/bin:$PATH"
eval "$(jenv init -)"
export JAVA_HOME="$HOME/.jenv/versions/`jenv version-name`"

Curl command without using cache

I know this is an older question, but I wanted to post an answer for users with the same question:

curl -H 'Cache-Control: no-cache'

This curl command servers in its header request to return non-cached data from the web server.

Generating UNIQUE Random Numbers within a range

This probably will solve your problem:

<?php print_r(array_rand(range(1,50), 5)); ?>

How to make blinking/flashing text with CSS 3

It works for me by using class=blink for the respective element(s)

Simple JS Code

// Blink


        //$(".blink").css("color","rgba(0,0,0,0.1)"); // If you want simply black/white blink of text
        $(".blink").css("visibility","hidden"); // This is for Visibility of the element  


        //$(".blink").css("color","rgba(0,0,0,1)");  // If you want simply black/white blink of text
        $(".blink").css("visibility","visible");  // This is for Visibility of the element


Count work days between two dates

In Calculating Work Days you can find a good article about this subject, but as you can see it is not that advanced.

--Changing current database to the Master database allows function to be shared by everyone.
--If the function already exists, drop it.
    SELECT *
    WHERE ID = OBJECT_ID(N'[dbo].[fn_WorkDays]')
    AND XType IN (N'FN', N'IF', N'TF')
DROP FUNCTION [dbo].[fn_WorkDays]
 CREATE FUNCTION dbo.fn_WorkDays
--Define the input parameters (OK if reversed by mistake).
    @StartDate DATETIME,
    @EndDate   DATETIME = NULL --@EndDate replaced by @StartDate when DEFAULTed

--Define the output data type.

--Calculate the RETURN of the function.
    --Declare local variables
    --Temporarily holds @EndDate during date reversal.

    --If the Start Date is null, return a NULL and exit.
    IF @StartDate IS NULL

    --If the End Date is null, populate with Start Date value so will have two dates (required by DATEDIFF below).
     IF @EndDate IS NULL
        SELECT @EndDate = @StartDate

    --Strip the time element from both dates (just to be safe) by converting to whole days and back to a date.
    --Usually faster than CONVERT.
    --0 is a date (01/01/1900 00:00:00.000)
     SELECT @StartDate = DATEADD(dd,DATEDIFF(dd,0,@StartDate), 0),
            @EndDate   = DATEADD(dd,DATEDIFF(dd,0,@EndDate)  , 0)

    --If the inputs are in the wrong order, reverse them.
     IF @StartDate > @EndDate
        SELECT @Swap      = @EndDate,
               @EndDate   = @StartDate,
               @StartDate = @Swap

    --Calculate and return the number of workdays using the input parameters.
    --This is the meat of the function.
    --This is really just one formula with a couple of parts that are listed on separate lines for documentation purposes.
     RETURN (
        --Start with total number of days including weekends
        (DATEDIFF(dd,@StartDate, @EndDate)+1)
        --Subtact 2 days for each full weekend
        -(DATEDIFF(wk,@StartDate, @EndDate)*2)
        --If StartDate is a Sunday, Subtract 1
        -(CASE WHEN DATENAME(dw, @StartDate) = 'Sunday'
            THEN 1
            ELSE 0
        --If EndDate is a Saturday, Subtract 1
        -(CASE WHEN DATENAME(dw, @EndDate) = 'Saturday'
            THEN 1
            ELSE 0

If you need to use a custom calendar, you might need to add some checks and some parameters. Hopefully it will provide a good starting point.

How to get info on sent PHP curl request

curl_getinfo() must be added before closing the curl handler

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "");
curl_setopt($ch, CURLOPT_USERPWD, "someusername:secretpassword");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
$info = curl_getinfo($ch);

CSS align images and text on same line

This question is from 2012, some things are changed from that date, and since it still receives a lot of traffic from google, I feel like completing it adding flexbox as a solution.

By now, flexbox is the advised pattern to be used, even if it lacks IE9 support.

The only thing you have to care about is adding display: flex in the parent element. As default and without the need of setting other property, all the children of that element will be aligned in the same row.

If you want to read more about flexbox, you can do it here.

.container {_x000D_
  display: flex;_x000D_
img {_x000D_
  margin: 6px;_x000D_
<div class="container">_x000D_
  <img src="" /> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum._x000D_

Can I get div's background-image url?

Here is a simple regex which will remove the url(" and ") from the returned string.

var css = $("#myElem").css("background-image");
var img = css.replace(/(?:^url\(["']?|["']?\)$)/g, "");

How to ping an IP address

Just an addition to what others have given, even though they work well but in some cases if internet is slow or some unknown network problem exists, some of the codes won't work (isReachable()). But this code mentioned below creates a process which acts as a command line ping (cmd ping) to windows. It works for me in all cases, tried and tested.

Code :-

public class JavaPingApp {

public static void runSystemCommand(String command) {

    try {
        Process p = Runtime.getRuntime().exec(command);
        BufferedReader inputStream = new BufferedReader(
                new InputStreamReader(p.getInputStream()));

        String s = "";
        // reading output stream of the command
        while ((s = inputStream.readLine()) != null) {

    } catch (Exception e) {

public static void main(String[] args) {

    String ip = ""; //Any IP Address on your network / Web
    runSystemCommand("ping " + ip);

Hope it helps, Cheers!!!

Reset MySQL root password using ALTER USER statement after install on Mac

Here is the way works for me.

mysql> show databases ;

ERROR 1820 (HY000): You must reset your password using ALTER USER statement before executing this statement.

mysql> uninstall plugin validate_password;

ERROR 1820 (HY000): You must reset your password using ALTER USER statement before executing this statement.

mysql> alter user 'root'@'localhost' identified by 'root';

Query OK, 0 rows affected (0.01 sec)

mysql> flush privileges;

Query OK, 0 rows affected (0.03 sec)

Oracle: how to add minutes to a timestamp?

In addition to being able to add a number of days to a date, you can use interval data types assuming you are on Oracle 9i or later, which can be somewhat easier to read,

SQL> ed
Wrote file afiedt.buf
SELECT sysdate, sysdate + interval '30' minute FROM dual
SQL> /

-------------------- --------------------
02-NOV-2008 16:21:40 02-NOV-2008 16:51:40

ValueError : I/O operation on closed file

I was getting this exception when debugging in PyCharm, given that no breakpoint was being hit. To prevent it, I added a breakpoint just after the with block, and then it stopped happening.

Extract first and last row of a dataframe in pandas

Here is the same style as in large datasets:

x = df[:5]
y = pd.DataFrame([['...']*df.shape[1]], columns=df.columns, index=['...'])
z = df[-5:]
frame = [x, y, z]
result = pd.concat(frame)



                     date  temp
0     1981-01-01 00:00:00  20.7
1     1981-01-02 00:00:00  17.9
2     1981-01-03 00:00:00  18.8
3     1981-01-04 00:00:00  14.6
4     1981-01-05 00:00:00  15.8
...                   ...   ...
3645  1990-12-27 00:00:00    14
3646  1990-12-28 00:00:00  13.6
3647  1990-12-29 00:00:00  13.5
3648  1990-12-30 00:00:00  15.7
3649  1990-12-31 00:00:00    13

error: 'Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)' -- Missing /var/run/mysqld/mysqld.sock

I had similar problem on a CentOS VPS. If MySQL won't start or keeps crashing right after it starts, try these steps:

1) Find my.cnf file (mine was located in /etc/my.cnf) and add the line:

innodb_force_recovery = X

replacing X with a number from 1 to 6, starting from 1 and then incrementing if MySQL won't start. Setting to 4, 5 or 6 can delete your data so be carefull and read before.

2) Restart MySQL service. Only SELECT will run and that's normal at this point.

3) Dump all your databases/schemas with mysqldump one by one, do not compress the dumps because you'd have to uncompress them later anyway.

4) Move (or delete!) only the bd's directories inside /var/lib/mysql, preserving the individual files in the root.

5) Stop MySQL and then uncomment the line added in 1). Start MySQL.

6) Recover all bd's dumped in 3).

Good luck!

adb devices command not working

HTC One m7 running fresh Cyanogenmod 11.

Phone is connected USB and tethering my data connection.

Then I get this surprise:

cinder@ultrabook:~/temp/htc_m7/2015-11-11$ adb shell
error: insufficient permissions for device

cinder@ultrabook:~/temp/htc_m7/2015-11-11$ adb devices
List of devices attached
????????????    no permissions

SOLUTION: Turn tethering OFF on phone.

cinder@ultrabook:~/temp/htc_m7/2015-11-11$ adb devices
List of devices attached
HT36AW908858    device

How to change default language for SQL Server?

Please try below:

SET @Today = '12/5/2007';  

SELECT DATENAME(month, @Today) AS 'Month Name';  

SET LANGUAGE us_english;  
SELECT DATENAME(month, @Today) AS 'Month Name' ;  


Netbeans - class does not have a main method

in Project window right click on your project and select properties go to Run and set Main Class ( you can brows it) . this manual work if you have static main in some class :

public class Someclass

     * @param args the command line arguments
    public static void main(String[] args)
        //your code

Netbeans doesn't have any conflict with W7 and you can use version 6.8 .

Parse error: syntax error, unexpected T_ECHO in

Missing ; after var_dump($row)

‘ant’ is not recognized as an internal or external command

I had a similar issue, but the reason that %ANT_HOME% wasn't resolving is that I had added it as a USER variable, not a SYSTEM one. Sorted now, thanks to this post.

ImportError: no module named win32api

After installing pywin32

Steps to correctly install your module (pywin32)

  1. First search where is your python pip is present

    1a. For Example in my case location of pip - C:\Users\username\AppData\Local\Programs\Python\Python36-32\Scripts

  2. Then open your command prompt and change directory to your pip folder location.

    cd C:\Users\username\AppData\Local\Programs\Python\Python36-32\Scripts
    C:\Users\username\AppData\Local\Programs\Python\Python36-32\Scripts>pip install 

Restart your IDE

All done now you can use the module .

Illegal character in path at index 16

If this error occurs with the jdk use this :

progra~1 instead of program files in the path example :

 c:/progra~1/java instead of c:/program files/java

It will be ok always avoid space in java code.....

it can be used for every thing in program files, otherwise put quotes at the beginning and the en of path


Drawing circles with System.Drawing

With this code you can easily draw a circle... C# is great and easy my friend

public partial class Form1 : Form

public Form1()

  private void button1_Click(object sender, EventArgs e)
        Graphics myGraphics = base.CreateGraphics();
        Pen myPen = new Pen(Color.Red);
        SolidBrush mySolidBrush = new SolidBrush(Color.Red);
        myGraphics.DrawEllipse(myPen, 50, 50, 150, 150);

How to export query result to csv in Oracle SQL Developer?

CSV Export does not escape your data. Watch out for strings which end in \ because the resulting \" will look like an escaped " and not a \. Then you have the wrong number of " and your entire row is broken.

How to "test" NoneType in python?

Python 2.7 :

x = None
isinstance(x, type(None))


isinstance(None, type(None))

==> True

How to create exe of a console application

For .NET Core 2.2 you can publish the application and set the target to be a self-contained executable.

In Visual Studio right click your console application project. Select publish to folder and set the profile settings like so:

Visual Studio Publish Menu

You'll find your compiled code with the .exe in the publish folder.

Accessing a property in a parent Component

On Angular 6, I access parent properties by injecting the parent via constructor. Not the best solution but it works:

 constructor(@Optional() public parentComponentInjectionObject: ParentComponent){
    // And access like this:

How do I check to see if my array includes an object?

Arrays in Ruby don't have exists? method, but they have an include? method as described in the docs. Something like

unless @suggested_horses.include?(horse)
   @suggested_horses << horse

should work out of box.

How to send and retrieve parameters using $state.go toParams and $stateParams?

Try With reload: true?

Couldn't figure out what was going on for the longest time -- turns out I was fooling myself. If you're certain that things are written correctly and you will to use the same state, try reload: true:

.state('status.item', {
    url: '/:id',
    views: {...}

$state.go('status.item', { id: $ }, { reload: true });

Hope this saves you time!

How to get Rails.logger printing to the console/stdout when running rspec?

A solution that I like, because it keeps rspec output separate from actual rails log output, is to do the following:

  • Open a second terminal window or tab, and arrange it so that you can see both the main terminal you're running rspec on as well as the new one.
  • Run a tail command in the second window so you see the rails log in the test environment. By default this can be like $ tail -f $RAILS_APP_DIR/logs/test.log or tail -f $RAILS_APP_DIR\logs\test.log for Window users
  • Run your rspec suites

If you are running a multi-pane terminal like iTerm, this becomes even more fun and you have rspec and the test.log output side by side.

Pass row number as variable in excel sheet

An alternative is to use OFFSET:

Assuming the column value is stored in B1, you can use the following

C1 = OFFSET(A1, 0, B1 - 1)

This works by:

a) taking a base cell (A1)
b) adding 0 to the row (keeping it as A)
c) adding (A5 - 1) to the column

You can also use another value instead of 0 if you want to change the row value too.

Bootstrap 4 - Glyphicons migration?

Migrating from Glyphicons to Font Awesome is quite easy.

Include a reference to Font Awesome (either locally, or use the CDN).

<link href="" rel="stylesheet">

Then run a search and replace where you search for glyphicon glyphicon- and replace it with fa fa-, and also change the enclosing element from <span to <i. Most of the CSS class names are the same. Some have changed though, so you have to manually fix those.

Compare and contrast REST and SOAP web services?

In day to day, practical programming terms, the biggest difference is in the fact that with SOAP you are working with static and strongly defined data exchange formats where as with REST and JSON data exchange formatting is very loose by comparison. For example with SOAP you can validate that exchanged data matches an XSD schema. The XSD therefore serves as a 'contract' on how the client and the server are to understand how the data being exchanged must be structured.

JSON data is typically not passed around according to a strongly defined format (unless you're using a framework that supports it .. e.g. or implementing json-schema).

In-fact, some (many/most) would argue that the "dynamic" secret sauce of JSON goes against the philosophy/culture of constraining it by data contracts (Should JSON RESTful web services use data contract)

People used to working in dynamic loosely typed languages tend to feel more comfortable with the looseness of JSON while developers from strongly typed languages prefer XML.

How do ports work with IPv6?

They're the same, aren't they? Now I'm losing confidence in myself but I really thought IPv6 was just an addressing change. TCP and UDP are still addressed as they are under IPv4.

Cordova : Requirements check failed for JDK 1.8 or greater

MacOS answer with multiple Java versions installed and no need to uninstall

Show me what versions of Java I have installed :

$ ls -l /Library/Java/JavaVirtualMachines/

To set it to my jdk1.8 version :

$ ln -s /Library/Java/JavaVirtualMachines/jdk1.8.0_261.jdk/Contents/Home/bin/javac /usr/local/bin/javac

To set it to my jdk11 version :

$ ln -s /Library/Java/JavaVirtualMachines/jdk-11.0.7.jdk/Contents/Home/bin/javac /usr/local/bin/javac


Note that, despite what the message says, it appears that it means that it wants version 1.8, and throws this message if you have a later version.

What follows is my earlier attempts which lead me to the above answer, which then worked ... You might need to do something different depending on what's installed, so maybe these notes might help :

Set it to my jdk1.8 version

$ export PATH=/Library/Java/JavaVirtualMachines/jdk-11.0.7.jdk/Contents/Home/bin/javac:$PATH

Set it to my jdk11 version

$ export PATH=/Library/Java/JavaVirtualMachines/jdk1.8.0_261.jdk/Contents/Home/bin/javac:$PATH

... but actually that doesn't work because /usr/bin/javac is still what runs first :

$ which javac

... to see what runs first on the path :

$ cat /etc/paths

That means I can override the /usr/bin/javac ... see the commands at the top of the answer ...
The command to set it to jdk1.8 using ln, at the top of this answer, is what worked for me.

Unable to update the EntitySet - because it has a DefiningQuery and no <UpdateFunction> element exist

The error may have occurred if your table doesn't have a primary key, in this case the table is "read only", and the db.SaveChanges () command will always error.

How to view data saved in android database(SQLite)?

1. Download SQLite Manager
2. Go to your DDMS tab in Eclipse
3. Go to the File Explorer --> data --> data --> "Your Package Name" --> pull file from device 4. Open file in SQLite Manager.
5. View data.

What is the difference between Set and List?

  • A List is an ordered grouping of items
  • A Set is an unordered grouping of items with no duplicates allowed (usually)

Conceptually we usually refer to an unordered grouping that allows duplicates as a Bag and doesn't allow duplicates is a Set.

PHP Get name of current directory

echo basename(__DIR__); will return the current directory name only
echo basename(__FILE__); will return the current file name only


you need to convert to char first because converting to int adds those days to 1900-01-01

select CONVERT (datetime,convert(char(8),rnwl_efctv_dt ))

here are some examples

select CONVERT (datetime,5)

1900-01-06 00:00:00.000

select CONVERT (datetime,20100101)

blows up, because you can't add 20100101 days to go above the limit

convert to char first

declare @i int
select @i = 20100101
select CONVERT (datetime,convert(char(8),@i))

How does data binding work in AngularJS?

It happened that I needed to link a data model of a person with a form, what I did was a direct mapping of the data with the form.

For example if the model had something like:


The control input of the form:

<input type="text" name="namePeople" model="">

That way if you modify the value of the object controller, this will be reflected automatically in the view.

An example where I passed the model is updated from server data is when you ask for a zip code and zip code based on written loads a list of colonies and cities associated with that view, and by default set the first value with the user. And this I worked very well, what does happen, is that angularJS sometimes takes a few seconds to refresh the model, to do this you can put a spinner while displaying the data.

how can select from drop down menu and call javascript function

<script type="text/javascript">
function report(func)

function daily()

function monthly()

How to find out client ID of component for ajax update/render? Cannot find component with expression "foo" referenced from "bar"

Look in HTML output for actual client ID

You need to look in the generated HTML output to find out the right client ID. Open the page in browser, do a rightclick and View Source. Locate the HTML representation of the JSF component of interest and take its id as client ID. You can use it in an absolute or relative way depending on the current naming container. See following chapter.

Note: if it happens to contain iteration index like :0:, :1:, etc (because it's inside an iterating component), then you need to realize that updating a specific iteration round is not always supported. See bottom of answer for more detail on that.

Memorize NamingContainer components and always give them a fixed ID

If a component which you'd like to reference by ajax process/execute/update/render is inside the same NamingContainer parent, then just reference its own ID.

<h:form id="form">
    <p:commandLink update="result"> <!-- OK! -->
    <h:panelGroup id="result" />

If it's not inside the same NamingContainer, then you need to reference it using an absolute client ID. An absolute client ID starts with the NamingContainer separator character, which is by default :.

<h:form id="form">
    <p:commandLink update="result"> <!-- FAIL! -->
<h:panelGroup id="result" />
<h:form id="form">
    <p:commandLink update=":result"> <!-- OK! -->
<h:panelGroup id="result" />
<h:form id="form">
    <p:commandLink update=":result"> <!-- FAIL! -->
<h:form id="otherform">
    <h:panelGroup id="result" />
<h:form id="form">
    <p:commandLink update=":otherform:result"> <!-- OK! -->
<h:form id="otherform">
    <h:panelGroup id="result" />

NamingContainer components are for example <h:form>, <h:dataTable>, <p:tabView>, <cc:implementation> (thus, all composite components), etc. You recognize them easily by looking at the generated HTML output, their ID will be prepended to the generated client ID of all child components. Note that when they don't have a fixed ID, then JSF will use an autogenerated ID in j_idXXX format. You should absolutely avoid that by giving them a fixed ID. The OmniFaces NoAutoGeneratedIdViewHandler may be helpful in this during development.

If you know to find the javadoc of the UIComponent in question, then you can also just check in there whether it implements the NamingContainer interface or not. For example, the HtmlForm (the UIComponent behind <h:form> tag) shows it implements NamingContainer, but the HtmlPanelGroup (the UIComponent behind <h:panelGroup> tag) does not show it, so it does not implement NamingContainer. Here is the javadoc of all standard components and here is the javadoc of PrimeFaces.

Solving your problem

So in your case of:

<p:tabView id="tabs"><!-- This is a NamingContainer -->
    <p:tab id="search"><!-- This is NOT a NamingContainer -->
        <h:form id="insTable"><!-- This is a NamingContainer -->
            <p:dialog id="dlg"><!-- This is NOT a NamingContainer -->
                <h:panelGrid id="display">

The generated HTML output of <h:panelGrid id="display"> looks like this:

<table id="tabs:insTable:display">

You need to take exactly that id as client ID and then prefix with : for usage in update:

<p:commandLink update=":tabs:insTable:display">

Referencing outside include/tagfile/composite

If this command link is inside an include/tagfile, and the target is outside it, and thus you don't necessarily know the ID of the naming container parent of the current naming container, then you can dynamically reference it via UIComponent#getNamingContainer() like so:

<p:commandLink update=":#{component.namingContainer.parent.namingContainer.clientId}:display">

Or, if this command link is inside a composite component and the target is outside it:

<p:commandLink update=":#{cc.parent.namingContainer.clientId}:display">

Or, if both the command link and target are inside same composite component:

<p:commandLink update=":#{cc.clientId}:display">

See also Get id of parent naming container in template for in render / update attribute

How does it work under the covers

This all is specified as "search expression" in the UIComponent#findComponent() javadoc:

A search expression consists of either an identifier (which is matched exactly against the id property of a UIComponent, or a series of such identifiers linked by the UINamingContainer#getSeparatorChar character value. The search algorithm should operates as follows, though alternate alogrithms may be used as long as the end result is the same:

  • Identify the UIComponent that will be the base for searching, by stopping as soon as one of the following conditions is met:
    • If the search expression begins with the the separator character (called an "absolute" search expression), the base will be the root UIComponent of the component tree. The leading separator character will be stripped off, and the remainder of the search expression will be treated as a "relative" search expression as described below.
    • Otherwise, if this UIComponent is a NamingContainer it will serve as the basis.
    • Otherwise, search up the parents of this component. If a NamingContainer is encountered, it will be the base.
    • Otherwise (if no NamingContainer is encountered) the root UIComponent will be the base.
  • The search expression (possibly modified in the previous step) is now a "relative" search expression that will be used to locate the component (if any) that has an id that matches, within the scope of the base component. The match is performed as follows:
    • If the search expression is a simple identifier, this value is compared to the id property, and then recursively through the facets and children of the base UIComponent (except that if a descendant NamingContainer is found, its own facets and children are not searched).
    • If the search expression includes more than one identifier separated by the separator character, the first identifier is used to locate a NamingContainer by the rules in the previous bullet point. Then, the findComponent() method of this NamingContainer will be called, passing the remainder of the search expression.

Note that PrimeFaces also adheres the JSF spec, but RichFaces uses "some additional exceptions".

"reRender" uses UIComponent.findComponent() algorithm (with some additional exceptions) to find the component in the component tree.

Those additional exceptions are nowhere in detail described, but it's known that relative component IDs (i.e. those not starting with :) are not only searched in the context of the closest parent NamingContainer, but also in all other NamingContainer components in the same view (which is a relatively expensive job by the way).

Never use prependId="false"

If this all still doesn't work, then verify if you aren't using <h:form prependId="false">. This will fail during processing the ajax submit and render. See also this related question: UIForm with prependId="false" breaks <f:ajax render>.

Referencing specific iteration round of iterating components

It was for long time not possible to reference a specific iterated item in iterating components like <ui:repeat> and <h:dataTable> like so:

<h:form id="form">
    <ui:repeat id="list" value="#{['one','two','three']}" var="item">
        <h:outputText id="item" value="#{item}" /><br/>

    <h:commandButton value="Update second item">
        <f:ajax render=":form:list:1:item" />

However, since Mojarra 2.2.5 the <f:ajax> started to support it (it simply stopped validating it; thus you would never face the in the question mentioned exception anymore; another enhancement fix is planned for that later).

This only doesn't work yet in current MyFaces 2.2.7 and PrimeFaces 5.2 versions. The support might come in the future versions. In the meanwhile, your best bet is to update the iterating component itself, or a parent in case it doesn't render HTML, like <ui:repeat>.

When using PrimeFaces, consider Search Expressions or Selectors

PrimeFaces Search Expressions allows you to reference components via JSF component tree search expressions. JSF has several builtin:

  • @this: current component
  • @form: parent UIForm
  • @all: entire document
  • @none: nothing

PrimeFaces has enhanced this with new keywords and composite expression support:

  • @parent: parent component
  • @namingcontainer: parent UINamingContainer
  • @widgetVar(name): component as identified by given widgetVar

You can also mix those keywords in composite expressions such as @form:@parent, @this:@parent:@parent, etc.

PrimeFaces Selectors (PFS) as in @(.someclass) allows you to reference components via jQuery CSS selector syntax. E.g. referencing components having all a common style class in the HTML output. This is particularly helpful in case you need to reference "a lot of" components. This only prerequires that the target components have all a client ID in the HTML output (fixed or autogenerated, doesn't matter). See also How do PrimeFaces Selectors as in update="@(.myClass)" work?

Value does not fall within the expected range

In case of WSS 3.0 recently I experienced same issue. It was because of column that was accessed from code was not present in the wss list.

SecurityError: Blocked a frame with origin from accessing a cross-origin frame

If you have control over the content of the iframe - that is, if it is merely loaded in a cross-origin setup such as on Amazon Mechanical Turk - you can circumvent this problem with the <body onload='my_func(my_arg)'> attribute for the inner html.

For example, for the inner html, use the this html parameter (yes - this is defined and it refers to the parent window of the inner body element):

<body onload='changeForm(this)'>

In the inner html :

    function changeForm(window) {
        console.log('inner window loaded: do whatever you want with the inner html');
        window.document.getElementById('mturk_form').style.display = 'none';

MySQL: Grant **all** privileges on database


This is how I create my "Super User" privileges (although I would normally specify a host).


While this answer can solve the problem of access, WITH GRANT OPTION creates a MySQL user that can edit the permissions of other users.

The GRANT OPTION privilege enables you to give to other users or remove from other users those privileges that you yourself possess.

For security reasons, you should not use this type of user account for any process that the public will have access to (i.e. a website). It is recommended that you create a user with only database privileges for that kind of use.

Remove whitespaces inside a string in javascript

Probably because you forgot to implement the solution in the accepted answer. That's the code that makes trim() work.


This answer only applies to older browsers. Newer browsers apparently support trim() natively.

Converting XML to JSON using Python?

You may want to have a look at This project starts off with an XML to JSON conversion of a large library of XML files. There was much research done in the conversion, and the most simple intuitive XML -> JSON mapping was produced (it is described early in the document). In summary, convert everything to a JSON object, and put repeating blocks as a list of objects.

objects meaning key/value pairs (dictionary in Python, hashmap in Java, object in JavaScript)

There is no mapping back to XML to get an identical document, the reason is, it is unknown whether a key/value pair was an attribute or an <key>value</key>, therefore that information is lost.

If you ask me, attributes are a hack to start; then again they worked well for HTML.

HashMap allows duplicates?

Hashmap type Overwrite that key if hashmap key is same key




How to convert uint8 Array to base64 Encoded String?

function Uint8ToBase64(u8Arr){
  var CHUNK_SIZE = 0x8000; //arbitrary number
  var index = 0;
  var length = u8Arr.length;
  var result = '';
  var slice;
  while (index < length) {
    slice = u8Arr.subarray(index, Math.min(index + CHUNK_SIZE, length)); 
    result += String.fromCharCode.apply(null, slice);
    index += CHUNK_SIZE;
  return btoa(result);

You can use this function if you have a very large Uint8Array. This is for Javascript, can be useful in case of FileReader readAsArrayBuffer.

Python 3 turn range to a list

You can just construct a list from the range object:

my_list = list(range(1, 1001))

This is how you do it with generators in python2.x as well. Typically speaking, you probably don't need a list though since you can come by the value of my_list[i] more efficiently (i + 1), and if you just need to iterate over it, you can just fall back on range.

Also note that on python2.x, xrange is still indexable1. This means that range on python3.x also has the same property2

1print xrange(30)[12] works for python2.x

2The analogous statement to 1 in python3.x is print(range(30)[12]) and that works also.

Populating a ListView using an ArrayList?

You need to do it through an ArrayAdapter which will adapt your ArrayList (or any other collection) to your items in your layout (ListView, Spinner etc.).

This is what the Android developer guide says:

A ListAdapter that manages a ListView backed by an array of arbitrary objects. By default this class expects that the provided resource id references a single TextView. If you want to use a more complex layout, use the constructors that also takes a field id. That field id should reference a TextView in the larger layout resource.

However the TextView is referenced, it will be filled with the toString() of each object in the array. You can add lists or arrays of custom objects. Override the toString() method of your objects to determine what text will be displayed for the item in the list.

To use something other than TextViews for the array display, for instance ImageViews, or to have some of data besides toString() results fill the views, override getView(int, View, ViewGroup) to return the type of view you want.

So your code should look like:

public class YourActivity extends Activity {

    private ListView lv;

    public void onCreate(Bundle saveInstanceState) {

         lv = (ListView) findViewById(;

         // Instanciating an array list (you don't need to do this, 
         // you already have yours).
         List<String> your_array_list = new ArrayList<String>();

         // This is the array adapter, it takes the context of the activity as a 
         // first parameter, the type of list view as a second parameter and your 
         // array as a third parameter.
         ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
                 your_array_list );


How to validate domain credentials?

I`m using the following code to validate credentials. The method shown below will confirm if the credentials are correct and if not wether the password is expired or needs change.

I`ve been looking for something like this for ages... So i hope this helps someone!

using System;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using System.Runtime.InteropServices;

namespace User
    public static class UserValidation
        [DllImport("advapi32.dll", SetLastError = true)]
        static extern bool LogonUser(string principal, string authority, string password, LogonTypes logonType, LogonProviders logonProvider, out IntPtr token);
        [DllImport("kernel32.dll", SetLastError = true)]
        static extern bool CloseHandle(IntPtr handle);
        enum LogonProviders : uint
            Default = 0, // default for platform (use this!)
            WinNT35,     // sends smoke signals to authority
            WinNT40,     // uses NTLM
            WinNT50      // negotiates Kerb or NTLM
        enum LogonTypes : uint
            Interactive = 2,
            Network = 3,
            Batch = 4,
            Service = 5,
            Unlock = 7,
            NetworkCleartext = 8,
            NewCredentials = 9
        public  const int ERROR_PASSWORD_MUST_CHANGE = 1907;
        public  const int ERROR_LOGON_FAILURE = 1326;
        public  const int ERROR_ACCOUNT_RESTRICTION = 1327;
        public  const int ERROR_ACCOUNT_DISABLED = 1331;
        public  const int ERROR_INVALID_LOGON_HOURS = 1328;
        public  const int ERROR_NO_LOGON_SERVERS = 1311;
        public  const int ERROR_INVALID_WORKSTATION = 1329;
        public  const int ERROR_ACCOUNT_LOCKED_OUT = 1909;      //It gives this error if the account is locked, REGARDLESS OF WHETHER VALID CREDENTIALS WERE PROVIDED!!!
        public  const int ERROR_ACCOUNT_EXPIRED = 1793;
        public  const int ERROR_PASSWORD_EXPIRED = 1330;

        public static int CheckUserLogon(string username, string password, string domain_fqdn)
            int errorCode = 0;
            using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, domain_fqdn, "ADMIN_USER", "PASSWORD"))
                if (!pc.ValidateCredentials(username, password))
                    IntPtr token = new IntPtr();
                        if (!LogonUser(username, domain_fqdn, password, LogonTypes.Network, LogonProviders.Default, out token))
                            errorCode = Marshal.GetLastWin32Error();
                    catch (Exception)
            return errorCode;

How do you fadeIn and animate at the same time?

For people still looking a couple of years later, things have changed a bit. You can now use the queue for .fadeIn() as well so that it will work like this:

$('.tooltip').fadeIn({queue: false, duration: 'slow'});
$('.tooltip').animate({ top: "-10px" }, 'slow');

This has the benefit of working on display: none elements so you don't need the extra two lines of code.

Column count doesn't match value count at row 1

You should also look at new triggers.

MySQL doesn't show the table name in the error, so you're really left in a lurch. Here's a working example:

use test;
create table blah (id int primary key AUTO_INCREMENT, data varchar(100));
create table audit_blah (audit_id int primary key AUTO_INCREMENT, action enum('INSERT','UPDATE','DELETE'), id int, data varchar(100) null);
insert into audit_blah(action, id, data) values ('INSERT', 1, 'a');
select * from blah;
select * from audit_blah;
truncate table audit_blah;

delimiter //
/* I've commented out "id" below, so the insert fails with an ambiguous error: */
create trigger ai_blah after insert on blah for each row 
  insert into audit_blah (action, /*id,*/ data) values ('INSERT', /*,*/;

/* This insert is valid, but you'll get an exception from the trigger: */
insert into blah (data) values ('data1');

How to detect the physical connected state of a network cable/connector?

There exists two daemons that detect these events:

ifplugd and netplugd

C#: How to make pressing enter in a text box trigger a button, yet still allow shortcuts such as "Ctrl+A" to get through?

If you add e.SuppressKeyPress = true; as shown in the answer in this link you will suppress the annoying ding sound that occurs.

Difference between javacore, thread dump and heap dump in Websphere

Thread dumps are javacore show snapshot of threads running in JVM, it is useful to debug hang issues, it will provide info about java level dead locks and also IBm version of javacores provides much more useful information, such as heap usage, CPU usage of each thread and overall heap usage along with number of classes laded by the JVM.

Heapdumps, provides information about Java heap usage by an JVM, which can be used to debug memory leaks. Heapdumps are generated by IBM JVMs when a JVM is runs into outofmemoryerror, Heapdumps are only for heap leaks in java, native out of memory error may result system dumps usually with an "GPF" General protection Fault.

ORACLE convert number to string

This should solve your problem:

select replace(to_char(a, '90D90'),'.00','')
select 50 a from dual
select 50.57 from dual
select 5.57 from dual
select 0.35 from dual
select 0.4 from dual

Give a look also as this SQL Fiddle for test.

Is there an equivalent to background-size: cover and contain for image elements?

For IE you also need to include the second line - width: 100%;

.mydiv img {
    max-width: 100%;
    width: 100%;