Programs & Examples On #Phpt

PHPT scripts are unit and integration tests for the PHP interpreter and user applications.

set value of input field by php variable's value

inside the Form, You can use this code. Replace your variable name (i use $variable)

<input type="text" value="<?php echo (isset($variable))?$variable:'';?>">

Apache: The requested URL / was not found on this server. Apache

Try changing Deny from all to Allow from all in your conf and see if that helps.

How to replace url parameter with javascript/jquery?

Editing a Parameter The set method of the URLSearchParams object sets the new value of the parameter.

After setting the new value you can get the new query string with the toString() method. This query string can be set as the new value of the search property of the URL object.

The final new url can then be retrieved with the toString() method of the URL object.

var query_string =;

var search_params = new URLSearchParams(query_string); 

// new value of "id" is set to "101"
search_params.set('id', '101');

// change the search property of the main url = search_params.toString();

// the new url string
var new_url = url.toString();

// output :

Source -


You can return json in PHP this way:

header('Content-Type: application/json');
echo json_encode(array('foo' => 'bar'));

How to select an option from drop down using Selenium WebDriver C#?

Adding a point to this- I came across a problem that OpenQA.Selenium.Support.UI namespace was not available after installing Selenium.NET binding into the C# project. Later found out that we can easily install latest version of Selenium WebDriver Support Classes by running the command:

Install-Package Selenium.Support

in NuGet Package Manager Console, or install Selenium.Support from NuGet Manager.

Rails - passing parameters in link_to

Try this

link_to "+ Service", my_services_new_path(:account_id =>

it will pass the account_id as you want.

For more details on link_to use this

Inserting code in this LaTeX document with indentation

Minted, whether from GitHub or CTAN, the Comprehensive TeX Archive Network, works in Overleaf, TeX Live and MiKTeX.

It requires the installation of the Python package Pygments; this is explained in the documentation in either source above. Although Pygments brands itself as a Python syntax highlighter, Minted guarantees the coverage of hundreds of other languages.



\begin{minted}[mathescape, linenos]{python}

# Note: $\pi=\lim_{n\to\infty}\frac{P_n}{d}$
title = "Hello World"

sum = 0
for i in range(10):
 sum += i




enter image description here

How do I create a round cornered UILabel on the iPhone?

Works fine in Xcode 8.1.2 with Swift 3

.cornerRadius is the key property to set rounded edges. If you are using the same style for all labels in your application, I would recommend for an extension method.


 // extension Class
extension UILabel {

    // extension user defined Method
    func setRoundEdge() {
        let myGreenColor = (UIColor(red: -0.108958, green: 0.714926, blue: 0.758113, alpha: 1.0))
        //Width of border
        self.layer.borderWidth = 1.0
        //How much the edge to be rounded
        self.layer.cornerRadius = 5.0

        // following properties are optional
        //color for border
        self.layer.borderColor = myGreenColor.cgColor
        //color for text
        self.textColor =
        // Mask the bound
        self.layer.masksToBounds = true
        //clip the pixel contents
        self.clipsToBounds = true


enter image description here

Why Extension method?

Create a Swift file and add the following code, which has the Extention method to the "UILabel" class, where this method is user defined but will work for all the label in your application and will help to maintain consistency and clean code, if you change any style in future require only in the extension method.

Generate an integer sequence in MySQL

The simplest way to do this is:

SET @seq := 0;
SELECT @seq := FLOOR(@seq + 1) AS sequence, yt.*
FROM your_table yt;

or in one query:

SELECT @seq := FLOOR(@seq + 1) AS sequence, yt.*
FROM (SELECT @seq := 0) s, your_table yt;

The FLOOR() function is used here to get an INTEGER in place of a FLOAT. Sometimes it is needed.

My answer was inspired by David Poor answer. Thanks David!

How to get a index value from foreach loop in jstl

use varStatus to get the index c:forEach varStatus properties

<c:forEach var="categoryName" items="${categoriesList}" varStatus="loop">
    <li><a onclick="getCategoryIndex(${loop.index})" href="#">${categoryName}</a></li>

How to configure welcome file list in web.xml

I saw a nice solution in this stackoverflow link that may help the readers of the defulat servlet handling issue by using the empty string URL pattern "" :



    <url-pattern></url-pattern> <!-- Yes, empty string! -->

What's the difference between __PRETTY_FUNCTION__, __FUNCTION__, __func__?

Despite not fully answering the original question, this is probably what most people googling this wanted to see.

For GCC:

$ cat test.cpp 
#include <iostream>

int main(int argc, char **argv)
    std::cout << __func__ << std::endl
              << __FUNCTION__ << std::endl
              << __PRETTY_FUNCTION__ << std::endl;
$ g++ test.cpp 
$ ./a.out 
int main(int, char**)

How to get screen width and height

Alternative way using function

private int[] getScreenSIze(){
        DisplayMetrics displaymetrics = new DisplayMetrics();
        int h = displaymetrics.heightPixels;
        int w = displaymetrics.widthPixels;

        int[] size={w,h};
        return size;


on button click or on your create function add the following code

int[] screenSize= getScreenSIze();
        int width=screenSize[0];
        int height=screenSize[1];
        screenSizes.setText("Phone Screen sizes \n\n  width = "+width+" \n Height = "+height);

See demo source code

gcc makefile error: "No rule to make target ..."

Is that it exactly? Remember that Makefile syntax is whitespace aware and requires tabs to indent commands under actions.

Does C++ support 'finally' blocks? (And what's this 'RAII' I keep hearing about?)

No, C++ does not support 'finally' blocks. The reason is that C++ instead supports RAII: "Resource Acquisition Is Initialization" -- a poor name for a really useful concept.

The idea is that an object's destructor is responsible for freeing resources. When the object has automatic storage duration, the object's destructor will be called when the block in which it was created exits -- even when that block is exited in the presence of an exception. Here is Bjarne Stroustrup's explanation of the topic.

A common use for RAII is locking a mutex:

// A class with implements RAII
class lock
    mutex &m_;

    lock(mutex &m)
      : m_(m)

// A class which uses 'mutex' and 'lock' objects
class foo
    mutex mutex_; // mutex for locking 'foo' object
    void bar()
        lock scopeLock(mutex_); // lock object.

        foobar(); // an operation which may throw an exception

        // scopeLock will be destructed even if an exception
        // occurs, which will release the mutex and allow
        // other functions to lock the object and run.

RAII also simplifies using objects as members of other classes. When the owning class' is destructed, the resource managed by the RAII class gets released because the destructor for the RAII-managed class gets called as a result. This means that when you use RAII for all members in a class that manage resources, you can get away with using a very simple, maybe even the default, destructor for the owner class since it doesn't need to manually manage its member resource lifetimes. (Thanks to Mike B for pointing this out.)

For those familliar with C# or VB.NET, you may recognize that RAII is similar to .NET deterministic destruction using IDisposable and 'using' statements. Indeed, the two methods are very similar. The main difference is that RAII will deterministically release any type of resource -- including memory. When implementing IDisposable in .NET (even the .NET language C++/CLI), resources will be deterministically released except for memory. In .NET, memory is not deterministically released; memory is only released during garbage collection cycles.


† Some people believe that "Destruction is Resource Relinquishment" is a more accurate name for the RAII idiom.

Parse Error: Adjacent JSX elements must be wrapped in an enclosing tag

Invalid: Not only child elements

            <h2>Responsive Form</h2>
            <div>Adjacent JSX elements must be wrapped in an enclosing tag</div>
            <div className="col-sm-4 offset-sm-4">
                <form id="contact-form" onSubmit={this.handleSubmit.bind(this)} method="POST">
                    <div className="form-group">
                        <label for="name">Name</label>
                        <input type="text" className="form-control" id="name" />
                    <div className="form-group">
                        <label for="exampleInputEmail1">Email address</label>
                        <input type="email" className="form-control" id="email" aria-describedby="emailHelp" />
                    <div className="form-group">
                        <label for="message">Message</label>
                        <textarea className="form-control" rows="5" id="message"></textarea>
                    <button type="submit" className="btn btn-primary">Submit</button>

Valid: Root element under child elements

            <h2>Responsive Form</h2>
            <div>Adjacent JSX elements must be wrapped in an enclosing tag</div>
            <div className="col-sm-4 offset-sm-4">
                <form id="contact-form" onSubmit={this.handleSubmit.bind(this)} method="POST">
                    <div className="form-group">
                        <label for="name">Name</label>
                        <input type="text" className="form-control" id="name" />
                    <div className="form-group">
                        <label for="exampleInputEmail1">Email address</label>
                        <input type="email" className="form-control" id="email" aria-describedby="emailHelp" />
                    <div className="form-group">
                        <label for="message">Message</label>
                        <textarea className="form-control" rows="5" id="message"></textarea>
                    <button type="submit" className="btn btn-primary">Submit</button>

How to get the home directory in Python?

I found that pathlib module also supports this.

from pathlib import Path
>>> Path.home()

How to get the file-path of the currently executing javascript code

The accepted answer here does not work if you have inline scripts in your document. To avoid this you can use the following to only target <script> tags with a [src] attribute.

 * Current Script Path
 * Get the dir path to the currently executing script file
 * which is always the last one in the scripts array with
 * an [src] attr
var currentScriptPath = function () {

    var scripts = document.querySelectorAll( 'script[src]' );
    var currentScript = scripts[ scripts.length - 1 ].src;
    var currentScriptChunks = currentScript.split( '/' );
    var currentScriptFile = currentScriptChunks[ currentScriptChunks.length - 1 ];

    return currentScript.replace( currentScriptFile, '' );

This effectively captures the last external .js file, solving some issues I encountered with inline JS templates.

IOS: verify if a point is inside a rect

In Swift that would look like this:

let point = CGPointMake(20,20)
let someFrame = CGRectMake(10,10,100,100)
let isPointInFrame = CGRectContainsPoint(someFrame, point)

Swift 3 version:

let point = CGPointMake(20,20)
let someFrame = CGRectMake(10,10,100,100)
let isPointInFrame = someFrame.contains(point)

Link to documentation . Please remember to check containment if both are in the same coordinate system if not then conversions are required (some example)

How do I merge my local uncommitted changes into another Git branch?

The answers given so far are not ideal because they require a lot of needless work resolving merge conflicts, or they make too many assumptions which are frequently false. This is how to do it perfectly. The link is to my own site.

How to Commit to a Different Branch in git

You have uncommited changes on my_branch that you want to commit to master, without committing all the changes from my_branch.


git merge master
git stash -u
git checkout master
git stash apply
git reset
git add example.js
git commit
git checkout .
git clean -f -d
git checkout my_branch
git merge master
git stash pop


Start by merging master into your branch, since you'll have to do that eventually anyway, and now is the best time to resolve any conflicts.

The -u option (aka --include-untracked) in git stash -u prevents you from losing untracked files when you later do git clean -f -d within master.

After git checkout master it is important that you do NOT git stash pop, because you will need this stash later. If you pop the stash created in my_branch and then do git stash in master, you will cause needless merge conflicts when you later apply that stash in my_branch.

git reset unstages everything resulting from git stash apply. For example, files that have been modified in the stash but do not exist in master get staged as "deleted by us" conflicts.

git checkout . and git clean -f -d discard everything that isn't committed: all changes to tracked files, and all untracked files and directories. They are already saved in the stash and if left in master would cause needless merge conflicts when switching back to my_branch.

The last git stash pop will be based on the original my_branch, and so will not cause any merge conflicts. However, if your stash contains untracked files which you have committed to master, git will complain that it "Could not restore untracked files from stash". To resolve this conflict, delete those files from your working tree, then git stash pop, git add ., and git reset.

How to see what privileges are granted to schema of another user

Login into the database. then run the below query

select * from dba_role_privs where grantee = 'SCHEMA_NAME';

All the role granted to the schema will be listed.

Thanks Szilagyi Donat for the answer. This one is taken from same and just where clause added.

What is the difference between jQuery: text() and html() ?

Well in simple term.

html()-- to get inner html(html tags and text).

text()-- to get only text if present inside(only text)

initialize a const array in a class initializer in C++

How about emulating a const array via an accessor function? It's non-static (as you requested), and it doesn't require stl or any other library:

class a {
    int privateB[2];
    a(int b0,b1) { privateB[0]=b0; privateB[1]=b1; }
    int b(const int idx) { return privateB[idx]; }

Because a::privateB is private, it is effectively constant outside a::, and you can access it similar to an array, e.g.

a aobj(2,3);    // initialize "constant array" b[]
n = aobj.b(1);  // read b[1] (write impossible from here)

If you are willing to use a pair of classes, you could additionally protect privateB from member functions. This could be done by inheriting a; but I think I prefer John Harrison's comp.lang.c++ post using a const class.

Extract values in Pandas value_counts()

#!/usr/bin/env python

import pandas as pd

# Make example dataframe
df = pd.DataFrame([(1, 'Germany'),
                   (2, 'France'),
                   (3, 'Indonesia'),
                   (4, 'France'),
                   (5, 'France'),
                   (6, 'Germany'),
                   (7, 'UK'),
                  columns=['groupid', 'country'],
                  index=['a', 'b', 'c', 'd', 'e', 'f', 'g'])

# What you're looking for
values = df['country'].value_counts().keys().tolist()
counts = df['country'].value_counts().tolist()

Now, print(df['country'].value_counts()) gives:

France       3
Germany      2
UK           1
Indonesia    1

and print(values) gives:

['France', 'Germany', 'UK', 'Indonesia']

and print(counts) gives:

[3, 2, 1, 1]

how to implement a pop up dialog box in iOS

Although I already wrote an overview of different kinds of popups, most people just need an Alert.

How to implement a popup dialog box

enter image description here

class ViewController: UIViewController {

    @IBAction func showAlertButtonTapped(_ sender: UIButton) {

        // create the alert
        let alert = UIAlertController(title: "My Title", message: "This is my message.", preferredStyle: UIAlertController.Style.alert)

        // add an action (button)
        alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))

        // show the alert
        self.present(alert, animated: true, completion: nil)

My fuller answer is here.

How can I count occurrences with groupBy?

List<String> list = new ArrayList<>();


Map<String, List<String>> collect =
                                        .collect(Collectors.groupingBy(o -> o));
       .forEach(e -> System.out.println(e.getKey() + " - " + e.getValue().size()));

How do you create optional arguments in php?

If you don't know how many attributes need to be processed, you can use the variadic argument list token(...) introduced in PHP 5.6 (see full documentation here).


function <functionName> ([<type> ]...<$paramName>) {}

For example:

function someVariadricFunc(...$arguments) {
  foreach ($arguments as $arg) {
    // do some stuff with $arg...

someVariadricFunc();           // an empty array going to be passed
someVariadricFunc('apple');    // provides a one-element array
someVariadricFunc('apple', 'pear', 'orange', 'banana');

As you can see, this token basically turns all parameters to an array, which you can process in any way you like.

Open window in JavaScript with HTML inserted

You can open a new popup window by following code:

var myWindow ="", "newWindow", "width=500,height=700");

Afterwards, you can add HTML using both myWindow.document.write(); or myWindow.document.body.innerHTML = "HTML";

What I will recommend is that first you create a new html file with any name. In this example I am using


And make sure to add all content in that file such as bootstrap cdn or jquery, means all the links and scripts. Then make a div with some id or use your body and give that a id. in this example I have given id="mainBody" to my newFile.html <body> tag

<body id="mainBody">

Then open this file using

var myWindow ="newFile.html", "newWindow", "width=500,height=700");

And add whatever you want to add in your body tag. using following code

 var myWindow ="newFile.html","newWindow","width=500,height=700");  

   myWindow.onload = function(){
     let content = "<button class='btn btn-primary' onclick='window.print();'>Confirm</button>";
   myWindow.document.getElementById('mainBody').innerHTML = content;


it is as simple as that.

ImportError: No Module named simplejson

On Ubuntu/Debian, you can install it with apt-get install python-simplejson

Query to get the names of all tables in SQL Server 2008 Database

another way, will also work on MySQL and PostgreSQL


What is the difference between absolute and relative xpaths? Which is preferred in Selenium automation testing?

Consider Below Html

    <input type ="text" id="username">


so Absoulte path= html/body/input and Relative path = //*[@id="username"]

Disadvantage with Absolute xpath is maintenance is high if there is nay change made in html it may disturb the entire path and also sometime we need to write long absolute xpaths so relative xpaths are preferred

How do you check if a variable is an array in JavaScript?

If you're only dealing with EcmaScript 5 and above then you can use the built in Array.isArray function


Array.isArray([])    // true
Array.isArray("foo") // false
Array.isArray({})    // false

How to implement band-pass Butterworth filter with Scipy.signal.butter

The filter design method in accepted answer is correct, but it has a flaw. SciPy bandpass filters designed with b, a are unstable and may result in erroneous filters at higher filter orders.

Instead, use sos (second-order sections) output of filter design.

from scipy.signal import butter, sosfilt, sosfreqz

def butter_bandpass(lowcut, highcut, fs, order=5):
        nyq = 0.5 * fs
        low = lowcut / nyq
        high = highcut / nyq
        sos = butter(order, [low, high], analog=False, btype='band', output='sos')
        return sos

def butter_bandpass_filter(data, lowcut, highcut, fs, order=5):
        sos = butter_bandpass(lowcut, highcut, fs, order=order)
        y = sosfilt(sos, data)
        return y

Also, you can plot frequency response by changing

b, a = butter_bandpass(lowcut, highcut, fs, order=order)
w, h = freqz(b, a, worN=2000)


sos = butter_bandpass(lowcut, highcut, fs, order=order)
w, h = sosfreqz(sos, worN=2000)

How do I make a fully statically linked .exe with Visual Studio Express 2005?

For the C-runtime go to the project settings, choose C/C++ then 'Code Generation'. Change the 'runtime library' setting to 'multithreaded' instead of 'multithreaded dll'.

If you are using any other libraries you may need to tell the linker to ignore the dynamically linked CRT explicitly.

Why should we typedef a struct so often in C?

From an old article by Dan Saks (

The C language rules for naming structs are a little eccentric, but they're pretty harmless. However, when extended to classes in C++, those same rules open little cracks for bugs to crawl through.

In C, the name s appearing in

struct s

is a tag. A tag name is not a type name. Given the definition above, declarations such as

s x;    /* error in C */
s *p;   /* error in C */

are errors in C. You must write them as

struct s x;     /* OK */
struct s *p;    /* OK */

The names of unions and enumerations are also tags rather than types.

In C, tags are distinct from all other names (for functions, types, variables, and enumeration constants). C compilers maintain tags in a symbol table that's conceptually if not physically separate from the table that holds all other names. Thus, it is possible for a C program to have both a tag and an another name with the same spelling in the same scope. For example,

struct s s;

is a valid declaration which declares variable s of type struct s. It may not be good practice, but C compilers must accept it. I have never seen a rationale for why C was designed this way. I have always thought it was a mistake, but there it is.

Many programmers (including yours truly) prefer to think of struct names as type names, so they define an alias for the tag using a typedef. For example, defining

struct s
typedef struct s S;

lets you use S in place of struct s, as in

S x;
S *p;

A program cannot use S as the name of both a type and a variable (or function or enumeration constant):

S S;    // error

This is good.

The tag name in a struct, union, or enum definition is optional. Many programmers fold the struct definition into the typedef and dispense with the tag altogether, as in:

typedef struct
    } S;

The linked article also has a discussion about how the C++ behavior of not requireing a typedef can cause subtle name hiding problems. To prevent these problems, it's a good idea to typedef your classes and structs in C++, too, even though at first glance it appears to be unnecessary. In C++, with the typedef the name hiding become an error that the compiler tells you about rather than a hidden source of potential problems.

ERROR 2003 (HY000): Can't connect to MySQL server on '' (111)

Try dont shut down iptables and open port 3306.

sudo iptables -A INPUT -i eth0 -p tcp -m tcp --dport 3306 -j ACCEPT

or sudo ufw allow 3306 if you use ufw.

check: netstat -lnp | grep mysql you should get sth like that:

cp        0      0*               LISTEN      2048/mysqld         
tcp6       0      0 :::33060                :::*                    LISTEN      2048/mysqld         
unix  2      [ ACC ]     STREAM     LISTENING     514961   2048/mysqld          /var/run/mysqld/mysqld.sock
unix  2      [ ACC ]     STREAM     LISTENING     514987   2048/mysqld          /var/run/mysqld/mysqlx.sock

if you have null then delete # before port = 3306 in cnf file.

Compiling Java 7 code via Maven

I had the same problem and to solve this I follow this blog article:

$ vim .bash_profile 

export JAVA_HOME=$(/usr/libexec/java_home)

$ source .bash_profile

$ echo $JAVA_HOME

special tks to @mkyong

EDIT: Now I'm using: jEnv + sdkman

Angular2 - Focusing a textbox on component load

I had a slightly different problem. I worked with inputs in a modal and it drove me mad. No of the proposed solutions worked for me.

Until i found this issue:

This good guy gave me the hint that ngx-bootstrap modal has a focus configuration. If this configuration is not set to false, the modal will be focused after the animation and there is NO WAY to focus anything else.


To set this configuration, add the following attribute to the modal div:

[config]="{focus: false}"

Update 2:

To force the focus on the input field i wrote a directive and set the focus in every AfterViewChecked cycle as long as the input field has the class ng-untouched.

 ngAfterViewChecked() {
    // This dirty hack is needed to force focus on an input element of a modal.
    if (this.el.nativeElement.classList.contains('ng-untouched')) {
        this.renderer.invokeElementMethod(this.el.nativeElement, 'focus', []);

set serveroutput on in oracle procedure

To understand the use of "SET SERVEROUTPUT ON" I will take an example

a number(10)  :=10;
dbms_output.put_line(a) ;
dbms_output.put_line('Hello World ! ')  ;

With an output : PL/SQl procedure successfully completed i.e without the expected output

And the main reason behind is that ,whatever we pass inside dbms_output.put_line(' ARGUMENT '/VALUES) i.e. ARGUMENT/VALUES , is internally stored inside a buffer in SGA(Shared Global Area ) memory area upto 2000 bytes .

*NOTE :***However one should note that this buffer is only created when we use **dbms_output package. And we need to set the environment variable only once for a session !!

And in order to fetch it from that buffer we need to set the environment variable for the session . It makes a lot of confusion to the beginners that we are setting the server output on ( because of its nomenclature ) , but unfortunately its nothing like that . Using SET SERVER OUTPUT ON are just telling the PL/SQL engine that

*Hey please print the ARGUMENT/VALUES that I will be passing inside dbms_output.put_line
and in turn PL/SQl run time engine prints the argument on the main console .

I think I am clear to you all . Wish you all the best . To know more about it with the architectural structure of Oracle Server Engine you can see my answer on Quora

And to answer your question "One should use SET SERVER OUTPUT in the beginning of the session. "

How to create a new component in Angular 4 using CLI

ng generate component component_name was not working in my case because instead of using 'app' as project folder name, I renamed it to something else. I again changed it to app. Now, it is working fine

Multiple SQL joins

 B.Title, B.Edition, B.Year, B.Pages, B.Rating     --from Books
, C.Category                                        --from Categories
, P.Publisher                                       --from Publishers
, W.LastName                                        --from Writers

FROM Books B

JOIN Categories_Books CB ON B._ISBN = CB._Books_ISBN
JOIN Categories_Books CB ON CB.__Categories_Category_ID = C._CategoryID
JOIN Publishers P ON B.PublisherID = P._Publisherid
JOIN Writers_Books WB ON B._ISBN = WB._Books_ISBN
JOIN Writers W ON WB._Writers_WriterID = W._WriterID

How to get javax.comm API?


On Debian install librxtx-java by typing:

sudo apt-get install librxtx-java

On Fedora or Enterprise Linux install rxtx by typing:

sudo yum install rxtx

onclick go full screen

I tried other answers on this question, and there are mistakes with the different browser APIs, particularly Fullscreen vs FullScreen. Here is my code that works with the major browsers (as of Q1 2019) and should continue to work as they standardize.

function fullScreenTgl() {
    let doc=document,elm=doc.documentElement;
    if      (elm.requestFullscreen      ) { (!doc.fullscreenElement   ? elm.requestFullscreen()       : doc.exitFullscreen()        ) }
    else if (elm.mozRequestFullScreen   ) { (!doc.mozFullScreen       ? elm.mozRequestFullScreen()    : doc.mozCancelFullScreen()   ) }
    else if (elm.msRequestFullscreen    ) { (!doc.msFullscreenElement ? elm.msRequestFullscreen()     : doc.msExitFullscreen()      ) }
    else if (elm.webkitRequestFullscreen) { (!doc.webkitIsFullscreen  ? elm.webkitRequestFullscreen() : doc.webkitCancelFullscreen()) }
    else                                  { console.log("Fullscreen support not detected.");                                          }

Eclipse projects not showing up after placing project files in workspace/projects

Problem: After creating a PyDev Project, the project does not show up in "PyDev Package Explorer" ;(

Solution: This is what I do to see them all in "Project Explorer":

I am using Eclipse IDE 2019-12

click on "Resource" icon at the top right corner

Now you shall see all projects show up in "Project Explorer".

Tricky note: now if you click on "PyDev" icon, you will see less projects show up in "PyDev Package Explorer" Magic?

Naming returned columns in Pandas aggregate function?

I agree with the OP that it seems more natural and consistent to name and define the output columns in the same place (e.g. as is done with tidyverse's summarize in R), but a work-around in pandas for now is to create the new columns with desired names via assign before doing the aggregation:

).groupby('Country').agg(dict(f=sum, mean=np.mean, std=np.std)).reset_index()

(Using reset_index turns 'Country', 'f', 'mean', and 'std' all into regular columns with a separate integer index.)

Recursively find files with a specific extension

As an alternative to using -regex option on find, since the question is labeled , you can use the brace expansion mechanism:

eval find . -false "-o -name Robert".{jpg,pdf}

What is the best way to access redux store outside a react component?

Export the store from the module you called createStore with. Then you are assured it will both be created and will not pollute the global window space.


const store = createStore(myReducer);
export store;


const store = createStore(myReducer);
export default store;


import {store} from './MyStore'

or if you used default

import store from './MyStore'

For Multiple Store Use Cases

If you need multiple instances of a store, export a factory function. I would recommend making it async (returning a promise).

async function getUserStore (userId) {
   // check if user store exists and return or create it.
export getUserStore

On the client (in an async block)

import {getUserStore} from './store'

const joeStore = await getUserStore('joe')

Python lookup hostname from IP with 1 second timeout

>>> import socket
>>> socket.gethostbyaddr("")
('', [''], [''])

For implementing the timeout on the function, this stackoverflow thread has answers on that.

Java Program to test if a character is uppercase/lowercase/number/vowel

In Java : Character class has static method called isLowerCase(Char ch) ans isUpperCase(Char ch) , Character.isDigit(Char ch)gives you Boolean value, base on that you can easily achieve your task


String abc = "HomePage";

char ch = abc.charAt(i); // here i= 1,2,3......

   // do something :  ch is in lower case

   // do something : ch is in Upper case

  // do something : ch is in Number / Digit

What does the line "#!/bin/sh" mean in a UNIX shell script?

When you try to execute a program in unix (one with the executable bit set), the operating system will look at the first few bytes of the file. These form the so-called "magic number", which can be used to decide the format of the program and how to execute it.

#! corresponds to the magic number 0x2321 (look it up in an ascii table). When the system sees that the magic number, it knows that it is dealing with a text script and reads until the next \n (there is a limit, but it escapes me atm). Having identified the interpreter (the first argument after the shebang) it will call the interpreter.

Other files also have magic numbers. Try looking at a bitmap (.BMP) file via less and you will see the first two characters are BM. This magic number denotes that the file is indeed a bitmap.

How to set session attribute in java?

By Java class, I am assuming you mean a Servlet class as setting session attribute in arbitrary Java class does not make sense.You can do something like this in your servlet's doGet/doPost methods

public void doGet(HttpServletRequest request, HttpServletResponse response) {

    HttpSession session = request.getSession();
    String username = (String)request.getAttribute("un");
    session.setAttribute("UserName", username);

How can I change from SQL Server Windows mode to mixed mode (SQL Server 2008)?

From this:

One can catch that you may change it through windows registry key

(SQLEXPRESS instance):

"Software\Microsoft\Microsoft SQL Server\SQLEXPRESS\LoginMode" = 2

... and restart service

How to use NSJSONSerialization

The following code fetches a JSON object from a webserver, and parses it to an NSDictionary. I have used the openweathermap API that returns a simple JSON response for this example. For keeping it simple, this code uses synchronous requests.

   NSString *urlString   = @",uk"; // The Openweathermap JSON responder
   NSURL *url            = [[NSURL alloc]initWithString:urlString];
   NSURLRequest *request = [NSURLRequest requestWithURL:url];
   NSURLResponse *response;
   NSData *GETReply      = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
   NSDictionary *res     = [NSJSONSerialization JSONObjectWithData:GETReply options:NSJSONReadingMutableLeaves|| NSJSONReadingMutableContainers error:nil];

Compare two files and write it to "match" and "nomatch" files

I had used JCL about 2 years back so cannot write a code for you but here is the idea;

  1. Have 2 steps
  2. First step will have ICETOOl where you can write the matching records to matched file.
  3. Second you can write a file for mismatched by using SORT/ICETOOl or by just file operations.

again i apologize for solution without code, but i am out of touch by 2 yrs+

Check whether a string contains a substring

Case Insensitive Substring Example

This is an extension of Eugene's answer, which converts the strings to lower case before checking for the substring:

if (index(lc($str), lc($substr)) != -1) {
    print "$str contains $substr\n";

Convert stdClass object to array in PHP

The easiest way is to JSON-encode your object and then decode it back to an array:

$array = json_decode(json_encode($object), true);

Or if you prefer, you can traverse the object manually, too:

foreach ($object as $value) 
    $array[] = $value->post_id;

Delete all local git branches

The following script deletes branches. Use it and modify it at your own risk, etc. etc.

Based on the other answers in this question, I ended up writing a quick bash script for myself. I called it "gitbd" (git branch -D) but if you use it, you can rename it to whatever you want.

gitbd() {
if [ $# -le 1 ]
    local branches_to_delete=`git for-each-ref --format '%(refname:short)' refs/heads/ | grep "$1"`
    printf "Matching branches:\n\n$branches_to_delete\n\nDelete? [Y/n] "
    read -n 1 -r # Immediately continue after getting 1 keypress
    echo # Move to a new line
    if [[ ! $REPLY == 'N' && ! $REPLY == 'n' ]]
        echo $branches_to_delete | xargs git branch -D
  echo "This command takes one arg (match pattern) or no args (match all)"

It will offer to delete any branches which match a pattern argument, if passed in, or all local branches when called with with no arguments. It will also give you a confirmation step, since, you know, we're deleting things, so that's nice.

It's kind of dumb - if there are no branches that match the pattern, it doesn't realize it.

An example output run:

$ gitbd test
Matching branches:


Delete? [Y/n] 

Turning off auto indent when pasting text into vim

Update: Better answer here:

To turn off autoindent when you paste code, there's a special "paste" mode.


:set paste

Then paste your code. Note that the text in the tooltip now says -- INSERT (paste) --.

After you pasted your code, turn off the paste-mode, so that auto-indenting when you type works correctly again.

:set nopaste

However, I always found that cumbersome. That's why I map <F3> such that it can switch between paste and nopaste modes while editing the text! I add this to .vimrc

set pastetoggle=<F3>

c# foreach (property in object)... Is there a simple way of doing this?

A small word of caution, if "do some stuff" means updating the value of the actual property that you visit AND if there is a struct type property along the path from root object to the visited property, the change you made on the property will not be reflected on the root object.

CSS/Javascript to force html table row on a single line

I wonder if it might be worth using PHP (or another server-side scripting language) or Javascript to truncate the strings to the right length (although calculating the right length is tricky, unless you use a fixed-width font)?

Could not find a base address that matches scheme https for the endpoint with binding WebHttpBinding. Registered base address schemes are [http]

In the endpoint tag you need to include the property address=""

<endpoint address="" binding="webHttpBinding" bindingConfiguration="SecureBasicRest" behaviorConfiguration="svcEndpoint" name="webHttp" contract="SvcContract.Authenticate" />

Getting Current date, time , day in laravel

use DateTime;

$now = new DateTime();

Why doesn't "System.out.println" work in Android?

I'll leave this for further visitors as for me it was something about the main thread being unable to System.out.println.

public class LogUtil {

private static String log = "";
private static boolean started = false;
public static void print(String s) {
    //Start the thread unless it's already running
    if(!started) {
    //Append a String to the log
    log += s;

public static void println(String s) {
    //Start the thread unless it's already running
    if(!started) {
    //Append a String to the log with a newline.
    //NOTE: Change to print(s + "\n") if you don't want it to trim the last newline.
    log += (s.endsWith("\n") )? s : (s + "\n");

private static void start() {
    //Creates a new Thread responsible for showing the logs.
    Thread thread = new Thread(new Runnable() {
        public void run() {
            while(true) {
                //Execute 100 times per second to save CPU cycles.
                try {
                } catch (InterruptedException e) {
                //If the log variable has any contents...
                if(!log.isEmpty()) {
                    //...print it and clear the log variable for new data.
                    log = "";
    started = true;

Usage: LogUtil.println("This is a string");

How can I loop through enum values for display in radio buttons?

Two options:

for (let item in MotifIntervention) {
    if (isNaN(Number(item))) {


Object.keys(MotifIntervention).filter(key => !isNaN(Number(MotifIntervention[key])));

(code in playground)


String enums look different than regular ones, for example:

enum MyEnum {
    A = "a",
    B = "b",
    C = "c"

Compiles into:

var MyEnum;
(function (MyEnum) {
    MyEnum["A"] = "a";
    MyEnum["B"] = "b";
    MyEnum["C"] = "c";
})(MyEnum || (MyEnum = {}));

Which just gives you this object:

    A: "a",
    B: "b",
    C: "c"

You can get all the keys (["A", "B", "C"]) like this:


And the values (["a", "b", "c"]):

Object.keys(MyEnum).map(key => MyEnum[key])

Or using Object.values():


Sending HTML email using Python

Here is my answer for AWS using boto3

    subject = "Hello"
    html = "<b>Hello Consumer</b>"

    client = boto3.client('ses', region_name='us-east-1', aws_access_key_id="your_key",

    Source='ACME <[email protected]>',
    Destination={'ToAddresses': [email]},
        'Subject': {'Data': subject},
        'Body': {
            'Html': {'Data': html}

Use of "this" keyword in C++

this points to the object in whose member function it is reffered, so it is optional.

How to understand nil vs. empty vs. blank in Ruby

Just a little note about the any? recommendation: He's right that it's generally equivalent to !empty?. However, any? will return true to a string of just whitespace (ala " ").

And of course, see the 1.9 comment above, too.

using awk with column value conditions

This is more readable for me

awk '{if ($2 ~ /findtext/) print $3}' <infile>

Add new row to excel Table (VBA)

Tbl.ListRows.Add doesn't work for me and I believe lot others are facing the same problem. I use the following workaround:

    'First check if the last row is empty; if not, add a row
    If table.ListRows.count > 0 Then
        Set lastRow = table.ListRows(table.ListRows.count).Range
        For col = 1 To lastRow.Columns.count
            If Trim(CStr(lastRow.Cells(1, col).Value)) <> "" Then
                lastRow.Cells(1, col).EntireRow.Insert
                'Cut last row and paste to second last
                lastRow.Cut Destination:=table.ListRows(table.ListRows.count - 1).Range
                Exit For
            End If
        Next col
    End If

    'Populate last row with the form data
    Set lastRow = table.ListRows(table.ListRows.count).Range
    lastRow.PasteSpecial Transpose:=True
    Application.CutCopyMode = False

Hope it helps someone out there.

Node.js EACCES error when listening on most ports

For me, it was just an error in the .env file. I deleted the comma at the end of each line and it was solved.





Format string to a 3 digit number

You can also do : string.Format("{0:D3}, 3);

Django ManyToMany filter()

Note that if the user may be in multiple zones used in the query, you may probably want to add .distinct(). Otherwise you get one user multiple times:

users_in_zones = User.objects.filter(zones__in=[zone1, zone2, zone3]).distinct()

How to make the 'cut' command treat same sequental delimiters as one?

This Perl one-liner shows how closely Perl is related to awk:

perl -lane 'print $F[3]' text.txt

However, the @F autosplit array starts at index $F[0] while awk fields start with $1

REST API Authentication

For e.g. when a user has login.Now lets say the user want to create a forum topic, How will I know that the user is already logged in?

Think about it - there must be some handshake that tells your "Create Forum" API that this current request is from an authenticated user. Since REST APIs are typically stateless, the state must be persisted somewhere. Your client consuming the REST APIs is responsible for maintaining that state. Usually, it is in the form of some token that gets passed around since the time the user was logged in. If the token is good, your request is good.

Check how Amazon AWS does authentications. That's a perfect example of "passing the buck" around from one API to another.

*I thought of adding some practical response to my previous answer. Try Apache Shiro (or any authentication/authorization library). Bottom line, try and avoid custom coding. Once you have integrated your favorite library (I use Apache Shiro, btw) you can then do the following:

  1. Create a Login/logout API like: /api/v1/login and api/v1/logout
  2. In these Login and Logout APIs, perform the authentication with your user store
  3. The outcome is a token (usually, JSESSIONID) that is sent back to the client (web, mobile, whatever)
  4. From this point onwards, all subsequent calls made by your client will include this token
  5. Let's say your next call is made to an API called /api/v1/findUser
  6. The first thing this API code will do is to check for the token ("is this user authenticated?")
  7. If the answer comes back as NO, then you throw a HTTP 401 Status back at the client. Let them handle it.
  8. If the answer is YES, then proceed to return the requested User

That's all. Hope this helps.

Escape text for HTML

.NET 4.0 and above:

using System.Web.Security.AntiXss;
var encoded = AntiXssEncoder.HtmlEncode("input", useNamedEntities: true);

How to select the row with the maximum value in each group

Another base solution

group_sorted <- group[order(group$Subject, -group$pt),]

# Subject pt Event
#       1  5     2
#       2 17     2
#       3  5     2

Order the data frame by pt (descending) and then remove rows duplicated in Subject

How to reload current page in ReactJS?

You can use window.location.reload(); in your componentDidMount() lifecycle method. If you are using react-router, it has a refresh method to do that.

Edit: If you want to do that after a data update, you might be looking to a re-render not a reload and you can do that by using this.setState(). Here is a basic example of it to fire a re-render after data is fetched.

import React from 'react'

const ROOT_URL = '';
const url = `${ROOT_URL}/users`;

class MyComponent extends React.Component {
    state = {
        users: null
    componentDidMount() {
            .then(response => response.json())
            .then(users => this.setState({users: users}));
    render() {
        const {users} = this.state;
        if (users) {
            return (
                    { => <li>{}</li>)}
        } else {
            return (<h1>Loading ...</h1>)

export default MyComponent;

How to change the style of alert box?

I tried to use script for alert() boxes styles using java-script.Here i used those JS and CSS.

Refer this coding JS functionality.

var ALERT_TITLE = "Oops!";

if(document.getElementById) {
    window.alert = function(txt) {

function createCustomAlert(txt) {
    d = document;

    if(d.getElementById("modalContainer")) return;

    mObj = d.getElementsByTagName("body")[0].appendChild(d.createElement("div")); = "modalContainer"; = d.documentElement.scrollHeight + "px";

    alertObj = mObj.appendChild(d.createElement("div")); = "alertBox";
    if(d.all && !window.opera) = document.documentElement.scrollTop + "px"; = (d.documentElement.scrollWidth - alertObj.offsetWidth)/2 + "px";"visible";

    h1 = alertObj.appendChild(d.createElement("h1"));

    msg = alertObj.appendChild(d.createElement("p"));
    msg.innerHTML = txt;

    btn = alertObj.appendChild(d.createElement("a")); = "closeBtn";
    btn.href = "#";
    btn.onclick = function() { removeCustomAlert();return false; } = "block";


function removeCustomAlert() {

And CSS for alert() Box

#modalContainer {
    background-color:rgba(0, 0, 0, 0.3);
    background-image:url(tp.png); /* required by MSIE to prevent actions on lower z-index elements */

#alertBox {
    border:1px solid #666;
    background-position:20px 30px;

#modalContainer > #alertBox {

#alertBox h1 {
    font:bold 0.9em verdana,arial;
    border-bottom:1px solid #000;
    padding:2px 0 2px 5px;

#alertBox p {
    font:0.7em verdana,arial;

#alertBox #closeBtn {
    margin:5px auto;
    border:0 none;
    font:0.7em verdana,arial;
    border-radius: 3px;

/* unrelated styles */

#mContainer {
    border-top:2px solid #000;
    border-bottom:2px solid #000;
    font:0.7em verdana,arial;

h1,h2 {
    font:bold 1.5em verdana;
    border-bottom:1px solid #000;

code {

#credits {
    margin:25px auto 0px auto;
    font:0.7em verdana;
    border-top:1px solid #000;
    border-bottom:1px solid #000;

#credits img {
    margin:5px 10px 5px 0px;
    border:1px solid #000000;

.important {

code span {

And HTML file:

<input type="button" value = "Test the alert" onclick="alert('Alert this pages');" />


enter image description here

Using a batch to copy from network drive to C: or D: drive

You are copying all files to a single file called TEST_BACKUP_FOLDER

try this:

copy "\\My_Servers_IP\Shared Drive\FolderName\*" TEST_BACKUP_FOLDER

difference between new String[]{} and new String[] in java


  • An array variable has to be typed T[]
    (note that T can be an arry type itself -> multidimensional arrays)
  • The length of the array must be determined either by:
    • giving it an explicit size
      (can be int constant or int expression, see n below)
    • initializing all the values inside the array
      (length is implicitly calculated from given elements)
  • Any variable that is typed T[] has one read-only field: length and an index operator [int] for reading/writing data at certain indices.


1. String[] array= new String[]{}; what is the use of { } here ?

It initializes the array with the values between { }. In this case 0 elements, so array.length == 0 and array[0] throws IndexOutOfBoundsException: 0.

2. what is the diff between String array=new String[]; and String array=new String[]{};

The first won't compile for two reasons while the second won't compile for one reason. The common reason is that the type of the variable array has to be an array type: String[] not just String. Ignoring that (probably just a typo) the difference is:

new String[]   // size not known, compile error
new String[]{} // size is known, it has 0 elements, listed inside {}
new String[0]  // size is known, it has 0 elements, explicitly sized

3. when am writing String array=new String[10]{}; got error why ?

(Again, ignoring the missing [] before array) In this case you're over-eager to tell Java what to do and you're giving conflicting data. First you tell Java that you want 10 elements for the array to hold and then you're saying you want the array to be empty via {}. Just make up your mind and use one of those - Java thinks.

help me i am confused


String[] noStrings = new String[0];
String[] noStrings = new String[] { };
String[] oneString = new String[] { "atIndex0" };
String[] oneString = new String[1];
String[] oneString = new String[] { null }; // same as previous
String[] threeStrings = new String[] { "atIndex0", "atIndex1", "atIndex2" };
String[] threeStrings = new String[] { "atIndex0", null, "atIndex2" }; // you can skip an index
String[] threeStrings = new String[3];
String[] threeStrings = new String[] { null, null, null }; // same as previous
int[] twoNumbers = new int[2];
int[] twoNumbers = new int[] { 0, 0 }; // same as above
int[] twoNumbers = new int[] { 1, 2 }; // twoNumbers.length == 2 && twoNumbers[0] == 1 && twoNumbers[1] == 2
int n = 2;
int[] nNumbers = new int[n]; // same as [2] and { 0, 0 }
int[] nNumbers = new int[2*n]; // same as new int[4] if n == 2

(Here, "same as" means it will construct the same array.)

Java String to Date object of the format "yyyy-mm-dd HH:mm:ss"

java.util.Date temp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS").parse("2012-07-10 14:58:00.000000");

The mm is minutes you want MM


public class Test {

    public static void main(String[] args) throws ParseException {
        java.util.Date temp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS")
                .parse("2012-07-10 14:58:00.000000");


Tue Jul 10 14:58:00 EDT 2012

C++: variable 'std::ifstream ifs' has initializer but incomplete type

This seems to be answered - #include <fstream>.

The message means :-

incomplete type - the class has not been defined with a full class. The compiler has seen statements such as class ifstream; which allow it to understand that a class exists, but does not know how much memory the class takes up.

The forward declaration allows the compiler to make more sense of :-

void BindInput( ifstream & inputChannel ); 

It understands the class exists, and can send pointers and references through code without being able to create the class, see any data within the class, or call any methods of the class.

The has initializer seems a bit extraneous, but is saying that the incomplete object is being created.

Convert hex to binary

The binary version of ABC123EFFF is actually 1010101111000001001000111110111111111111

For almost all applications you want the binary version to have a length that is a multiple of 4 with leading padding of 0s.

To get this in Python:

def hex_to_binary( hex_code ):
  bin_code = bin( hex_code )[2:]
  padding = (4-len(bin_code)%4)%4
  return '0'*padding + bin_code

Example 1:

>>> hex_to_binary( 0xABC123EFFF )

Example 2:

>>> hex_to_binary( 0x7123 )

Note that this also works in Micropython :)

What are good ways to prevent SQL injection?

My answer is quite easy:

Use Entity Framework for communication between C# and your SQL database. That will make parameterized SQL strings that isn't vulnerable to SQL injection.

As a bonus, it's very easy to work with as well.

CSS/HTML: What is the correct way to make text italic?

You should use different methods for different use cases:

  1. If you want to emphasise a phrase, use <em>.
  2. The <i> tag has a new meaning in HTML5, representing "a span of text in an alternate voice or mood". So you should use this tag for things like thoughts/asides or idiomatic phrases. The spec also suggests ship names (but no longer suggests book/song/movie names; use <cite> for that instead).
  3. If the italicised text is part of a larger context, say an introductory paragraph, you should attach the CSS style to the larger element, i.e. p.intro { font-style: italic; }

git checkout all the files

Other way which I found useful is:

git checkout <wildcard> 


git checkout *.html

More generally:

git checkout <branch> <filename/wildcard>

What is the difference between public, private, and protected?

Considering 'when':
I tend to declare everything as private initially, if I'm not exactly sure. Reason being, that it's usually much easier to turn a private method public than the other way round. That's because you can at least be sure that the private method hasn't been used anywhere but in the class itself. A public method may already be in use everywhere, possibly requiring an extensive re-write.

Update: i go for a default of protected nowadays, because I've come to find that it's good enough for encapsulation and doesn't get in the way when I'm extending classes (which i try to avoid anyway). Only if i have a good reason to use the other two, i will.

A good reason for a private method would be one that implements something inherent to that object that even an extending class should not change (factual reason, in addition to encapsulation, like internal state management). Eventually, it's still easy enough to track down where a protected method is being used usually, so i default to protected nowadays. Maybe not 100% objective "in the trenches" experience, I admit.

Append String in Swift


let extendedURLString = urlString.stringByAppendingString("&requireslogin=true")


From Documentation: "You can append a Character value to a String variable with the String type’s append() method:" so we cannot use append for Strings.

urlString += "&requireslogin=true"

"+" Operator works in both versions

let extendedURLString = urlString+"&requireslogin=true"

Putting text in top left corner of matplotlib plot

import matplotlib.pyplot as plt

plt.figure(figsize=(6, 6))
plt.text(0.1, 0.9, 'text', size=15, color='purple')

# or 

fig, axe = plt.subplots(figsize=(6, 6))
axe.text(0.1, 0.9, 'text', size=15, color='purple')

Output of Both

enter image description here

import matplotlib.pyplot as plt

# Build a rectangle in axes coords
left, width = .25, .5
bottom, height = .25, .5
right = left + width
top = bottom + height
ax = plt.gca()
p = plt.Rectangle((left, bottom), width, height, fill=False)

ax.text(left, bottom, 'left top',

ax.text(left, bottom, 'left bottom',

ax.text(right, top, 'right bottom',

ax.text(right, top, 'right top',

ax.text(right, bottom, 'center top',

ax.text(left, 0.5 * (bottom + top), 'right center',

ax.text(left, 0.5 * (bottom + top), 'left center',

ax.text(0.5 * (left + right), 0.5 * (bottom + top), 'middle',

ax.text(right, 0.5 * (bottom + top), 'centered',

ax.text(left, top, 'rotated\nwith newlines',


enter image description here

What is external linkage and internal linkage?


  • extern linkage variable is visible in all files
  • internal linkage variable is visible in single file.

Explain: const variables internally link by default unless otherwise declared as extern

  1. by default, global variable is external linkage
  2. but, const global variable is internal linkage
  3. extra, extern const global variable is external linkage

A pretty good material about linkage in C++

How to make a Qt Widget grow with the window size?

I found it was impossible to assign a layout to the centralwidget until I had added at least one child beneath it. Then I could highlight the tiny icon with the red 'disabled' mark and then click on a layout in the Designer toolbar at top.

Difference between a script and a program?

For me, the main difference is that a script is interpreted, while a program is executed (i.e. the source is first compiled, and the result of that compilation is expected).

Wikipedia seems to agree with me on this :

Script :

"Scripts" are distinct from the core code of the application, which is usually written in a different language, and are often created or at least modified by the end-user.
Scripts are often interpreted from source code or bytecode, whereas the applications they control are traditionally compiled to native machine code.

Program :

The program has an executable form that the computer can use directly to execute the instructions.
The same program in its human-readable source code form, from which executable programs are derived (e.g., compiled)

How to loop through a directory recursively to delete files with certain extensions

For bash (since version 4.0):

shopt -s globstar nullglob dotglob
echo **/*".ext"

That's all.
The trailing extension ".ext" there to select files (or dirs) with that extension.

Option globstar activates the ** (search recursivelly).
Option nullglob removes an * when it matches no file/dir.
Option dotglob includes files that start wit a dot (hidden files).

Beware that before bash 4.3, **/ also traverses symbolic links to directories which is not desirable.

Post a json object to mvc controller with jquery and ajax

I see in your code that you are trying to pass an ARRAY to POST action. In that case follow below working code -

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
    function submitForm() {
        var roles = ["role1", "role2", "role3"];

            type: "POST",
            url: "@Url.Action("AddUser")",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(roles),
            success: function (data) { alert(data); },
            failure: function (errMsg) {

<input type="button" value="Click" onclick="submitForm()"/>

And the controller action is going to be -

    public ActionResult AddUser(List<String> Roles)
        return null;

Then when you click on the button -

enter image description here

Combination of async function + await + setTimeout

await setTimeout(()=>{}, 200);

Will work if your Node version is 15 and above.

Node.js Error: Cannot find module express

I'm not proud sharing this, but in my case I had:


 //and the correct form is:
 require('express-handlebars'); //Use dash instead.

Warning: mysqli_real_escape_string() expects exactly 2 parameters, 1 given... what I do wrong?

pass $connect as your first parameter in mysqli_real_escape_string for this first make connection then do here

How to make several plots on a single page using matplotlib?

@doug & FS.'s answer are very good solutions. I want to share the solution for iteration on pandas.dataframe.

import pandas as pd
df=pd.DataFrame([[1, 2], [3, 4], [4, 3], [2, 3]])
fig = plt.figure(figsize=(14,8))
for i in df.columns:

Why does intellisense and code suggestion stop working when Visual Studio is open?

I had this problem when some of the dependent assemblies are changed but locked by an other instance of visual studio (2015).

PowerShell Connect to FTP server and get files

Remote pick directory path should be the exact path on the ftp server you are tryng to access.. here is the script to download files from the server.. you can add or modify with SSLMode..

#ftp server 
$ftp = "" 
$user = "XX" 
$pass = "XXX"
$SetType = "bin"  
$remotePickupDir = Get-ChildItem 'c:\test' -recurse
$webclient = New-Object System.Net.WebClient 

$webclient.Credentials = New-Object System.Net.NetworkCredential($user,$pass)  
foreach($item in $remotePickupDir){ 
    $uri = New-Object System.Uri($ftp+$item.Name) 

Maven compile: package does not exist

You do not include a <scope> tag in your dependency. If you add it, your dependency becomes something like:

     <scope> ... </scope>

The "scope" tag tells maven at which stage of the build your dependency is needed. Examples for the values to put inside are "test", "provided" or "runtime" (omit the quotes in your pom). I do not know your dependency so I cannot tell you what value to choose. Please consult the Maven documentation and the documentation of your dependency.

How to set Toolbar text and back arrow color

If using the latest iteration of Android Studio 3.0 and generating your Activity classes, in your styles files change this:

<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />

To this:

<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.ActionBar" />

git pull from master into the development branch

Situation: Working in my local branch, but I love to keep-up updates in the development branch named dev.

Solution: Usually, I prefer to do :

git fetch
git rebase origin/dev

How do you join on the same table, twice, in mysql?

you'd use another join, something along these lines:

SELECT toD.dom_url AS ToURL, 
    fromD.dom_url AS FromUrl, 

FROM reviews AS rvw

LEFT JOIN domain AS toD 
    ON toD.Dom_ID = rvw.rev_dom_for

LEFT JOIN domain AS fromD 
    ON fromD.Dom_ID = rvw.rev_dom_from


All you're doing is joining in the table multiple times. Look at the query in the post: it selects the values from the Reviews tables (aliased as rvw), that table provides you 2 references to the Domain table (a FOR and a FROM).

At this point it's a simple matter to left join the Domain table to the Reviews table. Once (aliased as toD) for the FOR, and a second time (aliased as fromD) for the FROM.

Then in the SELECT list, you will select the DOM_URL fields from both LEFT JOINS of the DOMAIN table, referencing them by the table alias for each joined in reference to the Domains table, and alias them as the ToURL and FromUrl.

For more info about aliasing in SQL, read here.

Search for one value in any column of any table inside a database

After trying @regeter's solution and seeing it didn't solve my problem when I was searching for a foreign/primary key to see all tables/columns where it exists, it didn't work. After reading how it failed for another who tried to use a unique identifier, I have made the modifications and here is the updated result: (works with both int, and guids... you will see how to easily extend)

CREATE PROC [dbo].[SearchAllTables_Like]
        @SearchStr nvarchar(100)

-- Copyright © 2002 Narayana Vyas Kondreddi. All rights reserved.
-- Purpose: To search all columns of all tables for a given search string
-- Written by: Narayana Vyas Kondreddi
-- Site:
-- Tested on: SQL Server 7.0 and SQL Server 2000
-- Date modified: 28th July 2002 22:50 GMT

CREATE TABLE #Results (ColumnName nvarchar(370), ColumnValue nvarchar(3630))


DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
SET  @TableName = ''
SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')

    SET @ColumnName = ''
    SET @TableName = 
                        QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
                         ), 'IsMSShipped'
                           ) = 0

    WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)

        SET @ColumnName =
            WHERE       TABLE_SCHEMA    = PARSENAME(@TableName, 2)
                AND TABLE_NAME  = PARSENAME(@TableName, 1)
                AND DATA_TYPE IN ('guid', 'int', 'char', 'varchar', 'nchar', 'nvarchar')
                AND QUOTENAME(COLUMN_NAME) > @ColumnName

        IF @ColumnName IS NOT NULL
            INSERT INTO #Results
                'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630) 
                FROM ' + @TableName + ' (NOLOCK) ' +
                ' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2

SELECT ColumnName, ColumnValue FROM #Results

ERROR 1452: Cannot add or update a child row: a foreign key constraint fails

The problem occurs because you set the foreign key in child table after you insert some data in the child table.

Try removing all the data from child table, then set the foreign key and afterwards add/insert the data in table, it will work.

GIT commit as different user without email / or only email

The --author option doesn't work:

*** Please tell me who you are.


  git config --global "[email protected]"
  git config --global "Your Name"

This does:

git -c'A U Thor' -c [email protected] commit

How to clone object in C++ ? Or Is there another solution?

In C++ copying the object means cloning. There is no any special cloning in the language.

As the standard suggests, after copying you should have 2 identical copies of the same object.

There are 2 types of copying: copy constructor when you create object on a non initialized space and copy operator where you need to release the old state of the object (that is expected to be valid) before setting the new state.

How does one convert a HashMap to a List in Java?

Collection Interface has 3 views

  • keySet
  • values
  • entrySet

Other have answered to to convert Hashmap into two lists of key and value. Its perfectly correct

My addition: How to convert "key-value pair" (aka entrySet)into list.

      Map m=new HashMap();
          m.put(3, "dev2");
          m.put(4, "dev3");

      List<Entry> entryList = new ArrayList<Entry>(m.entrySet());

      for (Entry s : entryList) {

ArrayList has this constructor.

getApplication() vs. getApplicationContext()

It seems to have to do with context wrapping. Most classes derived from Context are actually a ContextWrapper, which essentially delegates to another context, possibly with changes by the wrapper.

The context is a general abstraction that supports mocking and proxying. Since many contexts are bound to a limited-lifetime object such as an Activity, there needs to be a way to get a longer-lived context, for purposes such as registering for future notifications. That is achieved by Context.getApplicationContext(). A logical implementation is to return the global Application object, but nothing prevents a context implementation from returning a wrapper or proxy with a suitable lifetime instead.

Activities and services are more specifically associated with an Application object. The usefulness of this, I believe, is that you can create and register in the manifest a custom class derived from Application and be certain that Activity.getApplication() or Service.getApplication() will return that specific object of that specific type, which you can cast to your derived Application class and use for whatever custom purpose.

In other words, getApplication() is guaranteed to return an Application object, while getApplicationContext() is free to return a proxy instead.

Input type DateTime - Value format?

That one shows up correctly as HTML5-Tag for those looking for this:

<input type="datetime" name="somedatafield" value="2011-12-21T11:33:23Z" />

CSS media query to target only iOS devices

I don't know about targeting iOS as a whole, but to target iOS Safari specifically:

@supports (-webkit-touch-callout: none) {
   /* CSS specific to iOS devices */ 

@supports not (-webkit-touch-callout: none) {
   /* CSS for other than iOS devices */ 

Apparently as of iOS 13 -webkit-overflow-scrolling no longer responds to @supports, but -webkit-touch-callout still does. Of course that could change in the future...

Android Studio Google JAR file causing GC overhead limit exceeded error

I tried all the solutions mentioned above, but I was still facing the issue. Finally I stumbled upon the following which resolved the issue.

(On MacOS) Went to Preferences -> Memory Settings -> Find existing grade demon(s) -> Stopped all of them.

How to store values from foreach loop into an array?

Just to save you too much typos:

foreach($group_membership as $username){
        $username->items = array(additional array to add);

how to change onclick event with jquery?

$('#id').attr('onclick', 'function()');

Right now (11 Jul 2015) this solution is still working (jquery 2.1.4); in my opinion, it is the best one to pick up.

How do you change the text in the Titlebar in Windows Forms?

public partial class Form1 : Form
    DateTime date = new DateTime();
    public Form1()
    private void timer1_Tick(object sender, EventArgs e)
        date = DateTime.Now;
        this.Text = "Date: "+date;

I was having some problems with inserting date and time into the name of the form. Finally found the error. I'm posting this in case anyone has the same problem and doesn't have to spend years googling solutions.

How can I debug my JavaScript code?

I'm using Venkman, a JavaScript debugger for XUL applications.

Concatenate two char* strings in a C program

When you use string literals, such as "this is a string" and in your case "sssss" and "kkkk", the compiler puts them in read-only memory. However, strcat attempts to write the second argument after the first. You can solve this problem by making a sufficiently sized destination buffer and write to that.

char destination[10]; // 5 times s, 4 times k, one zero-terminator
char* str1;
char* str2;
str1 = "sssss";
str2 = "kkkk";
strcpy(destination, str1);

Note that in recent compilers, you usually get a warning for casting string literals to non-const character pointers.

ASP.NET MVC View Engine Comparison

My current choice is Razor. It is very clean and easy to read and keeps the view pages very easy to maintain. There is also intellisense support which is really great. ALos, when used with web helpers it is really powerful too.

To provide a simple sample:

@Model namespace.model
<!Doctype html>
<title>Test Razor</title>
<ul class="mainList">
@foreach(var x in ViewData.model)

And there you have it. That is very clean and easy to read. Granted, that's a simple example but even on complex pages and forms it is still very easy to read and understand.

As for the cons? Well so far (I'm new to this) when using some of the helpers for forms there is a lack of support for adding a CSS class reference which is a little annoying.

Thanks Nathj07

How to open a web server port on EC2 instance

You need to configure the security group as stated by cyraxjoe. Along with that you also need to open System port. Steps to open port in windows :-

  1. On the Start menu, click Run, type WF.msc, and then click OK.
  2. In the Windows Firewall with Advanced Security, in the left pane, right-click Inbound Rules, and then click New Rule in the action pane.
  3. In the Rule Type dialog box, select Port, and then click Next.
  4. In the Protocol and Ports dialog box, select TCP. Select Specific local ports, and then type the port number , such as 8787 for the default instance. Click Next.
  5. In the Action dialog box, select Allow the connection, and then click Next.
  6. In the Profile dialog box, select any profiles that describe the computer connection environment when you want to connect , and then click Next.
  7. In the Name dialog box, type a name and description for this rule, and then click Finish.

Ref:- Microsoft Docs for port Opening

Git/GitHub can't push to master

There is a simple solution to this for someone new to this:

Edit the configuration file in your local .git directory (config). Change git: to https: below.

[remote "origin"]
    url =

How to center an unordered list?

From your post, I understand that you cannot set the width to your li.

How about this?

ul {
  border:2px solid red;

li {
  padding:0 30%; /* try adjusting the side % to give a feel of center aligned.*/

Here's a demo.

How can I insert a line break into a <Text> component in React Native?

do this:


 { "Hi~ \n this is a test message." }


C# LINQ select from list

Execute the GetEventIdsByEventDate() method and save the results in a variable, and then you can use the .Contains() method

Change color inside strings.xml

You don't. strings.xml is just here to define the raw text messages. You should (must) use styles.xml to define reusable visual styles to apply to your widgets.

Think of it as a good practice to separate the concerns. You can work on the visual styles independently from the text messages.

Modify table: How to change 'Allow Nulls' attribute from not null to allow null

Yes you can use ALTER TABLE as follows:

ALTER TABLE [table name] ALTER COLUMN [column name] [data type] NULL

Quoting from the ALTER TABLE documentation:

NULL can be specified in ALTER COLUMN to force a NOT NULL column to allow null values, except for columns in PRIMARY KEY constraints.

How to get the first word in the string

You shoud do something like :

print line.split()[0]

How to remove unused imports from Eclipse

I just found the way. Right click on the desired package then Source -> Organize Imports.

Shortcut keys:

  • Windows: Ctrl + Shift + O
  • Mac: Cmd + Shift + O

How can I convert a string to a float in mysql?

This will convert to a numeric value without the need to cast or specify length or digits:


If your column is an INT, can leave off the .0 to avoid decimals:


What's a good IDE for Python on Mac OS X?

If you have a budget for your IDE, you should give Wingware Professional a try, see .

iterating through Enumeration of hastable keys throws NoSuchElementException error

You're calling nextElement twice in the loop. You should call it only once, else it moves ahead twice:

    String s = e.nextElement();

JQuery get data from JSON array

try this

$.getJSON(url, function(data){
    $.each(, function (index, value) {

Windows 7: unable to register DLL - Error Code:0X80004005

Use following command should work on windows 7. don't forget to enclose the dll name with full path in double quotations.

C:\Windows\SysWOW64>regsvr32 "c:\" 

How to comment a block in Eclipse?

For single line comment you can use Ctrl+/ and for multiple line comment you can use Ctrl + Shift + / after selecting the lines you want to comment in java editor.

On Mac/OS X you can use ? + / to comment out single lines or selected blocks.

How can I change IIS Express port for a site

Edit .sln file using an editor like notepad.

Replace All Ports With New Port.

How to solve COM Exception Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))?

Also note that the class context when initializing can create that exception. If you have an object which is coded as INPROC_SERVER but you try to CoCreateInstance as CLSCTX_LOCAL_SERVER, you will also get that error.

You need to ensure the object is registered and the CoCreateInstance is creating an instance with the correct class context.

Using Exit button to close a winform program

You can also do like this:

private void button2_Click(object sender, EventArgs e)

Oracle timestamp data type

The number in parentheses specifies the precision of fractional seconds to be stored. So, (0) would mean don't store any fraction of a second, and use only whole seconds. The default value if unspecified is 6 digits after the decimal separator.

So an unspecified value would store a date like:


And specifying (0) stores only:

TIMESTAMP(0) 24-JAN-2012 08.00.05 AM

See Oracle documentation on data types.

How can I generate a random number in a certain range?

To extend what Rahul Gupta said:

You can use Java function int random = Random.nextInt(n).
This returns a random int in the range [0, n-1].

I.e., to get the range [20, 80] use:

final int random = new Random().nextInt(61) + 20; // [0, 60] + 20 => [20, 80]

To generalize more:

final int min = 20;
final int max = 80;
final int random = new Random().nextInt((max - min) + 1) + min;

Google Maps shows "For development purposes only"

For me, Error has been fixed when activated Billing in google console. (I got 1-year developer trial)

Unable to Cast from Parent Class to Child Class

I have seen most of the people saying explicit parent to child casting is not possible, that actually is not true. Let's take a revised start and try proving it by examples.

As we know in .net all castings have two broad categories.

  1. For Value type
  2. For Reference type (in your case its reference type)

Reference type has further three main situational cases in which any scenario can lie.

Child to Parent (Implicit casting - Always successful)

Case 1. Child to any direct or indirect parent

Employee e = new Employee();
Person p = (Person)e; //Allowed

Parent to Child (Explicit casting - Can be successful)

Case 2. Parent variable holding parent object (Not allowed)

Person p = new Person();  // p is true Person object
Employee e = (Employee)p; //Runtime err : InvalidCastException <-------- Yours issue

Case 3. Parent variable holding child object (Always Successful)

Note: Because objects has polymorphic nature, it is possible for a variable of a parent class type to hold a child type.

Person p = new Employee(); // p actually is Employee
Employee e = (Employee)p; // Casting allowed

Conclusion : After reading above all, hope it will make sense now like how parent to child conversion is possible(Case 3).

Answer To The Question :

Your answer is in case 2.Where you can see such casting is not allowed by OOP and you are trying to violate one of OOP's basic rule.So always choose safe path.

Further more, to avoid such exceptional situations .net has recommended using is/as operators those will help you to take informed decisions and provide safe casting.

How to check if a string "StartsWith" another string?

You can use ECMAScript 6's String.prototype.startsWith() method, but it's not yet supported in all browsers. You'll want to use a shim/polyfill to add it on browsers that don't support it. Creating an implementation that complies with all the details laid out in the spec is a little complicated. If you want a faithful shim, use either:

Once you've shimmed the method (or if you're only supporting browsers and JavaScript engines that already have it), you can use it like this:

   console.log("Hello World!".startsWith("He")); // true
var haystack = "Hello world";
var prefix = 'orl';
console.log(haystack.startsWith(prefix)); // false

Speed tradeoff of Java's -Xms and -Xmx options

The -Xmx argument defines the max memory size that the heap can reach for the JVM. You must know your program well and see how it performs under load and set this parameter accordingly. A low value can cause OutOfMemoryExceptions or a very poor performance if your program's heap memory is reaching the maximum heap size. If your program is running in dedicated server you can set this parameter higher because it wont affect other programs.

The -Xms argument sets the initial heap memory size for the JVM. This means that when you start your program the JVM will allocate this amount of memory instantly. This is useful if your program will consume a large amount of heap memory right from the start. This avoids the JVM to be constantly increasing the heap and can gain some performance there. If you don't know if this parameter is going to help you, don't use it.

In summary, this is a compromise that you have to decide based only in the memory behavior of your program.

Best way to do a PHP switch with multiple values per case?

For the sake of completeness, I'll point out that the broken "Version 2" logic can be replaced with a switch statement that works, and also make use of arrays for both speed and clarity, like so:

// used for $current_home = 'current';
$home_group = array(
    'home'  => True,

// used for $current_users = 'current';
$user_group = array(
    ''      => True,
    'users.location'    => True,
    'users.featured'    => True,
    ''         => True,
    'users.browse'      => True,
    ''      => True,
    'users.staff'       => True,

// used for $current_forum = 'current';
$forum_group = array(
    'forum'     => True,

switch (true) {
    case isset($home_group[$p]):
        $current_home = 'current';
    case isset($user_group[$p]):
        $current_users = 'current';
    case isset($forum_group[$p]):
        $current_forum = 'current';
        user_error("\$p is invalid", E_USER_ERROR);

mysql query result into php array

I think you wanted to do this:

while( $row = mysql_fetch_assoc( $result)){
    $new_array[] = $row; // Inside while loop

Or maybe store id as key too

 $new_array[ $row['id']] = $row;

Using the second ways you would be able to address rows directly by their id, such as: $new_array[ 5].

Adjust UILabel height depending on the text

Updates according iOS7

// If description are available for protocol
protocolDescriptionLabel.text = [dataDictionary objectForKey:@"description"];
[protocolDescriptionLabel sizeToFit];
[protocolDescriptionLabel setLineBreakMode:NSLineBreakByWordWrapping];

CGSize expectedLabelSize = [protocolDescriptionLabel
NSLog(@"expectedLabelSize %f", expectedLabelSize.height);

//adjust the label the the new height.
CGRect newFrame = protocolDescriptionLabel.frame;
newFrame.size.height = expectedLabelSize.height;
protocolDescriptionLabel.frame = newFrame;

" app-release.apk" how to change this default generated apk name

Yes we can change that but with some more attention


Now add this in your build.gradle in your project while make sure you have checked the build variant of your project like release or Debug so here I have set my build variant as release but you may select as Debug as well.

    buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), ''
                signingConfig getSigningConfig()
                applicationVariants.all { variant ->
                    variant.outputs.each { output ->
                        def date = new Date();
                        def formattedDate = date.format('yyyyMMddHHmmss')
                        output.outputFile = new File(output.outputFile.parent,
                      "-release", "-" + formattedDate)
    //for Debug use output.outputFile = new File(output.outputFile.parent,
   //                   "-debug", "-" + formattedDate)

You may Do it With different Approach Like this

 defaultConfig {
        applicationId "com.myapp.status"
        minSdkVersion 16
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
        setProperty("archivesBaseName", "COMU-$versionName")

Using Set property method in build.gradle and Don't forget to sync the gradle before running the projects Hope It will solve your problem :)

A New approach to handle this added recently by google update You may now rename your build according to flavor or Variant output //Below source is from developer android documentation For more details follow the above documentation link
Using the Variant API to manipulate variant outputs is broken with the new plugin. It still works for simple tasks, such as changing the APK name during build time, as shown below:

// If you use each() to iterate through the variant objects,
// you need to start using all(). That's because each() iterates
// through only the objects that already exist during configuration time—
// but those object don't exist at configuration time with the new model.
// However, all() adapts to the new model by picking up object as they are
// added during execution.
android.applicationVariants.all { variant ->
    variant.outputs.all {
        outputFileName = "${}-${variant.versionName}.apk"

Renaming .aab bundle This is nicely answered by David Medenjak

tasks.whenTaskAdded { task ->
    if ("bundle")) {
        def renameTaskName = "rename${}Aab"
        def flavor ="bundle".length()).uncapitalize()
        tasks.create(renameTaskName, Copy) {
            def path = "${buildDir}/outputs/bundle/${flavor}/"
            include "app.aab"
            destinationDir file("${buildDir}/outputs/renamedBundle/")
            rename "app.aab", "${flavor}.aab"

//@credit to David Medenjak for this block of code

Is there need of above code

What I have observed in the latest version of the android studio 3.3.1

The rename of .aab bundle is done by the previous code there don't require any task rename at all.

Hope it will help you guys. :)

ORA-12528: TNS Listener: all appropriate instances are blocking new connections. Instance "CLRExtProc", status UNKNOWN

You have to know if the problem come from the listener or from the database.

  • So first, restart the listener, it could solve the problem.

  • Second, it could come from the db if it's not in open mode (nomount, mount, restrict). To check it, connect locally and do the following query:

    sqlplus /nolog

    connect / as sysdba

    SQL> select instance_name, status, database_status from v$instance;

What's the best way to break from nested loops in JavaScript?

Here are five ways to break out of nested loops in JavaScript:

1) Set parent(s) loop to the end

for (i = 0; i < 5; i++)
    for (j = 0; j < 5; j++)
        if (j === 2)
            i = 5;

2) Use label

for (i = 0; i < 5; i++)
    for (j = 0; j < 5; j++)
        if (j === 2)
            break exit_loops;

3) Use variable

var exit_loops = false;
for (i = 0; i < 5; i++)
    for (j = 0; j < 5; j++)
        if (j === 2)
            exit_loops = true;
    if (exit_loops)

4) Use self executing function

    for (i = 0; i < 5; i++)
        for (j = 0; j < 5; j++)
             if (j === 2)

5) Use regular function

function nested_loops()
    for (i = 0; i < 5; i++)
        for (j = 0; j < 5; j++)
             if (j === 2)

Write string to text file and ensure it always overwrites the existing content.

If your code doesn't require the file to be truncated first, you can use the FileMode.OpenOrCreate to open the filestream, which will create the file if it doesn't exist or open it if it does. You can use the stream to point at the front and start overwriting the existing file?

I'm assuming your using a streams here, there are other ways to write a file.

node.js execute system command synchronously

I get used to implement "synchronous" stuff at the end of the callback function. Not very nice, but it works. If you need to implement a sequence of command line executions you need to wrap exec into some named function and recursively call it. This pattern seem to be usable for me:


function SeqOfExec(somepParam) {
    // some stuff
    // .....
    // .....

    var execStr = "yourExecString";
    child_proc.exec(execStr, function (error, stdout, stderr) {
        if (error != null) {
            if (stdout) {
                throw Error("Smth goes wrong" + error);
            } else {
                // consider that empty stdout causes
                // creation of error object
        // some stuff
        // .....
        // .....

        // you also need some flag which will signal that you 
        // need to end loop
        if (someFlag ) {
            // your synch stuff after all execs
            // here
            // .....
        } else {

TERM environment variable not set

Using a terminal command i.e. "clear", in a script called from cron (no terminal) will trigger this error message. In your particular script, the smbmount command expects a terminal in which case the work-arounds above are appropriate.

How to remove all duplicate items from a list

for unhashable lists. It is faster as it does not iterate about already checked entries.

def purge_dublicates(X):
    unique_X = []
    for i, row in enumerate(X):
        if row not in X[i + 1:]:
    return unique_X

External VS2013 build error "error MSB4019: The imported project <path> was not found"

I had the same issue and find an easier solution

It is due to Vs2012 adding the following to the csproj file:

  <VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion>
  <VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>

You can safely remove that part and your solution will build.

As Sielu pointed out you have to ensure that the .proj file begin with <Project ToolsVersion="12" otherwise the next time you open the project with visual studio 2010, it will add the removed node again.

Otherwise, if you need to use webdeploy or you use a build server, the above solution will not work but you can specify the VisualStudioVersion property in your build script:

msbuild myproject.csproj /p:VisualStudioVersion=12.0

or edit your build definition:

edit build definition to specify the <code>VisualStudioVersion</code> property

Selenium WebDriver: Wait for complex page with JavaScript to load

Here's how I do it:

new WebDriverWait(driver, 20).until(
                   "return document.readyState === 'complete' ? true : false"));

jQuery Find and List all LI elements within a UL within a specific DIV


<ul class="answerList" id="oneAnswer">
    <li class="answer" value="false">info1</li>
    <li class="answer" value="false">info2</li>
    <li class="answer" value="false">info3</li>

Get index,text,value js

    $('#oneAnswer li').each(function (i) {

        var index = $(this).index();
        var text = $(this).text();
        var value = $(this).attr('value');
        alert('Index is: ' + index + ' and text is ' + text + ' and Value ' + value);

req.query and req.param in ExpressJS

I would suggest using following


req.param("") works as following

Lookup is performed in the following order:


Direct access to req.body, req.params, and req.query should be favoured for clarity - unless you truly accept input from each object.


Shell script "for" loop syntax

If the seq command available on your system:

for i in `seq 2 $max`
  echo "output: $i"

If not, then use poor man's seq with perl:

seq=`perl -e "\$,=' ';print 2..$max"`
for i in $seq
  echo "output: $i"

Watch those quote marks.

SQL to LINQ Tool

Edit 7/17/2020: I cannot delete this accepted answer. It used to be good, but now it isn't. Beware really old posts, guys. I'm removing the link.

[Linqer] is a SQL to LINQ converter tool. It helps you to learn LINQ and convert your existing SQL statements.

Not every SQL statement can be converted to LINQ, but Linqer covers many different types of SQL expressions. Linqer supports both .NET languages - C# and Visual Basic.

How to handle the modal closing event in Twitter Bootstrap?

There are two pair of modal events, one is "show" and "shown", the other is "hide" and "hidden". As you can see from the name, hide event fires when modal is about the be close, such as clicking on the cross on the top-right corner or close button or so on. While hidden is fired after the modal is actually close. You can test these events your self. For exampel:

$( '#modal' )
   .on('hide', function() {
   .on('hidden', function(){
   .on('show', function() {
   .on('shown', function(){
      console.log('shown' )

And, as for your question, I think you should listen to the 'hide' event of your modal.

Creating a generic method in C#

You can use sort of Maybe monad (though I'd prefer Jay's answer)

public class Maybe<T>
    private readonly T _value;

    public Maybe(T value)
        _value = value;
        IsNothing = false;

    public Maybe()
        IsNothing = true;

    public bool IsNothing { get; private set; }

    public T Value
            if (IsNothing)
                throw new InvalidOperationException("Value doesn't exist");
            return _value;

    public override bool Equals(object other)
        if (IsNothing)
            return (other == null);
        if (other == null)
            return false;
        return _value.Equals(other);

    public override int GetHashCode()
        if (IsNothing)
            return 0;
        return _value.GetHashCode();

    public override string ToString()
        if (IsNothing)
            return "";
        return _value.ToString();

    public static implicit operator Maybe<T>(T value)
        return new Maybe<T>(value);

    public static explicit operator T(Maybe<T> value)
        return value.Value;

Your method would look like:

    public static Maybe<T> GetQueryString<T>(string key) where T : IConvertible
        if (String.IsNullOrEmpty(HttpContext.Current.Request.QueryString[key]) == false)
            string value = HttpContext.Current.Request.QueryString[key];

                return (T)Convert.ChangeType(value, typeof(T));
                //Could not convert.  Pass back default value...
                return new Maybe<T>();

        return new Maybe<T>();

Text that shows an underline on hover

Fairly simple process I am using SCSS obviously but you don't have to as it's just CSS in the end!


<span class="menu">Menu</span>


.menu {
    position: relative;
    text-decoration: none;
    font-weight: 400;
    color: blue;
    transition: all .35s ease;

    &::before {
        content: "";
        position: absolute;
        width: 100%;
        height: 2px;
        bottom: 0;
        left: 0;
        background-color: yellow;
        visibility: hidden;
        -webkit-transform: scaleX(0);
        transform: scaleX(0);
        -webkit-transition: all 0.3s ease-in-out 0s;
        transition: all 0.3s ease-in-out 0s;

    &:hover {
        color: yellow;

        &::before {
            visibility: visible;
            -webkit-transform: scaleX(1);
            transform: scaleX(1);

How to wait in bash for several subprocesses to finish and return exit code !=0 when any subprocess ends with code !=0?

I almost fell into the trap of using jobs -p to collect PIDs, which does not work if the child has already exited, as shown in the script below. The solution I picked was simply calling wait -n N times, where N is the number of children I have, which I happen to know deterministically.

#!/usr/bin/env bash

sleeper() {
    echo "Sleeper $1"
    sleep $2
    echo "Exiting $1"
    return $3

start_sleepers() {
    sleeper 1 1 0 &
    sleeper 2 2 $1 &
    sleeper 3 5 0 &
    sleeper 4 6 0 &
    sleep 4

echo "Using jobs"
start_sleepers 1

pids=( $(jobs -p) )

echo "PIDS: ${pids[*]}"

for pid in "${pids[@]}"; do
    wait "$pid"
    echo "Exit code $?"

echo "Clearing other children"
wait -n; echo "Exit code $?"
wait -n; echo "Exit code $?"

echo "Waiting for N processes"
start_sleepers 2

for ignored in $(seq 1 4); do
    wait -n
    echo "Exit code $?"


Using jobs
Sleeper 1
Sleeper 2
Sleeper 3
Sleeper 4
Exiting 1
Exiting 2
PIDS: 56496 56497
Exiting 3
Exit code 0
Exiting 4
Exit code 0
Clearing other children
Exit code 0
Exit code 1
Waiting for N processes
Sleeper 1
Sleeper 2
Sleeper 3
Sleeper 4
Exiting 1
Exiting 2
Exit code 0
Exit code 2
Exiting 3
Exit code 0
Exiting 4
Exit code 0

What's onCreate(Bundle savedInstanceState)

onCreate(Bundle savedInstanceState) you will get the Bundle null when activity get starts first time and it will get in use when activity orientation get changed .......

Android provides another elegant way of achieving this. To achieve this, we have to override a method called onSaveInstanceState(). Android platform allows the users to save any instance state. Instance state can be saved in the Bundle. Bundle is passed as argument to the onSaveInstanceState method.

we can load the saved instance state from the Bundle passed as argument to the onCreate method. We can also load the saved instance state in onRestoreInstanceState method. But I will leave that for the readers to figure out.

How can I check if a scrollbar is visible?

The first solution above works only in IE The second solution above works only in FF

This combination of both functions works in both browsers:

//Firefox Only!!
if ($(document).height() > $(window).height()) {
    // has scrollbar
    alert('scrollbar present - Firefox');
} else {

//Internet Explorer Only!!
(function($) {
    $.fn.hasScrollBar = function() {
        return this.get(0).scrollHeight > this.innerHeight();
if ($('#monitorWidth1').hasScrollBar()) {
    // has scrollbar
    alert('scrollbar present - Internet Exploder');
} else {
  • Wrap in a document ready
  • monitorWidth1 : the div where the overflow is set to auto
  • mtc : a container div inside monitorWidth1
  • AdjustOverflowWidth : a css class applied to the #mtc div when the Scrollbar is active *Use the alert to test cross browser, and then comment out for final production code.


Laravel - Form Input - Multiple select for a one to many relationship

A multiple select is really just a select with a multiple attribute. With that in mind, it should be as easy as...

Form::select('sports[]', $sports, null, array('multiple'))

The first parameter is just the name, but post-fixing it with the [] will return it as an array when you use Input::get('sports').

The second parameter is an array of selectable options.

The third parameter is an array of options you want pre-selected.

The fourth parameter is actually setting this up as a multiple select dropdown by adding the multiple property to the actual select element..

Python Binomial Coefficient

The simplest way is using the Multiplicative formula. It works for (n,n) and (n,0) as expected.

def coefficient(n,k):
    c = 1.0
    for i in range(1, k+1):
        c *= float((n+1-i))/float(i)
    return c

Multiplicative formula

In Oracle, is it possible to INSERT or UPDATE a record through a view?

YES, you can Update and Insert into view and that edit will be reflected on the original table....
1-the view should have all the NOT NULL values on the table
2-the update should have the same rules as table... "updating primary key related to other foreign key.. etc"...

target input by type and name (selector)

You can combine attribute selectors this way:


so that an element has to satisfy both conditions. Of course you can use this for more than two. Also, don't do [type=checkbox]. jQuery has a selector for that, namely :checkbox so the end result is:


Attribute selectors are slow however so the recommended approach is to use ID and class selectors where possible. You could change your markup to:

<input type="checkbox" class="ProductCode" name="ProductCode"value="396P4"> 
<input type="checkbox" class="ProductCode" name="ProductCode"value="401P4"> 
<input type="checkbox" class="ProductCode" name="ProductCode"value="F460129">

allowing you to use the much faster selector of:


Which language uses .pde extension?

The .pde file extension is the one used by the Processing, Wiring, and the Arduino IDE.

Processing is not C-based but rather Java-based and with a syntax derived from Java. It is a Java framework that can be used as a Java library. It includes a default IDE that uses .pde extension. Just wanted to rectify @kersny's answer.

Wiring is a microcontroller that uses the same IDE. Arduino uses a modified version, but also with .pde. The OpenProcessing page where you found it is a website to exhibit some Processing work.

If you know Java, it should be fairly easy to convert the Processing code to Java AWT.

Showing all errors and warnings

Straight from the php.ini file:

; Error handling and logging ;

; This directive informs PHP of which errors, warnings and notices you would like
; it to take action for. The recommended way of setting values for this
; directive is through the use of the error level constants and bitwise
; operators. The error level constants are below here for convenience as well as
; some common settings and their meanings.
; By default, PHP is set to take action on all errors, notices and warnings EXCEPT
; those related to E_NOTICE and E_STRICT, which together cover best practices and
; recommended coding standards in PHP. For performance reasons, this is the
; recommend error reporting setting. Your production server shouldn't be wasting
; resources complaining about best practices and coding standards. That's what
; development servers and development settings are for.
; Note: The php.ini-development file has this setting as E_ALL. This
; means it pretty much reports everything which is exactly what you want during
; development and early testing.
; Error Level Constants:
; E_ALL             - All errors and warnings (includes E_STRICT as of PHP 5.4.0)
; E_ERROR           - fatal run-time errors
; E_RECOVERABLE_ERROR  - almost fatal run-time errors
; E_WARNING         - run-time warnings (non-fatal errors)
; E_PARSE           - compile-time parse errors
; E_NOTICE          - run-time notices (these are warnings which often result
;                     from a bug in your code, but it's possible that it was
;                     intentional (e.g., using an uninitialized variable and
;                     relying on the fact it is automatically initialized to an
;                     empty string)
; E_STRICT          - run-time notices, enable to have PHP suggest changes
;                     to your code which will ensure the best interoperability
;                     and forward compatibility of your code
; E_CORE_ERROR      - fatal errors that occur during PHP's initial startup
; E_CORE_WARNING    - warnings (non-fatal errors) that occur during PHP's
;                     initial startup
; E_COMPILE_ERROR   - fatal compile-time errors
; E_COMPILE_WARNING - compile-time warnings (non-fatal errors)
; E_USER_ERROR      - user-generated error message
; E_USER_WARNING    - user-generated warning message
; E_USER_NOTICE     - user-generated notice message
; E_DEPRECATED      - warn about code that will not work in future versions
;                     of PHP
; E_USER_DEPRECATED - user-generated deprecation warnings
; Common Values:
;   E_ALL (Show all errors, warnings and notices including coding standards.)
;   E_ALL & ~E_NOTICE  (Show all errors, except for notices)
;   E_ALL & ~E_NOTICE & ~E_STRICT  (Show all errors, except for notices and coding standards warnings.)
; Default Value: E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED
; Development Value: E_ALL
; Production Value: E_ALL & ~E_DEPRECATED & ~E_STRICT
error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT

For pure development I go for:

error_reporting = E_ALL ^ E_NOTICE ^ E_WARNING

Also don't forget to put display_errors to on

display_errors = On

After that, restart your server for Apache on Ubuntu:

sudo /etc/init.d/apache2 restart

Is there a CSS selector for text nodes?

Text nodes cannot have margins or any other style applied to them, so anything you need style applied to must be in an element. If you want some of the text inside of your element to be styled differently, wrap it in a span or div, for example.

Setting Curl's Timeout in PHP

See documentation:

CURLOPT_CONNECTTIMEOUT - The number of seconds to wait while trying to connect. Use 0 to wait indefinitely.
CURLOPT_TIMEOUT - The maximum number of seconds to allow cURL functions to execute.

curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0); 
curl_setopt($ch, CURLOPT_TIMEOUT, 400); //timeout in seconds

also don't forget to enlarge time execution of php script self:

set_time_limit(0);// to infinity for example

EditText non editable

android:editable="false" should work, but it is deprecated, you should be using android:inputType="none" instead.

Alternatively, if you want to do it in the code you could do this :

EditText mEdit = (EditText) findViewById(;

This is also a viable alternative :

EditText mEdit = (EditText) findViewById(;

If you're going to make your EditText non-editable, may I suggest using the TextView widget instead of the EditText, since using a EditText seems kind of pointless in that case.

EDIT: Altered some information since I've found that android:editable is deprecated, and you should use android:inputType="none", but there is a bug about it on android code; So please check this.

How to remove an HTML element using Javascript?

Your JavaScript is correct. Your button has type="submit" which is causing the page to refresh.

How to get parameters from the URL with JSP

request.getParameter("accountID") is what you're looking for. This is part of the Java Servlet API. See for more information.

Error Code 1292 - Truncated incorrect DOUBLE value - Mysql

If you have used CHECK CONSTRAINT on table for string field length

e.g: to check username length >= 8


CHECK (CHAR_LENGTH(username)>=8)

instead of

CHECK (username>=8)

fix the check constraint if any have wrong datatype comparison

Delete duplicate records from a SQL table without a primary key

there are two columns in the a table ID and name where names are repeating with different IDs so for that you may use this query: . .

DELETE FROM dbo.tbl1
     Select MIN(Id) AS namecount FROM tbl1
     GROUP BY Name

Do Git tags only apply to the current branch?

Tags and branch are completely unrelated, since tags refer to a specific commit, and branch is a moving reference to the last commit of a history. Branches go, tags stay.

So when you tag a commit, git doesn't care which commit or branch is checked out, if you provide him the SHA1 of what you want to tag.

I can even tag by refering to a branch (it will then tag the tip of the branch), and later say that the branch's tip is elsewhere (with git reset --hard for example), or delete the branch. The tag I created however won't move.

Plot smooth line with PyPlot

For this example spline works well, but if the function is not smooth inherently and you want to have smoothed version you can also try:

from scipy.ndimage.filters import gaussian_filter1d

ysmoothed = gaussian_filter1d(y, sigma=2)
plt.plot(x, ysmoothed)

if you increase sigma you can get a more smoothed function.

Proceed with caution with this one. It modifies the original values and may not be what you want.

HashMap allows duplicates?

Hashmap type Overwrite that key if hashmap key is same key




How do I call a dynamically-named method in Javascript?

Try These

Call Functions With Dynamic Names, like this:

let dynamic_func_name = 'alert';
(new Function(dynamic_func_name+'()'))()

with parameters:

let dynamic_func_name = 'alert';
let para_1 = 'HAHAHA';
let para_2 = 'ABCD';
(new Function(`${dynamic_func_name}('${para_1}','${para_2}')`))()

Run Dynamic Code:

let some_code = "alert('hahaha');";
(new Function(some_code))()

Fastest way to Remove Duplicate Value from a list<> by lambda

There is Distinct() method. it should works.

List<long> longs = new List<long> { 1, 2, 3, 4, 3, 2, 5 };
var distinctList = longs.Distinct().ToList();

Get the IP Address of local computer

The problem with all the approaches based on gethostbyname is that you will not get all IP addresses assigned to a particular machine. Servers usually have more than one adapter.

Here is an example of how you can iterate through all Ipv4 and Ipv6 addresses on the host machine:

void ListIpAddresses(IpAddresses& ipAddrs)
  IP_ADAPTER_ADDRESSES* adapter_addresses(NULL);

  // Start with a 16 KB buffer and resize if needed -
  // multiple attempts in case interfaces change while
  // we are in the middle of querying them.
  DWORD adapter_addresses_buffer_size = 16 * KB;
  for (int attempts = 0; attempts != 3; ++attempts)
    adapter_addresses = (IP_ADAPTER_ADDRESSES*)malloc(adapter_addresses_buffer_size);

    DWORD error = ::GetAdaptersAddresses(

    if (ERROR_SUCCESS == error)
      // We're done here, people!
    else if (ERROR_BUFFER_OVERFLOW == error)
      // Try again with the new size
      adapter_addresses = NULL;

      // Unexpected error code - log and throw
      adapter_addresses = NULL;

      // @todo

  // Iterate through all of the adapters
  for (adapter = adapter_addresses; NULL != adapter; adapter = adapter->Next)
    // Skip loopback adapters
    if (IF_TYPE_SOFTWARE_LOOPBACK == adapter->IfType)

    // Parse all IPv4 and IPv6 addresses
    for (
      IP_ADAPTER_UNICAST_ADDRESS* address = adapter->FirstUnicastAddress; 
      NULL != address;
      address = address->Next)
      auto family = address->Address.lpSockaddr->sa_family;
      if (AF_INET == family)
        // IPv4
        SOCKADDR_IN* ipv4 = reinterpret_cast<SOCKADDR_IN*>(address->Address.lpSockaddr);

        char str_buffer[INET_ADDRSTRLEN] = {0};
        inet_ntop(AF_INET, &(ipv4->sin_addr), str_buffer, INET_ADDRSTRLEN);
      else if (AF_INET6 == family)
        // IPv6
        SOCKADDR_IN6* ipv6 = reinterpret_cast<SOCKADDR_IN6*>(address->Address.lpSockaddr);

        char str_buffer[INET6_ADDRSTRLEN] = {0};
        inet_ntop(AF_INET6, &(ipv6->sin6_addr), str_buffer, INET6_ADDRSTRLEN);

        std::string ipv6_str(str_buffer);

        // Detect and skip non-external addresses
        bool is_link_local(false);
        bool is_special_use(false);

        if (0 == ipv6_str.find("fe"))
          char c = ipv6_str[2];
          if (c == '8' || c == '9' || c == 'a' || c == 'b')
            is_link_local = true;
        else if (0 == ipv6_str.find("2001:0:"))
          is_special_use = true;

        if (! (is_link_local || is_special_use))
        // Skip all other types of addresses

  // Cleanup
  adapter_addresses = NULL;

  // Cheers!

How to revert initial git commit?

You can't. So:

rm -rf .git/
git init
git add -A
git commit -m 'Your new commit message'

Install-Module : The term 'Install-Module' is not recognized as the name of a cmdlet

I have Windows 10 and PowerShell 5.1 was already installed. For whatever reason the x86 version works and can find "Install-Module", but the other version cannot.

Search your Start Menu for "powershell", and find the entry that ends in "(x86)":

Windows 10 Start Menu searching for PowerShell

Here is what I experience between the two different versions:

PowerShell x86 vs x64 running Install-Module cmdlet comparison

How to add anything in <head> through jquery/javascript?

Create a temporary element (e. g. DIV), assign your HTML code to its innerHTML property, and then append its child nodes to the HEAD element one by one. For example, like this:

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

temp.innerHTML = '<link rel="stylesheet" href="example.css" />'
               + '<script src="foobar.js"><\/script> ';

var head = document.head;

while (temp.firstChild) {

Compared with rewriting entire HEAD contents via its innerHTML, this wouldn’t affect existing child elements of the HEAD element in any way.

Note that scripts inserted this way are apparently not executed automatically, while styles are applied successfully. So if you need scripts to be executed, you should load JS files using Ajax and then execute their contents using eval().

Iterating over every two elements in a list

for (i, k) in zip(l[::2], l[1::2]):
    print i, "+", k, "=", i+k

zip(*iterable) returns a tuple with the next element of each iterable.

l[::2] returns the 1st, the 3rd, the 5th, etc. element of the list: the first colon indicates that the slice starts at the beginning because there's no number behind it, the second colon is only needed if you want a 'step in the slice' (in this case 2).

l[1::2] does the same thing but starts in the second element of the lists so it returns the 2nd, the 4th, 6th, etc. element of the original list.

Merge data frames based on rownames in R

See ?merge:

the name "row.names" or the number 0 specifies the row names.


R> de <- merge(d, e, by=0, all=TRUE)  # merge by row names (by=0 or by="row.names")
R> de[] <- 0                 # replace NA values
R> de
  Row.names   a   b   c   d   e   f   g   h   i  j  k  l  m  n  o  p  q  r  s
1         1 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10 11 12 13 14 15 16 17 18 19
2         2 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9  1  0  0  0  0  0  0  0  0  0
3         3 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0  0 21 22 23 24 25 26 27 28 29
1 20
2  0
3 30

Creating runnable JAR with Gradle

An executable jar file is just a jar file containing a Main-Class entry in its manifest. So you just need to configure the jar task in order to add this entry in its manifest:

jar {
    manifest {
        attributes 'Main-Class': ''

You might also need to add classpath entries in the manifest, but that would be done the same way.


Android get image path from drawable as string

First check whether the file exists in SDCard. If the file doesnot exists in SDcard then you can set image using setImageResource() methodand passing default image from drawable folder

Sample Code

File imageFile = new File(absolutepathOfImage);//absolutepathOfImage is absolute path of image including its name
        if(!imageFile.exists()){//file doesnot exist in SDCard

        imageview.setImageResource(R.drawable.defaultImage);//set default image from drawable folder

How to test Spring Data repositories?


To make it short - there's no way to unit test Spring Data JPA repositories reasonably for a simple reason: it's way to cumbersome to mock all the parts of the JPA API we invoke to bootstrap the repositories. Unit tests don't make too much sense here anyway, as you're usually not writing any implementation code yourself (see the below paragraph on custom implementations) so that integration testing is the most reasonable approach.


We do quite a lot of upfront validation and setup to make sure you can only bootstrap an app that has no invalid derived queries etc.

  • We create and cache CriteriaQuery instances for derived queries to make sure the query methods do not contain any typos. This requires working with the Criteria API as well as the meta.model.
  • We verify manually defined queries by asking the EntityManager to create a Query instance for those (which effectively triggers query syntax validation).
  • We inspect the Metamodel for meta-data about the domain types handled to prepare is-new checks etc.

All stuff that you'd probably defer in a hand-written repository which might cause the application to break at runtime (due to invalid queries etc.).

If you think about it, there's no code you write for your repositories, so there's no need to write any unittests. There's simply no need to as you can rely on our test base to catch basic bugs (if you still happen to run into one, feel free to raise a ticket). However, there's definitely need for integration tests to test two aspects of your persistence layer as they are the aspects that related to your domain:

  • entity mappings
  • query semantics (syntax is verified on each bootstrap attempt anyway).

Integration tests

This is usually done by using an in-memory database and test cases that bootstrap a Spring ApplicationContext usually through the test context framework (as you already do), pre-populate the database (by inserting object instances through the EntityManager or repo, or via a plain SQL file) and then execute the query methods to verify the outcome of them.

Testing custom implementations

Custom implementation parts of the repository are written in a way that they don't have to know about Spring Data JPA. They are plain Spring beans that get an EntityManager injected. You might of course wanna try to mock the interactions with it but to be honest, unit-testing the JPA has not been a too pleasant experience for us as well as it works with quite a lot of indirections (EntityManager -> CriteriaBuilder, CriteriaQuery etc.) so that you end up with mocks returning mocks and so on.

ARG or ENV, which one to use in this case?

From Dockerfile reference:

  • The ARG instruction defines a variable that users can pass at build-time to the builder with the docker build command using the --build-arg <varname>=<value> flag.

  • The ENV instruction sets the environment variable <key> to the value <value>.
    The environment variables set using ENV will persist when a container is run from the resulting image.

So if you need build-time customization, ARG is your best choice.
If you need run-time customization (to run the same image with different settings), ENV is well-suited.

If I want to add let's say 20 (a random number) of extensions or any other feature that can be enable|disable

Given the number of combinations involved, using ENV to set those features at runtime is best here.

But you can combine both by:

  • building an image with a specific ARG
  • using that ARG as an ENV

That is, with a Dockerfile including:

ARG var
ENV var=${var}

You can then either build an image with a specific var value at build-time (docker build --build-arg var=xxx), or run a container with a specific runtime value (docker run -e var=yyy)

What could cause java.lang.reflect.InvocationTargetException?

I had a java.lang.reflect.InvocationTargetException error from a statement calling a logger object in an external class inside a try / catch block in my class.

Stepping through the code in the Eclipse debugger & hovering the mouse over the logger statement I saw the logger object was null (some external constants needed to be instantiated at the very top of my class).

HTML/CSS font color vs span style

You should use <span>, because as specified by the spec, <font> has been deprecated and probably won't display as you intend.

How to get access to HTTP header information in Spring MVC REST controller?

You can use the @RequestHeader annotation with HttpHeaders method parameter to gain access to all request headers:

@RequestMapping(value = "/restURL")
public String serveRest(@RequestBody String body, @RequestHeader HttpHeaders headers) {
    // Use headers to get the information about all the request headers
    long contentLength = headers.getContentLength();
    // ...
    StreamSource source = new StreamSource(new StringReader(body));
    YourObject obj = (YourObject) jaxb2Mashaller.unmarshal(source);
    // ...

Pointer arithmetic for void pointer in C

You can't do pointer arithmetic on void * types, for exactly this reason!

chrome undo the action of "prevent this page from creating additional dialogs"

Turning Hardware Acceleration OFF seems to be the setting that affects popups & dialogs.

Chrome was continually hiding Dialog Windows when I needed to respond Yes or No to things, also when I needed to Rename folders in my bookmarks panel. After weeks of doing this. I disabled all the Chrome helpers in Settings, Also In windows 10 I switched Window Snapping off. It has done something to put the popups and dialogs back in the Viewport.

When this bug is happening, I was able to shut a tab by first pressing Enter before clicking the tab close X button. The browser had an alert box, hidden which needed a response from the user.

Switching Hardware Accleration Off and back On, Killing the Chrome process and switching all the other Helpers Off and back has fixed it for me... It must be in chrome itself because Ive just gone into a Chrome window in the Mac and it has now stopped the problem, without any intervention. Im guessing flicking the chrome settings on/off/on has caused it to reposition the dialogs. I cant get the browser to repeat the fault now...

How can I get a character in a string by index?

Do you mean like this

int index = 2;
string s = "hello";

string also implements IEnumberable<char> so you can also enumerate it like this

foreach (char c in s)

How can I get a list of all functions stored in the database of a particular schema in PostgreSQL?

Run below SQL query to create a view which will show all functions:

    SELECT routine_name FROM information_schema.routines 
        WHERE routine_type='FUNCTION' AND specific_schema='public';

How to see data from .RData file?

you can try

isfar <- get(load('c:/users/isfar.Rdata'))

this will assign the variable in isfar.Rdata to isfar . After this assignment, you can use str(isfar) or ls(isfar) or head(isfar) to get a rough look of the isfar.