Programs & Examples On #Mainframe

The mainframe tag refers to the class of "big iron" computers, primarily those from IBM. Currently this is limited to the System z hardware, typically running zOS as its operating system, zVM, or zLinux.

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+

What is the difference between Serialization and Marshaling?

From the Marshalling (computer science) Wikipedia article:

The term "marshal" is considered to be synonymous with "serialize" in the Python standard library1, but the terms are not synonymous in the Java-related RFC 2713:

To "marshal" an object means to record its state and codebase(s) in such a way that when the marshalled object is "unmarshalled", a copy of the original object is obtained, possibly by automatically loading the class definitions of the object. You can marshal any object that is serializable or remote. Marshalling is like serialization, except marshalling also records codebases. Marshalling is different from serialization in that marshalling treats remote objects specially. (RFC 2713)

To "serialize" an object means to convert its state into a byte stream in such a way that the byte stream can be converted back into a copy of the object.

So, marshalling also saves the codebase of an object in the byte stream in addition to its state.

Can I access variables from another file?

I did like what answer above said but although, it didn't worked with me

because I was declaring these variables inside JQuery $( document ).ready()

so make sure you declare your variables inside the <script> tag not somewhere else

Using jQuery to center a DIV on the screen

To center the element relative to the browser viewport (window), don't use position: absolute, the correct position value should be fixed (absolute means: "The element is positioned relative to its first positioned (not static) ancestor element").

This alternative version of the proposed center plugin uses "%" instead of "px" so when you resize the window the content is keep centered:

$ = function () {
    var heightRatio = ($(window).height() != 0) 
            ? this.outerHeight() / $(window).height() : 1;
    var widthRatio = ($(window).width() != 0) 
            ? this.outerWidth() / $(window).width() : 1;

        position: 'fixed',
        margin: 0,
        top: (50*(1-heightRatio)) + "%",
        left: (50*(1-widthRatio))  + "%"

    return this;

You need to put margin: 0 to exclude the content margins from the width/height (since we are using position fixed, having margins makes no sense). According to the jQuery doc using .outerWidth(true) should include margins, but it didn't work as expected when I tried in Chrome.

The 50*(1-ratio) comes from:

Window Width: W = 100%

Element Width (in %): w = 100 * elementWidthInPixels/windowWidthInPixels

Them to calcule the centered left:

 left = W/2 - w/2 = 50 - 50 * elementWidthInPixels/windowWidthInPixels =
 = 50 * (1-elementWidthInPixels/windowWidthInPixels)

Whitespace Matching Regex - Java

For Java (not php, not javascript, not anyother):

txt.replaceAll("\\p{javaSpaceChar}{2,}"," ")

Synchronous Requests in Node.js

See sync-request:


var request = require('sync-request');
var res = request('GET', '');

How do I output the results of a HiveQL query to CSV?

This shell command prints the output format in csv to output.txt without the column headers.

$ hive --outputformat=csv2 -f 'hivedatascript.hql' --hiveconf hive.cli.print.header=false > output.txt

If Else in LINQ

Answer above is not suitable for complicate Linq expression. All you need is:

// set up the "main query"
var test = from p in _db.test select _db.test;
// if str1 is not null, add a where-condition
if(str1 != null)
    test = test.Where(p => p.test == str);

How can I remove an element from a list?

Use - (Negative sign) along with position of element, example if 3rd element is to be removed use it as your_list[-3]


my_list <- list(a = 3, b = 3, c = 4, d = "Hello", e = NA)
# $`a`
# [1] 3

# $b
# [1] 3

# $c
# [1] 4

# $d
# [1] "Hello"

# $e
# [1] NA

Remove single element from list

 # $`a`
 # [1] 3

 # $b
 # [1] 3

 # $d
 # [1] "Hello"

 # $e
 [1] NA

Remove multiple elements from list

 # $`d`
 # [1] "Hello"

 # $e
 # [1] NA

 # $`a`
 # [1] 3

 # $b
 # [1] 3

 # $`c`
 # [1] 4

 # $d
 # [1] "Hello"

 # $e
 # [1] NA

Nested lists python

n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
def flatten(lists):
  results = []
  for numbers in lists:
    for numbers2 in numbers:
  return results
print flatten(n)

Output: n = [1,2,3,4,5,6,7,8,9]

Windows 10 SSH keys

  1. Open the windows command line (type "cmd" on the search box and hit enter).
  2. It'll default to your home folder, so you don't need to cd to a different one.
  3. Type ssh-keygen
  4. Follow the instructions and you are good to go
  5. Your ssh keys should be stored at chosed directory, the default is: /c/Users/YourUserName/.ssh/

p.s.: If you installed git with bash integration (like me) open "Git Bash" instead of "cmd" on first step

How do I install g++ on MacOS X?

That's the compiler that comes with Apple's XCode tools package. They've hacked on it a little, but basically it's just g++.

You can download XCode for free (well, mostly, you do have to sign up to become an ADC member, but that's free too) here:

Edit 2013-01-25: This answer was correct in 2010. It needs an update.

While XCode tools still has a command-line C++ compiler, In recent versions of OS X (I think 10.7 and later) have switched to clang/llvm (mostly because Apple wants all the benefits of Open Source without having to contribute back and clang is BSD licensed). Secondly, I think all you have to do to install XCode is to download it from the App store. I'm pretty sure it's free there.

So, in order to get g++ you'll have to use something like homebrew (seemingly the current way to install Open Source software on the Mac (though homebrew has a lot of caveats surrounding installing gcc using it)), fink (basically Debian's apt system for OS X/Darwin), or MacPorts (Basically, OpenBSDs ports system for OS X/Darwin) to get it.

Fink definitely has the right packages. On 2016-12-26, it had gcc 5 and gcc 6 packages.

I'm less familiar with how MacPorts works, though some initial cursory investigation indicates they have the relevant packages as well.

How to solve SQL Server Error 1222 i.e Unlock a SQL Server table

I had these SQL behavior settings enabled on options query execution: ANSI SET IMPLICIT_TRANSACTIONS checked. On execution of your query e.g create, alter table or stored procedure, you have to COMMIT it.

Just type COMMIT and execute it F5

How to implement a Keyword Search in MySQL?

I know this is a bit late but what I did to our application is this. Hope this will help someone tho. But it works for me:

SELECT * FROM `landmarks` WHERE `landmark_name` OR `landmark_description` OR `landmark_address` LIKE '%keyword'
OR `landmark_name` OR `landmark_description` OR `landmark_address` LIKE 'keyword%' 
OR `landmark_name` OR `landmark_description` OR `landmark_address` LIKE '%keyword%'

How do I make a Windows batch script completely silent?

If you want that all normal output of your Batch script be silent (like in your example), the easiest way to do that is to run the Batch file with a redirection:

C:\Temp> test.bat >nul

This method does not require to modify a single line in the script and it still show error messages in the screen. To supress all the output, including error messages:

C:\Temp> test.bat >nul 2>&1

If your script have lines that produce output you want to appear in screen, perhaps will be simpler to add redirection to those lineas instead of all the lines you want to keep silent:

SET scriptDirectory=%~dp0
COPY %scriptDirectory%test.bat %scriptDirectory%test2.bat
FOR /F %%f IN ('dir /B "%scriptDirectory%*.noext"') DO (
del "%scriptDirectory%%%f"
REM Next line DO appear in the screen
ECHO Script completed >con


"The public type <<classname>> must be defined in its own file" error in Eclipse

error in the very first line public class StaticDemo {

Any Class A which has access modifier as public must have a separate source file as or A.jav. This is specified in JLS 7.6 section:

If and only if packages are stored in a file system (§7.2), the host system may choose to enforce the restriction that it is a compile-time error if a type is not found in a file under a name composed of the type name plus an extension (such as .java or .jav) if either of the following is true:

  • The type is referred to by code in other compilation units of the package in which the type is declared.

  • The type is declared public (and therefore is potentially accessible from code in other packages).

However, you may have to remove public access modifier from the Class declaration StaticDemo. Then as StaticDemo class will have no modifier it will become package-private, That is, it will be visible only within its own package.

Check out Controlling Access to Members of a Class

How to link 2 cell of excel sheet?

The simplest solution is to select the second cell, and press =. This will begin the fomula creation process. Now either type in the 1st cell reference (eg, A1) or click on the first cell and press enter. This should make the second cell reference the value of the first cell.

To read up more on different options for referencing see - This Article.

How to check if the user can go back in browser history or not

Check if window.history.length is equal to 0.

How to set time zone of a java.util.Date?

Convert the Date to String and do it with SimpleDateFormat.

    SimpleDateFormat readFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    readFormat.setTimeZone(TimeZone.getTimeZone("GMT" + timezoneOffset));
    String dateStr = readFormat.format(date);
    SimpleDateFormat writeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    Date date = writeFormat.parse(dateStr);

How do I remove repeated elements from ArrayList?

If you are using model type List< T>/ArrayList< T> . Hope,it's help you.

Here is my code without using any other data structure like set or hashmap

for (int i = 0; i < Models.size(); i++){
for (int j = i + 1; j < Models.size(); j++) {       
 if (Models.get(i).getName().equals(Models.get(j).getName())) {    

How to make an AlertDialog in Flutter?

Another easy option to show Dialog is to use stacked_services package

      title: "Title",
      description: "Dialog message Tex",

Copy Paste Values only( xlPasteValues )

I've had this problem before too and I think I found the answer.

If you are using a button to run the macro, it is likely linked to a different macro, perhaps a save as version of what you are currently working in and you might not even realize it. Try running the macro directly from VBA (F5) instead of running it with the button. My guess is that will work. You just have to reassign the macro on the button to the one you actually want to run.

How do I use a regex in a shell script?

To complement the existing helpful answers:

Using Bash's own regex-matching operator, =~, is a faster alternative in this case, given that you're only matching a single value already stored in a variable:

set -- '12-34-5678' # set $1 to sample value

kREGEX_DATE='^[0-9]{2}[-/][0-9]{2}[-/][0-9]{4}$' # note use of [0-9] to avoid \d
[[ $1 =~ $kREGEX_DATE ]]
echo $? # 0 with the sample value, i.e., a successful match

Note, however, that the caveat re using flavor-specific regex constructs such as \d equally applies: While =~ supports EREs (extended regular expressions), it also supports the host platform's specific extension - it's a rare case of Bash's behavior being platform-dependent.

To remain portable (in the context of Bash), stick to the POSIX ERE specification.

Note that =~ even allows you to define capture groups (parenthesized subexpressions) whose matches you can later access through Bash's special ${BASH_REMATCH[@]} array variable.

Further notes:

  • $kREGEX_DATE is used unquoted, which is necessary for the regex to be recognized as such (quoted parts would be treated as literals).

  • While not always necessary, it is advisable to store the regex in a variable first, because Bash has trouble with regex literals containing \.

    • E.g., on Linux, where \< is supported to match word boundaries, [[ 3 =~ \<3 ]] && echo yes doesn't work, but re='\<3'; [[ 3 =~ $re ]] && echo yes does.
  • I've changed variable name REGEX_DATE to kREGEX_DATE (k signaling a (conceptual) constant), so as to ensure that the name isn't an all-uppercase name, because all-uppercase variable names should be avoided to prevent conflicts with special environment and shell variables.

Auto refresh code in HTML using meta tags

You're using smart quotes. That is, instead of standard quotation marks ("), you are using curly quotes (). This happens automatically with Microsoft Word and other word processors to make things look prettier, but it also mangles HTML. Make sure to code in a plain text editor, like Notepad or Notepad2.

    <title>HTML in 10 Simple Steps or Less</title>
    <meta http-equiv="refresh" content="5"> <!-- See the difference? -->

Email address validation using ASP.NET MVC data type attributes

Scripts are usually loaded in the end of the html page, and MVC recommends the using of bundles, just saying. So my best bet is that your jquery.validate files got altered in some way or are not updated to the latest version, since they do validate e-mail inputs.

So you could either update/refresh your nuget package or write your own function, really.

Here's an example which you would add in an extra file after jquery.validate.unobtrusive:

    function (value, element) {
        return this.optional( element ) || /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test( value );
    "This e-mail is not valid"

This is just a copy and paste of the current jquery.validate Regex, but this way you could set your custom error message/add extra methods to fields you might want to validate in the near future.

How do I decode a string with escaped unicode?

Note that the use of unescape() is deprecated and doesn't work with the TypeScript compiler, for example.

Based on radicand's answer and the comments section below, here's an updated solution:

var string = "http\\u00253A\\u00252F\\";
decodeURIComponent(JSON.parse('"' + string.replace(/\"/g, '\\"') + '"'));

Combining two sorted lists in Python

Well, the naive approach (combine 2 lists into large one and sort) will be O(N*log(N)) complexity. On the other hand, if you implement the merge manually (i do not know about any ready code in python libs for this, but i'm no expert) the complexity will be O(N), which is clearly faster. The idea is described wery well in post by Barry Kelly.

Position one element relative to another in CSS

position: absolute will position the element by coordinates, relative to the closest positioned ancestor, i.e. the closest parent which isn't position: static.

Have your four divs nested inside the target div, give the target div position: relative, and use position: absolute on the others.

Structure your HTML similar to this:

<div id="container">
  <div class="top left"></div>
  <div class="top right"></div>
  <div class="bottom left"></div>
  <div class="bottom right"></div>

And this CSS should work:

#container {
  position: relative;

#container > * {
  position: absolute;

.left {
  left: 0;

.right {
  right: 0;

.top {
  top: 0;

.bottom {
  bottom: 0;


Bash: Syntax error: redirection unexpected

do it the simpler way,

direc=$(basename `pwd`)

Or use the shell

$ direc=${PWD##*/}

Redirect form to different URL based on select option element

This can be archived by adding code on the onchange event of the select control.

For Example:

<select onchange="this.options[this.selectedIndex].value && (window.location = this.options[this.selectedIndex].value);">
    <option value="">Gmail</option>
    <option value="">Youtube</option>

What does jQuery.fn mean?

In the jQuery source code we have jQuery.fn = jQuery.prototype = {...} since jQuery.prototype is an object the value of jQuery.fn will simply be a reference to the same object that jQuery.prototype already references.

To confirm this you can check jQuery.fn === jQuery.prototype if that evaluates true (which it does) then they reference the same object

How do you get the index of the current iteration of a foreach loop?

How about something like this? Note that myDelimitedString may be null if myEnumerable is empty.

IEnumerator enumerator = myEnumerable.GetEnumerator();
string myDelimitedString;
string current = null;

if( enumerator.MoveNext() )
    current = (string)enumerator.Current;

while( null != current)
    current = (string)enumerator.Current; }

    myDelimitedString += current;

    if( enumerator.MoveNext() )
        myDelimitedString += DELIMITER;

What is the difference between Subject and BehaviorSubject?

BehaviorSubject keeps in memory the last value that was emitted by the observable. A regular Subject doesn't.

BehaviorSubject is like ReplaySubject with a buffer size of 1.

Is there a CSS parent selector?

The pseudo element :focus-within allows a parent to be selected if a descendent has focus.

An element can be focused if it has a tabindex attribute.

Browser support for focus-within



.click {_x000D_
  cursor: pointer;_x000D_
.color:focus-within .change {_x000D_
  color: red;_x000D_
.color:focus-within p {_x000D_
  outline: 0;_x000D_
<div class="color">_x000D_
  <p class="change" tabindex="0">_x000D_
    I will change color_x000D_
  <p class="click" tabindex="1">_x000D_
    Click me_x000D_

Incrementing in C++ - When to use x++ or ++x?

Scott Meyers tells you to prefer prefix except on those occasions where logic would dictate that postfix is appropriate.

"More Effective C++" item #6 - that's sufficient authority for me.

For those who don't own the book, here are the pertinent quotes. From page 32:

From your days as a C programmer, you may recall that the prefix form of the increment operator is sometimes called "increment and fetch", while the postfix form is often known as "fetch and increment." The two phrases are important to remember, because they all but act as formal specifications...

And on page 34:

If you're the kind who worries about efficiency, you probably broke into a sweat when you first saw the postfix increment function. That function has to create a temporary object for its return value and the implementation above also creates an explicit temporary object that has to be constructed and destructed. The prefix increment function has no such temporaries...

Getting attributes of Enum's value

Alternatively, you could do the following:

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

    foreach (var item in typeof(PaymentTerm).GetEnumValues())
        var type = item.GetType();
        var name = type.GetField(item.ToString()).GetCustomAttributesData().FirstOrDefault()?.NamedArguments.FirstOrDefault().TypedValue.Value.ToString();
        selectListItems.Add(new SelectListItem(name, type.Name));


How to add noise (Gaussian/salt and pepper etc) to image in Python with OpenCV

just look at cv2.randu() or cv.randn(), it's all pretty similar to matlab already, i guess.

let's play a bit ;) :

import cv2
import numpy as np

>>> im = np.empty((5,5), np.uint8) # needs preallocated input image
>>> im
array([[248, 168,  58,   2,   1],  # uninitialized memory counts as random, too ?  fun ;) 
       [  0, 100,   2,   0, 101],
       [  0,   0, 106,   2,   0],
       [131,   2,   0,  90,   3],
       [  0, 100,   1,   0,  83]], dtype=uint8)
>>> im = np.zeros((5,5), np.uint8) # seriously now.
>>> im
array([[0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0]], dtype=uint8)
>>> cv2.randn(im,(0),(99))         # normal
array([[  0,  76,   0, 129,   0],
       [  0,   0,   0, 188,  27],
       [  0, 152,   0,   0,   0],
       [  0,   0, 134,  79,   0],
       [  0, 181,  36, 128,   0]], dtype=uint8)
>>> cv2.randu(im,(0),(99))         # uniform
array([[19, 53,  2, 86, 82],
       [86, 73, 40, 64, 78],
       [34, 20, 62, 80,  7],
       [24, 92, 37, 60, 72],
       [40, 12, 27, 33, 18]], dtype=uint8)

to apply it to an existing image, just generate noise in the desired range, and add it:

img = ...
noise = ...

image = img + noise

Postfix is installed but how do I test it?

(I just got this working, with my main issue being that I don't have a real internet hostname, so answering this question in case it helps someone)

You need to specify a hostname with HELO. Even so, you should get an error, so Postfix is probably not running.

Also, the => is not a command. The '.' on a single line without any text around it is what tells Postfix that the entry is complete. Here are the entries I used:

telnet localhost 25
(says connected)
(returns a bunch of 250 codes)
MAIL FROM: [email protected]
RCPT TO: (use a real email address you want to send to)
DATA (type whatever you want on muliple lines)
. (this on a single line tells Postfix that the DATA is complete)

You should get a response like:

250 2.0.0 Ok: queued as 6E414C4643A

The email will probably end up in a junk folder. If it is not showing up, then you probably need to setup the 'Postfix on hosts without a real Internet hostname'. Here is the breakdown on how I completed that step on my Ubuntu box:

sudo vim /etc/postfix/
smtp_generic_maps = hash:/etc/postfix/generic (add this line somewhere)
(edit or create the file 'generic' if it doesn't exist)
sudo vim /etc/postfix/generic
(add these lines, I don't think it matters what names you use, at least to test)
[email protected]             [email protected]
[email protected]             [email protected]
@localdomain.local                [email protected]
then run:
postmap /etc/postfix/generic (this needs to be run whenever you change the 
generic file)

Happy Trails

How can I select checkboxes using the Selenium Java WebDriver?

Solution for C#

    IWebElement TargetElement = driver.FindElement(By.XPath(xPathVal));
    if (!TargetElement.Selected)
catch (Exception e)

Empty brackets '[]' appearing when using .where

A good bet is to utilize Rails' Arel SQL manager, which explicitly supports case-insensitive ActiveRecord queries:

t = Guide.arel_table Guide.where(t[:title].matches('%attack')) 

Here's an interesting blog post regarding the portability of case-insensitive queries using Arel. It's worth a read to understand the implications of utilizing Arel across databases.

Accessing variables from other functions without using global variables

What you're looking for is technically known as currying.

function getMyCallback(randomValue)
    return function(otherParam)
        return randomValue * otherParam //or whatever it is you are doing.


var myCallback = getMyCallBack(getRand())


The above isn't exactly a curried function but it achieves the result of maintaining an existing value without adding variables to the global namespace or requiring some other object repository for it.

How can I convert a comma-separated string to an array?

The split() method is used to split a string into an array of substrings, and returns the new array.

var array = string.split(',');

Mockito verify order / sequence of method calls

Note that you can also use the InOrder class to verify that various methods are called in order on a single mock, not just on two or more mocks.

Suppose I have two classes Foo and Bar:

public class Foo {
  public void first() {}
  public void second() {}

public class Bar {
  public void firstThenSecond(Foo foo) {

I can then add a test class to test that Bar's firstThenSecond() method actually calls first(), then second(), and not second(), then first(). See the following test code:

public class BarTest {
  public void testFirstThenSecond() {
    Bar bar = new Bar();
    Foo mockFoo = Mockito.mock(Foo.class);

    InOrder orderVerifier = Mockito.inOrder(mockFoo);
    // These lines will PASS

    // These lines will FAIL
    // orderVerifier.verify(mockFoo).second();
    // orderVerifier.verify(mockFoo).first();

How do I put my website's logo to be the icon image in browser tabs?

Add a icon file named "favicon.ico" to the root of your website.

How to use ng-if to test if a variable is defined

Try this:


How do I get a list of installed CPAN modules?

Here a script which would do the trick:

use ExtUtils::Installed;

my $inst = ExtUtils::Installed->new();
my @modules = $inst->modules();
foreach $module (@modules){
       print $module ." - ". $inst->version($module). "\n";

=head1 ABOUT

This scripts lists installed cpan modules using the ExtUtils modules

=head1 FORMAT

Prints each module in the following format
<name> - <version>


How do you set CMAKE_C_COMPILER and CMAKE_CXX_COMPILER for building Assimp for iOS?


  1. Sometimes the project is created before installing g++. So install g++ first and then recreate your project. This worked for me.
  2. Paste the following line in CMakeCache.txt: CMAKE_CXX_COMPILER:FILEPATH=/usr/bin/c++

Note the path to g++ depends on OS. I have used my fedora path obtained using which g++

ORACLE convert number to string

Using the FM format model modifier to get close, as you won't get the trailing zeros after the decimal separator; but you will still get the separator itself, e.g. 50.. You can use rtrim to get rid of that:

select to_char(a, '99D90'),
    to_char(a, '90D90'),
    to_char(a, 'FM90D99'),
    rtrim(to_char(a, 'FM90D99'), to_char(0, 'D'))
from (
    select 50 a from dual
    union all select 50.57 from dual
    union all select 5.57 from dual
    union all select 0.35 from dual
    union all select 0.4 from dual
order by a;

------ ------ ------ ------
   .35   0.35 0.35   0.35
   .40   0.40 0.4    0.4
  5.57   5.57 5.57   5.57
 50.00  50.00 50.    50
 50.57  50.57 50.57  50.57

Note that I'm using to_char(0, 'D') to generate the character to trim, to match the decimal separator - so it looks for the same character, , or ., as the first to_char adds.

The slight downside is that you lose the alignment. If this is being used elsewhere it might not matter, but it does then you can also wrap it in an lpad, which starts to make it look a bit complicated:

lpad(rtrim(to_char(a, 'FM90D99'), to_char(0, 'D')), 6)

------ ------ ------ ------ ------------------------
   .35   0.35 0.35   0.35     0.35
   .40   0.40 0.4    0.4       0.4
  5.57   5.57 5.57   5.57     5.57
 50.00  50.00 50.    50         50
 50.57  50.57 50.57  50.57   50.57

Static Vs. Dynamic Binding in Java

Well in order to understand how static and dynamic binding actually works? or how they are identified by compiler and JVM?

Let's take below example where Mammal is a parent class which has a method speak() and Human class extends Mammal, overrides the speak() method and then again overloads it with speak(String language).

public class OverridingInternalExample {

    private static class Mammal {
        public void speak() { System.out.println("ohlllalalalalalaoaoaoa"); }

    private static class Human extends Mammal {

        public void speak() { System.out.println("Hello"); }

        // Valid overload of speak
        public void speak(String language) {
            if (language.equals("Hindi")) System.out.println("Namaste");
            else System.out.println("Hello");

        public String toString() { return "Human Class"; }


    //  Code below contains the output and bytecode of the method calls
    public static void main(String[] args) {
        Mammal anyMammal = new Mammal();
        anyMammal.speak();  // Output - ohlllalalalalalaoaoaoa
        // 10: invokevirtual #4 // Method org/programming/mitra/exercises/OverridingInternalExample$Mammal.speak:()V

        Mammal humanMammal = new Human();
        humanMammal.speak(); // Output - Hello
        // 23: invokevirtual #4 // Method org/programming/mitra/exercises/OverridingInternalExample$Mammal.speak:()V

        Human human = new Human();
        human.speak(); // Output - Hello
        // 36: invokevirtual #7 // Method org/programming/mitra/exercises/OverridingInternalExample$Human.speak:()V

        human.speak("Hindi"); // Output - Namaste
        // 42: invokevirtual #9 // Method org/programming/mitra/exercises/OverridingInternalExample$Human.speak:(Ljava/lang/String;)V

When we compile the above code and try to look at the bytecode using javap -verbose OverridingInternalExample, we can see that compiler generates a constant table where it assigns integer codes to every method call and byte code for the program which I have extracted and included in the program itself (see the comments below every method call)

Program Bytecode

By looking at above code we can see that the bytecodes of humanMammal.speak(), human.speak() and human.speak("Hindi") are totally different (invokevirtual #4, invokevirtual #7, invokevirtual #9) because the compiler is able to differentiate between them based on the argument list and class reference. Because all of this get resolved at compile time statically that is why Method Overloading is known as Static Polymorphism or Static Binding.

But bytecode for anyMammal.speak() and humanMammal.speak() is same (invokevirtual #4) because according to compiler both methods are called on Mammal reference.

So now the question comes if both method calls have same bytecode then how does JVM know which method to call?

Well, the answer is hidden in the bytecode itself and it is invokevirtual instruction set. JVM uses the invokevirtual instruction to invoke Java equivalent of the C++ virtual methods. In C++ if we want to override one method in another class we need to declare it as virtual, But in Java, all methods are virtual by default because we can override every method in the child class (except private, final and static methods).

In Java, every reference variable holds two hidden pointers

  1. A pointer to a table which again holds methods of the object and a pointer to the Class object. e.g. [speak(), speak(String) Class object]
  2. A pointer to the memory allocated on the heap for that object’s data e.g. values of instance variables.

So all object references indirectly hold a reference to a table which holds all the method references of that object. Java has borrowed this concept from C++ and this table is known as virtual table (vtable).

A vtable is an array like structure which holds virtual method names and their references on array indices. JVM creates only one vtable per class when it loads the class into memory.

So whenever JVM encounter with a invokevirtual instruction set, it checks the vtable of that class for the method reference and invokes the specific method which in our case is the method from a object not the reference.

Because all of this get resolved at runtime only and at runtime JVM gets to know which method to invoke, that is why Method Overriding is known as Dynamic Polymorphism or simply Polymorphism or Dynamic Binding.

You can read it more details on my article How Does JVM Handle Method Overloading and Overriding Internally.

row-level trigger vs statement-level trigger

if you want to execute the statement when number of rows are modified then it can be possible by statement level triggers.. viseversa... when you want to execute your statement each modification on your number of rows then you need to go for row level triggers..

for example: statement level triggers works for when table is modified..then more number of records are effected. and row level triggers works for when each row updation or modification..

Difference in Months between two dates in JavaScript

function monthDiff(date1, date2, countDays) {

  countDays = (typeof countDays !== 'undefined') ?  countDays : false;

  if (!date1 || !date2) {
    return 0;

  let bigDate = date1;
  let smallDate = date2;

  if (date1 < date2) {
    bigDate = date2;
    smallDate = date1;

  let monthsCount = (bigDate.getFullYear() - smallDate.getFullYear()) * 12 + (bigDate.getMonth() - smallDate.getMonth());

  if (countDays && bigDate.getDate() < smallDate.getDate()) {

  return monthsCount;

Unresolved Import Issues with PyDev and Eclipse

class A:
from com.jbk.KD import A;
class B:


THIS works perfectly file for me

Another example is
from com.jbk.scenarios.objectcreation.settings import _init
from com.jbk.scenarios.objectcreation.subfile import stuff

def _init():
def stuff():

How can I create a Windows .exe (standalone executable) using Java/Eclipse?

Typical Java programs compile into .jar files, which can be executed like .exe files provided the target machine has Java installed and that Java is in its PATH. From Eclipse you use the Export menu item from the File menu.

indexOf Case Sensitive?

 static string Search(string factMessage, string b)

            int index = factMessage.IndexOf(b, StringComparison.CurrentCultureIgnoreCase);
            string line = null;
            int i = index;
            if (i == -1)
            { return "not matched"; }
                while (factMessage[i] != ' ')
                    line = line + factMessage[i];

                return line;


What does git push -u mean?

This is no longer up-to-date!

Push.default is unset; its implicit value has changed in
Git 2.0 from 'matching' to 'simple'. To squelch this message
and maintain the traditional behavior, use:

  git config --global push.default matching

To squelch this message and adopt the new behavior now, use:

  git config --global push.default simple

When push.default is set to 'matching', git will push local branches
to the remote branches that already exist with the same name.

Since Git 2.0, Git defaults to the more conservative 'simple'
behavior, which only pushes the current branch to the corresponding
remote branch that 'git pull' uses to update the current branch.

Displaying a vector of strings in C++

You have to insert the elements using the insert method present in vectors STL, check the below program to add the elements to it, and you can use in the same way in your program.

#include <iostream>
#include <vector>
#include <string.h>

int main ()
  std::vector<std::string> myvector ;
  std::vector<std::string>::iterator it;

   it = myvector.begin();
  std::string myarray [] = { "Hi","hello","wassup" };
  myvector.insert (myvector.begin(), myarray, myarray+3);

  std::cout << "myvector contains:";
  for (it=myvector.begin(); it<myvector.end(); it++)
    std::cout << ' ' << *it;
    std::cout << '\n';

  return 0;

Can I use a min-height for table, tr or td?

In CSS 2.1, the effect of 'min-height' and 'max-height' on tables, inline tables, table cells, table rows, and row groups is undefined.

So try wrapping the content in a div, and give the div a min-height jsFiddle here

<table cellspacing="0" cellpadding="0" border="0" style="width:300px">
                <div style="min-height: 100px; background-color: #ccc">
                    Hello World !
                <div style="min-height: 100px; background-color: #f00">
                    Good Morning !

How to export table as CSV with headings on Postgresql?

The COPY command isn't what is restricted. What is restricted is directing the output from the TO to anywhere except to STDOUT. However, there is no restriction on specifying the output file via the \o command.

\o '/tmp/products_199.csv';

Giving a border to an HTML table row, <tr>

Absolutely! Just use

<tr style="outline: thin solid">

on which ever row you like. Here's a fiddle.

Of course, as people have mentioned, you can do this via an id, or class, or some other means if you wish.

How to use Google Translate API in my Java application?

Use java-google-translate-text-to-speech instead of Google Translate API v2 Java.

About java-google-translate-text-to-speech

Api unofficial with the main features of Google Translate in Java.

Easy to use!

It also provide text to speech api. If you want to translate the text "Hello!" in Romanian just write:

Translator translate = Translator.getInstance();
String text = translate.translate("Hello!", Language.ENGLISH, Language.ROMANIAN);
System.out.println(text); // "Buna ziua!" 

It's free!

As @r0ast3d correctly said:

Important: Google Translate API v2 is now available as a paid service. The courtesy limit for existing Translate API v2 projects created prior to August 24, 2011 will be reduced to zero on December 1, 2011. In addition, the number of requests your application can make per day will be limited.

This is correct: just see the official page:

Google Translate API is available as a paid service. See the Pricing and FAQ pages for details.

BUT, java-google-translate-text-to-speech is FREE!


I've created a sample application that demonstrates that this works. Try it here:

Select the top N values by group

There are at least 4 ways to do this thing, however,each has some difference. We using u_id to group and using lift value to order/sort

1 dplyr traditional way

top10_final_subset1 = final_subset %>% arrange(desc(lift)) %>% group_by(u_id) %>% slice(1:10)

and if you switch the order of arrange(desc(lift)) and group_by(u_id) the result is essential the same.And if there is tie for equal lift value,it will slice to make sure each group has no more than 10 values, if you only have 5 lift value in the group, it will only gives you 5 results for that group.

2 dplyr topN way

top10_final_subset2 = final_subset %>% group_by(u_id) %>% top_n(10,lift)

this one if you have tie in lift value, say 15 same lift for the same u_id, you will got all 15 observations

3 data.table tail way

final_subset = data.table(final_subset,key = "lift")
top10_final_subset3 = final_subset[,tail(.SD,10),,by = c("u_id")]

It has the same row numbers as the first way, however, there are some rows are different, I guess they are using diff random algorithm dealing with tie.

4 data.table .SD way

top10_final_subset4 = final_subset[,.SD[order(lift,decreasing = TRUE),][1:10],by = "u_id"]

This way is the most "uniform" way,if in a group there are only 5 observation it will repeat value to make it to 10 observations and if there are ties it will still slice and only hold for 10 observations.

HTTPS connections over proxy servers

TLS/SSL (The S in HTTPS) guarantees that there are no eavesdroppers between you and the server you are contacting, i.e. no proxies. Normally, you use CONNECT to open up a TCP connection through the proxy. In this case, the proxy will not be able to cache, read, or modify any requests/responses, and therefore be rather useless.

If you want the proxy to be able to read information, you can take the following approach:

  1. Client starts HTTPS session
  2. Proxy transparently intercepts the connection and returns an ad-hoc generated(possibly weak) certificate Ka, signed by a certificate authority that is unconditionally trusted by the client.
  3. Proxy starts HTTPS session to target
  4. Proxy verifies integrity of SSL certificate; displays error if the cert is not valid.
  5. Proxy streams content, decrypts it and re-encrypts it with Ka
  6. Client displays stuff

An example is Squid's SSL bump. Similarly, burp can be configured to do this. This has also been used in a less-benign context by an Egyptian ISP.

Note that modern websites and browsers can employ HPKP or built-in certificate pins which defeat this approach.

Reading serial data in realtime in Python

You need to set the timeout to "None" when you open the serial port:

ser = serial.Serial(**bco_port**, timeout=None, baudrate=115000, xonxoff=False, rtscts=False, dsrdtr=False) 

This is a blocking command, so you are waiting until you receive data that has newline (\n or \r\n) at the end: line = ser.readline()

Once you have the data, it will return ASAP.

How to find out when an Oracle table was updated the last time

Since you are on 10g, you could potentially use the ORA_ROWSCN pseudocolumn. That gives you an upper bound of the last SCN (system change number) that caused a change in the row. Since this is an increasing sequence, you could store off the maximum ORA_ROWSCN that you've seen and then look only for data with an SCN greater than that.

By default, ORA_ROWSCN is actually maintained at the block level, so a change to any row in a block will change the ORA_ROWSCN for all rows in the block. This is probably quite sufficient if the intention is to minimize the number of rows you process multiple times with no changes if we're talking about "normal" data access patterns. You can rebuild the table with ROWDEPENDENCIES which will cause the ORA_ROWSCN to be tracked at the row level, which gives you more granular information but requires a one-time effort to rebuild the table.

Another option would be to configure something like Change Data Capture (CDC) and to make your OCI application a subscriber to changes to the table, but that also requires a one-time effort to configure CDC.

ng-repeat: access key and value for each object in array of objects

Here is another way, without the need for nesting the repeaters.

From the Angularjs docs:

It is possible to get ngRepeat to iterate over the properties of an object using the following syntax:

<div ng-repeat="(key, value) in steps"> {{key}} : {{value}} </div>

Make page to tell browser not to cache/preserve input values

This worked for me in newer browsers:


Please add a @Pipe/@Directive/@Component annotation. Error

I was trying to use BrowserModule in a shared module (import and export). That was not allowed so instead I had to use the CommonModule instead and it worked.

angular.service vs angular.factory

app.factory('fn', fn) vs. app.service('fn',fn)


With factories, Angular will invoke the function to get the result. It is the result that is cached and injected.

 var obj = fn();
 return obj;

With services, Angular will invoke the constructor function by calling new. The constructed function is cached and injected.

  var obj = new fn();
  return obj;


Factories typically return an object literal because the return value is what's injected into controllers, run blocks, directives, etc

  app.factory('fn', function(){
         var foo = 0;
         var bar = 0;
         function setFoo(val) {
               foo = val;
         function setBar (val){
               bar = val;
         return {
                setFoo: setFoo,
                serBar: setBar

Service functions typically do not return anything. Instead, they perform initialization and expose functions. Functions can also reference 'this' since it was constructed using 'new'.

app.service('fn', function () {
         var foo = 0;
         var bar = 0;
         this.setFoo = function (val) {
               foo = val;
         this.setBar = function (val){
               bar = val;


When it comes to using factories or services they are both very similar. They are injected into a controllers, directives, run block, etc, and used in client code in pretty much the same way. They are also both singletons - meaning the same instance is shared between all places where the service/factory is injected.

So which should you prefer? Either one - they are so similar that the differences are trivial. If you do choose one over the other, just be aware how they are constructed, so that you can implement them properly.

Blocks and yields in Ruby

Yes, it is a bit puzzling at first.

In Ruby, methods may receive a code block in order to perform arbitrary segments of code.

When a method expects a block, it invokes it by calling the yield function.

This is very handy, for instance, to iterate over a list or to provide a custom algorithm.

Take the following example:

I'm going to define a Person class initialized with a name, and provide a do_with_name method that when invoked, would just pass the name attribute, to the block received.

class Person 
    def initialize( name ) 
         @name = name

    def do_with_name 
        yield( @name ) 

This would allow us to call that method and pass an arbitrary code block.

For instance, to print the name we would do:

person ="Oscar")

#invoking the method passing a block
person.do_with_name do |name|
    puts "Hey, his name is #{name}"

Would print:

Hey, his name is Oscar

Notice, the block receives, as a parameter, a variable called name (N.B. you can call this variable anything you like, but it makes sense to call it name). When the code invokes yield it fills this parameter with the value of @name.

yield( @name )

We could provide another block to perform a different action. For example, reverse the name:

#variable to hold the name reversed
reversed_name = ""

#invoke the method passing a different block
person.do_with_name do |name| 
    reversed_name = name.reverse

puts reversed_name

=> "racsO"

We used exactly the same method (do_with_name) - it is just a different block.

This example is trivial. More interesting usages are to filter all the elements in an array:

 days = ["monday", "tuesday", "wednesday", "thursday", "friday"]  

 # select those which start with 't' do | item |
     item.match /^t/

=> ["tuesday", "thursday"]

Or, we can also provide a custom sort algorithm, for instance based on the string size:

 days.sort do |x,y|
    x.size <=> y.size

=> ["monday", "friday", "tuesday", "thursday", "wednesday"]

I hope this helps you to understand it better.

BTW, if the block is optional you should call it like:

yield(value) if block_given?

If is not optional, just invoke it.


@hmak created a for these examples:

How to display raw html code in PRE or something like it but without escaping it

xmp is the way to go, i.e.:

  # your code...

jquery animate .css

You could opt for a pure CSS solution:

#hfont1 {
    transition: color 1s ease-in-out;
    -moz-transition: color 1s ease-in-out; /* FF 4 */
    -webkit-transition: color 1s ease-in-out; /* Safari & Chrome */
    -o-transition: color 1s ease-in-out; /* Opera */

MongoDB what are the default user and password?

For MongoDB earlier than 2.6, the command to add a root user is addUser (e.g.)


PHP, display image with Header()

Browsers make their best guess with the data they receive. This works for markup (which Websites often get wrong) and other media content. A program that receives a file can often figure out what its received regardless of the MIME content type it's been told.

This isn't something you should rely on however. It's recommended you always use the correct MIME content.

How do I build a graphical user interface in C++?

OS independent algorithm "Creating GUI applications in C++ in three steps":

  1. Install Qt Creator

    enter image description here

  2. Create new project (Qt Widgets Application)

    enter image description here

  3. Build it.

Congratulations, you've got your first GUI in C++.

Now you're ready to read a lot of documentation to create something more complicate than "Hello world" GUI application.

Disable elastic scrolling in Safari

You could check if the scroll-offsets are in the bounds. If they go beyond, set them back.

var scrollX = 0;
var scrollY = 0;
var scrollMinX = 0;
var scrollMinY = 0;
var scrollMaxX = document.body.scrollWidth - window.innerWidth;
var scrollMaxY = document.body.scrollHeight - window.innerHeight;

// make sure that we work with the correct dimensions
window.addEventListener('resize', function () {
  scrollMaxX = document.body.scrollWidth - window.innerWidth;
  scrollMaxY = document.body.scrollHeight - window.innerHeight;
}, false);

// where the magic happens
window.addEventListener('scroll', function () {
  scrollX = window.scrollX;
  scrollY = window.scrollY;

  if (scrollX <= scrollMinX) scrollTo(scrollMinX, window.scrollY);
  if (scrollX >= scrollMaxX) scrollTo(scrollMaxX, window.scrollY);

  if (scrollY <= scrollMinY) scrollTo(window.scrollX, scrollMinY);
  if (scrollY >= scrollMaxY) scrollTo(window.scrollX, scrollMaxY);
}, false);

How correctly produce JSON by RESTful web service?

Use this annotation

@RequestMapping(value = "/url", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON})

How can I convert radians to degrees with Python?

I also like to define my own functions that take and return arguments in degrees rather than radians. I am sure there some capitalization purest who don't like my names, but I just use a capital first letter for my custom functions. The definitions and testing code are below.

#Definitions for trig functions using degrees.
def Cos(a):
    return cos(radians(a))
def Sin(a):
    return sin(radians(a))
def Tan(a):
    return tan(radians(a))
def ArcTan(a):
    return degrees(arctan(a))
def ArcSin(a):
    return degrees(arcsin(a))
def ArcCos(a):
    return degrees(arccos(a))

#Testing Code

Note that I have imported math (or numpy) into the namespace with

from math import *

Also note, that my functions are in the namespace in which they were defined. For instance,


does not exist.

How to downgrade Java from 9 to 8 on a MACOS. Eclipse is not running with Java 9

If you have multiple Java versions installed on your Mac, here's a quick way to switch the default version using Terminal. In this example, I am going to switch Java 10 to Java 8.

$ java -version
java version "10.0.1" 2018-04-17
Java(TM) SE Runtime Environment 18.3 (build 10.0.1+10)
Java HotSpot(TM) 64-Bit Server VM 18.3 (build 10.0.1+10, mixed mode)

$ /usr/libexec/java_home -V
Matching Java Virtual Machines (2):
    10.0.1, x86_64: "Java SE 10.0.1"    /Library/Java/JavaVirtualMachines/jdk-10.0.1.jdk/Contents/Home
    1.8.0_171, x86_64:  "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_171.jdk/Contents/Home


Then, in your .bash_profile add the following.

# Java 8
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_171.jdk/Contents/Home

Now if you try java -version again, you should see the version you want.

$ java -version
java version "1.8.0_171"
Java(TM) SE Runtime Environment (build 1.8.0_171-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.171-b11, mixed mode)

setBackground vs setBackgroundDrawable (Android)

This works for me: View view is your editText, spinner...etc. And int drawable is your drawable route example (R.drawable.yourDrawable)

 public void verifyDrawable (View view, int drawable){

        int sdk = Build.VERSION.SDK_INT;

        if(sdk < Build.VERSION_CODES.JELLY_BEAN) {
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {

Why do some functions have underscores "__" before and after the function name?

This convention is used for special variables or methods (so-called “magic method”) such as __init__ and __len__. These methods provides special syntactic features or do special things.

For example, __file__ indicates the location of Python file, __eq__ is executed when a == b expression is executed.

A user of course can make a custom special method, which is a very rare case, but often might modify some of the built-in special methods (e.g. you should initialize the class with __init__ that will be executed at first when an instance of a class is created).

class A:
    def __init__(self, a):  # use special method '__init__' for initializing
        self.a = a
    def __custom__(self):  # custom special method. you might almost do not use it

Google Maps API v3 adding an InfoWindow to each marker

You can use this in event:

google.maps.event.addListener(marker, 'click', function() {  
    // this = marker
    var marker_map = this.getMap();;
    //, this);
    // Note: If you call open() without passing a marker, the InfoWindow will use the position specified upon construction through the InfoWindowOptions object literal.

How to create batch file in Windows using "start" with a path and command with spaces

Escaping the path with apostrophes is correct, but the start command takes a parameter containing the title of the new window. This parameter is detected by the surrounding apostrophes, so your application is not executed.

Try something like this:

start "Dummy Title" "c:\path with spaces\app.exe" param1 "param with spaces"

Regular Expression: Allow letters, numbers, and spaces (with at least one letter or number)

$("#ValuationName").bind("keypress", function (event) {
    if (event.charCode!=0) {
        var regex = new RegExp("^[a-zA-Z ]+$");
        var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
        if (!regex.test(key)) {
            return false;

How do you load custom UITableViewCells from Xib files?

Here's the class method that I've been using for creating custom cells out of XIBs:

+ (CustomCell*) createNewCustomCellFromNib {

    NSArray* nibContents = [[NSBundle mainBundle]
                            loadNibNamed:@"CustomCell" owner:self options:NULL];

    NSEnumerator *nibEnumerator = [nibContents objectEnumerator];
    CustomCell *customCell= nil;
    NSObject* nibItem = nil;

    while ( (nibItem = [nibEnumerator nextObject]) != nil) {

        if ( [nibItem isKindOfClass: [CustomCell class]]) {
            customCell = (CustomCell*) nibItem;

            if ([customCell.reuseIdentifier isEqualToString: @"CustomCell"]) {
                break; // we have a winner
                fuelEntryCell = nil;
    return customCell;

Then, in the XIB, I set the class name, and reuse identifier. After that, I can just call that method in my view controller instead of the

[[UITableViewCell] alloc] initWithFrame:]

It's plenty fast enough, and being used in two of my shipping applications. It's more reliable than calling [nib objectAtIndex:0], and in my mind at least, more reliable than Stephan Burlot's example because you're guaranteed to only grab a view out of a XIB that is the right type.

Connect to external server by using phpMyAdmin

You can use the phpmyadmin setup page (./phpmyadmin/setup) to generate a new config file ( for you. This file is found at the root of the phpMyAdmin directory.

Just create the config folder as prompted in setup page, add your servers, then click the 'Save' button. This will create a new config file in the config folder you just created.

You now have only to move the file to the main phpMyAdmin folder, or just copy the lines concerning the servers if you got some old configuration done already you'd like to keep.

Don't forget to delete the config folder afterwards.

How to shift a block of code left/right by one space in VSCode?

No need to use any tool for that

  1. Set Tab Spaces to 1.
  2. Select whole block of code and then press Shift + Tab

Shift + Tab = Shift text right to left

How do I drop a function if it already exists?

Here's my take on this:

if(object_id(N'[dbo].[fn_Nth_Pos]', N'FN')) is not null
    drop function [dbo].[fn_Nth_Pos];
CREATE FUNCTION [dbo].[fn_Nth_Pos]
    @find char, --char to find
    @search varchar(max), --string to process   
    @nth int --occurrence   
    declare @pos int --position of nth occurrence
    set @pos = 0

    while(@nth > 0)
        set @pos = charindex(@find,@search,@pos+1)
        set @nth = @nth - 1

    return @pos

declare @files table(name varchar(max));

insert into @files(name) values('abc_1_2_3_4.gif');
insert into @files(name) values('zzz_12_3_3_45.gif');

    dbo.fn_Nth_Pos('_',, 1) as [1st],
    dbo.fn_Nth_Pos('_',, 2) as [2nd],
    dbo.fn_Nth_Pos('_',, 3) as [3rd],
    dbo.fn_Nth_Pos('_',, 4) as [4th]
    @files f;

How can I get npm start at a different directory?

Below Command where project is a folder which contains package.json file

npm run --prefix project ${COMMAND}

is working as well. Useful in Docker based applications.

How to delete multiple rows in SQL where id = (x to y)

,@ERRFLAG  CHAR(1) = '0' OUTPUT    



DELETE tb_SampleTest
        CODE IN(
            SELECT Item.value('.', 'VARCHAR(20)')
            FROM  @CODE.nodes('RecordList/ID') AS x(Item)

    SET @ERRFLAG = 200


Get string value delete


ADB not responding. You can wait more,or kill "adb.exe" process manually and click 'Restart'

Check if any service is listening on port 5037, and kill it. You can use lsof for this:

$ lsof -i :5037
$ kill <PID Process>

Then try

$ adb start-server
* daemon not running. starting it now on port 5037 *
* daemon started successfully *

This solved my problem.

Unrecognized SSL message, plaintext connection? Exception Unrecognized SSL message, plaintext connection?

You should have a local SMTP domain name that will contact the mail server and establishes a new connection as well you should change the SSL property in your programming below Unrecognized SSL message, plaintext connection

 props.put("mail.smtp.socketFactory.fallback", "true"); // Should be true

XMLHttpRequest cannot load file. Cross origin requests are only supported for HTTP

This error is happening because you are just opening html documents directly from the browser. To fix this you will need to serve your code from a webserver and access it on localhost. If you have Apache setup, use it to serve your files. Some IDE's have built in web servers, like JetBrains IDE's, Eclipse...

If you have Node.Js setup then you can use http-server. Just run npm install http-server -g and you will be able to use it in terminal like http-server C:\location\to\app. Kirill Fuchs

Jupyter notebook not running code. Stuck on In [*]

I fixed this issue

just only type this command: jupyter notebook --no-browser

It will show you the path then copy and paste on Jupyter Notebook browser

The code will be executed in IPython Notebook Python 3

how to increase the limit for max.print in R

Use the options command, e.g. options(max.print=1000000).

See ?options:

 ‘max.print’: integer, defaulting to ‘99999’.  ‘print’ or ‘show’
      methods can make use of this option, to limit the amount of
      information that is printed, to something in the order of
      (and typically slightly less than) ‘max.print’ _entries_.

Convert javascript array to string

I needed an array to became a String rappresentation of an array I mean I needed that

var a = ['a','b','c'];
//became a "real" array string-like to pass on query params so was easy to do:
JSON.stringify(a); //-->"['a','b','c']"

maybe someone need it :)

Find all elements with a certain attribute value in jquery

Although it doesn't precisely answer the question, I landed here when searching for a way to get the collection of elements (potentially different tag names) that simply had a given attribute name (without filtering by attribute value). I found that the following worked well for me:


Hope that helps somebody who happens to land on this page looking for the same thing that I was :).

Update: It appears that the asterisk is not required, i.e. based on some basic tests, the following seems to be equivalent to the above (thanks to Matt for pointing this out):


set pythonpath before import statements

As also noted in the docs here.
Go to Python X.X/Lib and add these lines to the there,

import sys

This changes your sys.path so that on every load, it will have that value in it..

As stated here about,

This module is automatically imported during initialization. Importing this module will append site-specific paths to the module search path and add a few builtins.

For other possible methods of adding some path to sys.path see these docs

curl usage to get header

You need to add the -i flag to the first command, to include the HTTP header in the output. This is required to print headers.

curl -X HEAD -i

More here:

how to implement a pop up dialog box in iOS

Updated for iOS 8.0

Since iOS 8.0, you will need to use UIAlertController as the following:

    UIAlertController* alert = [UIAlertController

    UIAlertAction* defaultAction = [UIAlertAction 
          actionWithTitle:@"OK" style:UIAlertActionStyleDefault
         handler:^(UIAlertAction * action) {}];

    [alert addAction:defaultAction];
    [self presentViewController:alert animated:YES completion:nil];

Where self in my example is a UIViewController, which implements "presentViewController" method for a popup.


How to serialize/deserialize to `Dictionary<int, string>` from custom XML not using XElement?

I use serializable classes for the WCF communication between different modules. Below is an example of serializable class which serves as DataContract as well. My approach is to use the power of LINQ to convert the Dictionary into out-of-the-box serializable List<> of KeyValuePair<>:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.Serialization;
    using System.Xml.Serialization;

    namespace MyFirm.Common.Data
        public class SerializableClassX
            // since the Dictionary<> class is not serializable,
            // we convert it to the List<KeyValuePair<>>
            public Dictionary<string, int> DictionaryX 
                    return  SerializableList == null ? 
                            null :
                            SerializableList.ToDictionary(item => item.Key, item => item.Value);

                    SerializableList =  value == null ?
                                        null :

            public List<KeyValuePair<string, int>> SerializableList { get; set; }

The usage is straightforward - I assign a dictionary to my data object's dictionary field - DictionaryX. The serialization is supported inside the SerializableClassX by conversion of the assigned dictionary into the serializable List<> of KeyValuePair<>:

    // create my data object
    SerializableClassX SerializableObj = new SerializableClassX(param);

    // this will call the DictionaryX.set and convert the '
    // new Dictionary into SerializableList
    SerializableObj.DictionaryX = new Dictionary<string, int>
        {"Key1", 1},
        {"Key2", 2},

How do I get a computer's name and IP address using VB.NET?

Private Function GetIPv4Address() As String
    GetIPv4Address = String.Empty
    Dim strHostName As String = System.Net.Dns.GetHostName()
    Dim iphe As System.Net.IPHostEntry = System.Net.Dns.GetHostEntry(strHostName)

    For Each ipheal As System.Net.IPAddress In iphe.AddressList
        If ipheal.AddressFamily = System.Net.Sockets.AddressFamily.InterNetwork Then
            GetIPv4Address = ipheal.ToString()
        End If

End Function

Get the Highlighted/Selected text

Getting the text the user has selected is relatively simple. There's no benefit to be gained by involving jQuery since you need nothing other than the window and document objects.

function getSelectionText() {
    var text = "";
    if (window.getSelection) {
        text = window.getSelection().toString();
    } else if (document.selection && document.selection.type != "Control") {
        text = document.selection.createRange().text;
    return text;

If you're interested in an implementation that will also deal with selections in <textarea> and texty <input> elements, you could use the following. Since it's now 2016 I'm omitting the code required for IE <= 8 support but I've posted stuff for that in many places on SO.

function getSelectionText() {_x000D_
    var text = "";_x000D_
    var activeEl = document.activeElement;_x000D_
    var activeElTagName = activeEl ? activeEl.tagName.toLowerCase() : null;_x000D_
    if (_x000D_
      (activeElTagName == "textarea") || (activeElTagName == "input" &&_x000D_
      /^(?:text|search|password|tel|url)$/i.test(activeEl.type)) &&_x000D_
      (typeof activeEl.selectionStart == "number")_x000D_
    ) {_x000D_
        text = activeEl.value.slice(activeEl.selectionStart, activeEl.selectionEnd);_x000D_
    } else if (window.getSelection) {_x000D_
        text = window.getSelection().toString();_x000D_
    return text;_x000D_
document.onmouseup = document.onkeyup = document.onselectionchange = function() {_x000D_
  document.getElementById("sel").value = getSelectionText();_x000D_
<textarea id="sel" rows="3" cols="50"></textarea>_x000D_
<p>Please select some text.</p>_x000D_
<input value="Some text in a text input">_x000D_
<input type="search" value="Some text in a search input">_x000D_
<input type="tel" value="4872349749823">_x000D_
<textarea>Some text in a textarea</textarea>

How to compile a c++ program in Linux?

As the other answers say, use g++ instead of gcc.

Or use make: make hi

Find full path of the Python interpreter?

sys.executable contains full path of the currently running Python interpreter.

import sys


which is now documented here

How to semantically add heading to a list

I put the heading inside the ul. There's no rule that says UL must contain only LI elements.

How to upgrade Angular CLI to the latest version

The following approach worked for me:

npm uninstall -g @angular/cli


npm cache verify


npm install -g @angular/cli

I work on Windows 10, sometimes I had to use: npm cache clean --force as well. You don't need to do if you don't have any problem during the installation.

How to import NumPy in the Python shell

On Debian/Ubuntu:

aptitude install python-numpy

On Windows, download the installer:

On other systems, download the tar.gz and run the following:

$ tar xfz numpy-n.m.tar.gz
$ cd numpy-n.m
$ python install

List of All Locales and Their Short Codes?

The importance of locales is that your environment/os can provide formatting functionality for all installed locales even if you don't know about them when you write your application. My Windows 7 system has 211 locales installed (listed below), so you wouldn't likely write any custom code or translation specific to this many locales.

The most important thing for various versions of English is in formatting numbers and dates. Other differences are significant to the extent that you want and able to cater to specific variations.


Error Installing Homebrew - Brew Command Not Found

nano ~/.profile

add these lines:

export PATH="$HOME/.linuxbrew/bin:$PATH"
export MANPATH="$HOME/.linuxbrew/share/man:$MANPATH"
export INFOPATH="$HOME/.linuxbrew/share/info:$INFOPATH"

save the file:

Ctrl + X then Y then Enter

then render the changes:

source ~/.profile

Hibernate dialect for Oracle Database 11g?

At least in case of EclipseLink 10g and 11g differ. Since 11g it is not recommended to use first_rows hint for pagination queries.

See "Is it possible to disable jpa hints per particular query". Such a query should not be used in 11g.

  SELECT /*+ FIRST_ROWS */ a.*, ROWNUM rnum  FROM (
  WHERE ROWNUM <= 10 )
WHERE rnum > 0;

But there can be other nuances.

Testing pointers for validity (C/C++)

It's unbelievable how much misleading information you can read in articles above...

And even in microsoft msdn documentation IsBadPtr is claimed to be banned. Oh well - I prefer working application rather than crashing. Even if term working might be working incorrectly (as long as end-user can continue with application).

By googling I haven't found any useful example for windows - found a solution for 32-bit apps,

but I need also to support 64-bit apps, so this solution did not work for me.

But I've harvested wine's source codes, and managed to cook similar kind of code which would work for 64-bit apps as well - attaching code here:

#include <typeinfo.h>   

typedef void (*v_table_ptr)();   

typedef struct _cpp_object   
    v_table_ptr*    vtable;   
} cpp_object;   

#ifndef _WIN64
typedef struct _rtti_object_locator
    unsigned int signature;
    int base_class_offset;
    unsigned int flags;
    const type_info *type_descriptor;
    //const rtti_object_hierarchy *type_hierarchy;
} rtti_object_locator;

typedef struct
    unsigned int signature;
    int base_class_offset;
    unsigned int flags;
    unsigned int type_descriptor;
    unsigned int type_hierarchy;
    unsigned int object_locator;
} rtti_object_locator;  


/* Get type info from an object (internal) */  
static const rtti_object_locator* RTTI_GetObjectLocator(void* inptr)  
    cpp_object* cppobj = (cpp_object*) inptr;  
    const rtti_object_locator* obj_locator = 0;   

    if (!IsBadReadPtr(cppobj, sizeof(void*)) &&   
        !IsBadReadPtr(cppobj->vtable - 1, sizeof(void*)) &&   
        !IsBadReadPtr((void*)cppobj->vtable[-1], sizeof(rtti_object_locator)))  
        obj_locator = (rtti_object_locator*) cppobj->vtable[-1];  

    return obj_locator;  

And following code can detect whether pointer is valid or not, you need probably to add some NULL checking:

    CTest* t = new CTest();
    //t = (CTest*) 0;
    //t = (CTest*) 0x12345678;

    const rtti_object_locator* ptr = RTTI_GetObjectLocator(t);  

#ifdef _WIN64
    char *base = ptr->signature == 0 ? (char*)RtlPcToFileHeader((void*)ptr, (void**)&base) : (char*)ptr - ptr->object_locator;
    const type_info *td = (const type_info*)(base + ptr->type_descriptor);
    const type_info *td = ptr->type_descriptor;
    const char* n =td->name();

This gets class name from pointer - I think it should be enough for your needs.

One thing which I'm still afraid is performance of pointer checking - in code snipet above there is already 3-4 API calls being made - might be overkill for time critical applications.

It would be good if someone could measure overhead of pointer checking compared for example to C#/managed c++ calls.

Calling a java method from c++ in Android

If it's an object method, you need to pass the object to CallObjectMethod:

jobject result = env->CallObjectMethod(obj, messageMe, jstr);

What you were doing was the equivalent of jstr.messageMe().

Since your is a void method, you should call:

env->CallVoidMethod(obj, messageMe, jstr);

If you want to return a result, you need to change your JNI signature (the ()V means a method of void return type) and also the return type in your Java code.

What is the difference between pull and clone in git?

In laymen language we can say:

  • Clone: Get a working copy of the remote repository.
  • Pull: I am working on this, please get me the new changes that may be updated by others.

Passing parameters on button action:@selector

I think the correct method should be : - (void)addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents

UIControl Reference

Where do you get your method from?

I see that your selector has an argument, that argument will be filled by the runtime system. It will send you back the button through that argument.

Your method should look like:

- (void)buttonPressed:(id)BUTTON_HERE { }

overlay opaque div over youtube iframe

Is the opaque overlay for aesthetic purposes?

If so, you can use:

#overlay {
        position: fixed;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        z-index: 50;
        background: #000;
        pointer-events: none;
        opacity: 0.8;
        color: #fff;

'pointer-events: none' will change the overlay behavior so that it can be physically opaque. Of course, this will only work in good browsers.

Xcode 10 Error: Multiple commands produce

Before I begin note that my project utilizes Carthage as a dependency manager.

None of the existing answers here resolved my issue. What did resolve the issue for me was the following.

First, I noticed that the build error pointed out one framework in particular. Next I filtered App Target > Build Phases for that framework. I noticed that that framework was present in both "Link Binary With Libraries" and "Embed Frameworks". Noting that none of the frameworks listed under "Embed Frameworks" were ones managed by Carthage I removed the framework in question from "Embed Frameworks". I then re-built my project and everything works fine including the functionality enabled by the framework in question.

glob exclude pattern

You can't exclude patterns with the glob function, globs only allow for inclusion patterns. Globbing syntax is very limited (even a [!..] character class must match a character, so it is an inclusion pattern for every character that is not in the class).

You'll have to do your own filtering; a list comprehension usually works nicely here:

files = [fn for fn in glob('somepath/*.txt') 
         if not os.path.basename(fn).startswith('eph')]

Want to show/hide div based on dropdown box selection

<script src="">
    $('#purpose').on('change', function() {
      if ( this.value == '1')
      else  if ( this.value == '2')
<select id='purpose'>
<option value="0">Personal use</option>
<option value="1">Business use</option>
<option value="2">Passing on to a client</option>
<div style='display:none;' id='business'>Business Name<br/>&nbsp;
    <input type='text' class='text' name='business' value size='20' />
    <input type='text' class='text' name='business' value size='20' />
<div style='display:none;' id='business_new'>Business Name<br/>&nbsp;
    <input type='text' class='text' name='business' value="1254" size='20' />
    <input type='text' class='text' name='business' value size='20' />

Sort a list of lists with a custom compare function

>>> l = [list(range(i, i+4)) for i in range(10,1,-1)]
>>> l
[[10, 11, 12, 13], [9, 10, 11, 12], [8, 9, 10, 11], [7, 8, 9, 10], [6, 7, 8, 9], [5, 6, 7, 8], [4, 5, 6, 7], [3, 4, 5, 6], [2, 3, 4, 5]]
>>> sorted(l, key=sum)
[[2, 3, 4, 5], [3, 4, 5, 6], [4, 5, 6, 7], [5, 6, 7, 8], [6, 7, 8, 9], [7, 8, 9, 10], [8, 9, 10, 11], [9, 10, 11, 12], [10, 11, 12, 13]]

The above works. Are you doing something different?

Notice that your key function is just sum; there's no need to write it explicitly.

How do I make a https post in Node Js without any third party module?

For example, like this:

const querystring = require('querystring');
const https = require('https');

var postData = querystring.stringify({
    'msg' : 'Hello World!'

var options = {
  hostname: '',
  port: 443,
  path: '/post.php',
  method: 'POST',
  headers: {
       'Content-Type': 'application/x-www-form-urlencoded',
       'Content-Length': postData.length

var req = https.request(options, (res) => {
  console.log('statusCode:', res.statusCode);
  console.log('headers:', res.headers);

  res.on('data', (d) => {

req.on('error', (e) => {


How to reverse an animation on mouse out after hover

Using transform in combination with transition works flawlessly for me:

.ani-grow {
    -webkit-transition: all 0.5s ease; 
    -moz-transition: all 0.5s ease; 
    -o-transition: all 0.5s ease; 
    -ms-transition: all 0.5s ease; 
    transition: all 0.5s ease; 
.ani-grow:hover {
    transform: scale(1.01);

How to stop VMware port error of 443 on XAMPP Control Panel v3.2.1

Say you let vmware use port 443, and use another ssl port in XAMPP Apache (httpd-ssl.conf) :

The red error will keep popping in XAMPP Control Panel. You also need to change the port in the XAMPP Control Panel configuration :

In XAMPP Control Panel, click the "Config" button (top-left). Then click "Service and Port Settings". There you can set the ports to match the ports used by Apache.

How can I connect to MySQL in Python 3 on Windows?


I have installed pip on my windows 7, with python 3.3 just pip install cymysql

(you don't need cython) quick and painless

LINQ-to-SQL vs stored procedures?

LINQ doesn't prohibit the use of stored procedures. I've used mixed mode with LINQ-SQL and LINQ-storedproc. Personally, I'm glad I don't have to write the stored procs....pwet-tu.

python .replace() regex

In order to replace text using regular expression use the re.sub function:

sub(pattern, repl, string[, count, flags])

It will replace non-everlaping instances of pattern by the text passed as string. If you need to analyze the match to extract information about specific group captures, for instance, you can pass a function to the string argument. more info here.


>>> import re
>>> re.sub(r'a', 'b', 'banana')

>>> re.sub(r'/\d+', '/{id}', '/andre/23/abobora/43435')

How to check if a variable is equal to one string or another string?

if var == 'stringone' or var == 'stringtwo':

'is' is used to check if the two references are referred to a same object. It compare the memory address. Apparently, 'stringone' and 'var' are different objects, they just contains the same string, but they are two different instances of the class 'str'. So they of course has two different memory addresses, and the 'is' will return False.

How to disable gradle 'offline mode' in android studio?

Gradle is in offline mode, which means that it won't go to the network to resolve dependencies.

Go to Preferences > Gradle and uncheck "Offline work".

How to write a file or data to an S3 object using boto3

Here's a nice trick to read JSON from s3:

import json, boto3
s3 = boto3.resource("s3").Bucket("bucket")
json.load_s3 = lambda f: json.load(s3.Object(key=f).get()["Body"])
json.dump_s3 = lambda obj, f: s3.Object(key=f).put(Body=json.dumps(obj))

Now you can use json.load_s3 and json.dump_s3 with the same API as load and dump

data = {"test":0}
json.dump_s3(data, "key") # saves json to s3://bucket/key
data = json.load_s3("key") # read json from s3://bucket/key

How can I get a list of all values in select box?

As per the DOM structure you can use below code:

var x = document.getElementById('mySelect');
     var txt = "";
     var val = "";
     for (var i = 0; i < x.length; i++) {
         txt +=x[i].text + ",";
         val +=x[i].value + ",";

How to remove part of a string before a ":" in javascript?

There is no need for jQuery here, regular JavaScript will do:

var str = "Abc: Lorem ipsum sit amet";
str = str.substring(str.indexOf(":") + 1);

Or, the .split() and .pop() version:

var str = "Abc: Lorem ipsum sit amet";
str = str.split(":").pop();

Or, the regex version (several variants of this):

var str = "Abc: Lorem ipsum sit amet";
str = /:(.+)/.exec(str)[1];

batch file to list folders within a folder to one level

I tried this command to display the list of files in the directory.

dir /s /b > List.txt

In the file it displays the list below.

C:\Program Files (x86)\Cisco Systems\Cisco Jabber\XmppMgr.dll

C:\Program Files (x86)\Cisco Systems\Cisco Jabber\XmppSDK.dll

C:\Program Files (x86)\Cisco Systems\Cisco Jabber\accessories\Plantronics

C:\Program Files (x86)\Cisco Systems\Cisco Jabber\accessories\SennheiserJabberPlugin.dll

C:\Program Files (x86)\Cisco Systems\Cisco Jabber\accessories\Logitech\LogiUCPluginForCisco

C:\Program Files (x86)\Cisco Systems\Cisco Jabber\accessories\Logitech\LogiUCPluginForCisco\lucpcisco.dll

What is want to do is only to display sub-directory not the full directory path.

Just like this:

Cisco Jabber\XmppMgr.dll Cisco Jabber\XmppSDK.dll

Cisco Jabber\accessories\JabraJabberPlugin.dll

Cisco Jabber\accessories\Logitech

Cisco Jabber\accessories\Plantronics

Cisco Jabber\accessories\SennheiserJabberPlugin.dll

How do I make a textbox that only accepts numbers?

int Number;
bool isNumber;
isNumber = int32.TryPase(textbox1.text, out Number);

if (!isNumber)
    (code if not an integer);
    (code if an integer);

How to get a random number in Ruby

rand(6)    #=> gives a random number between 0 and 6 inclusively 
rand(1..6) #=> gives a random number between 1 and 6 inclusively

Note that the range option is only available in newer(1.9+ I believe) versions of ruby.

How do I change column default value in PostgreSQL?

If you want to remove the default value constraint, you can do:


How to convert C++ Code to C

There is indeed such a tool, Comeau's C++ compiler. . It will generate C code which you can't manually maintain, but that's no problem. You'll maintain the C++ code, and just convert to C on the fly.

Finding the second highest number in array

I'm not convinced that doing what you did fixes the problem; I think it masks yet another problem in your logic. To find the second highest is actually quite simple:

 static int secondHighest(int... nums) {
    int high1 = Integer.MIN_VALUE;
    int high2 = Integer.MIN_VALUE;
    for (int num : nums) {
      if (num > high1) {
        high2 = high1;
        high1 = num;
      } else if (num > high2) {
        high2 = num;
    return high2;

This is O(N) in one pass. If you want to accept ties, then change to if (num >= high1), but as it is, it will return Integer.MIN_VALUE if there aren't at least 2 elements in the array. It will also return Integer.MIN_VALUE if the array contains only the same number.

find -mtime files older than 1 hour

What about -mmin?

find /var/www/html/audio -daystart -maxdepth 1 -mmin +59 -type f -name "*.mp3" \
    -exec rm -f {} \;

From man find:

-mmin n
        File's data was last modified n minutes ago.

Also, make sure to test this first!

... -exec echo rm -f '{}' \;
          ^^^^ Add the 'echo' so you just see the commands that are going to get
               run instead of actual trying them first.

Send Email Intent

Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto", email, null));
if (emailIntent.resolveActivity(context.getPackageManager()) != null) {
    context.startActivity(Intent.createChooser(emailIntent, "Send Email..."));
} else {
    Toast.makeText(context, "No apps can perform this action.", Toast.LENGTH_SHORT).show();

How can Print Preview be called from Javascript?

I think the best that's possible in cross-browser JavaScript is window.print(), which (in Firefox 3, for me) brings up the 'print' dialog and not the print preview dialog.

FYI, the print dialog is your computer's Print popup, what you get when you do Ctrl-p. The print preview is Firefox's own Preview window, and it has more options. It's what you get with Firefox Menu > Print...

Eclipse: How to build an executable jar with external jar?

As a good practice you can use an Ant Script (Eclipse comes with it) to generate your JAR file. Inside this JAR you can have all dependent libs.

You can even set the MANIFEST's Class-path header to point to files in your filesystem, it's not a good practice though.

Ant build.xml script example:

<project name="jar with libs" default="compile and build" basedir=".">
<!-- this is used at compile time -->
<path id="example-classpath">
    <pathelement location="${root-dir}" />
    <fileset dir="D:/LIC/xalan-j_2_7_1" includes="*.jar" />

<target name="compile and build">
    <!-- deletes previously created jar -->
    <delete file="test.jar" />

    <!-- compile your code and drop .class into "bin" directory -->
    <javac srcdir="${basedir}" destdir="bin" debug="true" deprecation="on">
        <!-- this is telling the compiler where are the dependencies -->
        <classpath refid="example-classpath" />

    <!-- copy the JARs that you need to "bin" directory  -->
    <copy todir="bin">
        <fileset dir="D:/LIC/xalan-j_2_7_1" includes="*.jar" />

    <!-- creates your jar with the contents inside "bin" (now with your .class and .jar dependencies) -->
    <jar destfile="test.jar" basedir="bin" duplicate="preserve">
            <!-- Who is building this jar? -->
            <attribute name="Built-By" value="${}" />
            <!-- Information about the program itself -->
            <attribute name="Implementation-Vendor" value="ACME inc." />
            <attribute name="Implementation-Title" value="GreatProduct" />
            <attribute name="Implementation-Version" value="1.0.0beta2" />
            <!-- this tells which class should run when executing your jar -->
            <attribute name="Main-class" value="ApplyXPath" />

How to align content of a div to the bottom

2015 solution

<div style='width:200px; height:60px; border:1px solid red;'>

    <table width=100% height=100% cellspacing=0 cellpadding=0 border=0>
        <tr><td valign=bottom>{$This_text_at_bottom}</td></tr>


your welcome

How to get the first five character of a String

In C# 8.0 you can get the first five characters of a string like so

string str = data[0..5];

Here is some more information about Indices And Ranges

How to check if element in groovy array/hash/collection/list?

For lists, use contains:

[1,2,3].contains(1) == true

Assert a function/method was not called using Mock

Though an old question, I would like to add that currently mock library (backport of unittest.mock) supports assert_not_called method.

Just upgrade yours;

pip install mock --upgrade

Load image from resources area of project in C#

I looked at the designer code from one of my projects and noticed it used this notation

myButton.Image = global::MyProjectName.Properties.Resources.max;

where max is the name of the resource I uploaded into the project.

How to insert a character in a string at a certain position?

String.format("%0d.%02d", d / 100, d % 100);

mongodb how to get max value from collections

db.collection.findOne().sort({age:-1}) //get Max without need for limit(1)

How to disable Compatibility View in IE

Another way to achieve this in Apache is by putting the following lines in .htaccess in the root folder of your website (or in Apache's config files).

BrowserMatch "MSIE" isIE
BrowserMatch "Trident" isIE
Header set X-UA-Compatible "IE=edge" env=isIE

This requires that you have the mod_headers and mod_setenvif modules enabled.

The extra HTTP header only gets sent to IE browsers, and none of the others.

How do I move a file (or folder) from one folder to another in TortoiseSVN?

Use Tortoise's RENAME command, and type in a relative path ("folder/file.ext").

Angular CLI - Please add a @NgModule annotation when using latest

In my case, I created a new ChildComponent in Parentcomponent whereas both in the same module but Parent is registered in a shared module so I created ChildComponent using CLI which registered Child in the current module but my parent was registered in the shared module.

So register the ChildComponent in Shared Module manually.

Can't bind to 'ngIf' since it isn't a known property of 'div'

Just for anyone who still has an issue, I also had an issue where I typed ngif rather than ngIf (notice the capital 'I').

How to validate an OAuth 2.0 access token for a resource server?

Update Nov. 2015: As per Hans Z. below - this is now indeed defined as part of RFC 7662.

Original Answer: The OAuth 2.0 spec (RFC 6749) doesn't clearly define the interaction between a Resource Server (RS) and Authorization Server (AS) for access token (AT) validation. It really depends on the AS's token format/strategy - some tokens are self-contained (like JSON Web Tokens) while others may be similar to a session cookie in that they just reference information held server side back at the AS.

There has been some discussion in the OAuth Working Group about creating a standard way for an RS to communicate with the AS for AT validation. My company (Ping Identity) has come up with one such approach for our commercial OAuth AS (PingFederate): It uses REST based interaction for this that is very complementary to OAuth 2.0.

How to get ID of the last updated row in MySQL?

SET @uids := "";
UPDATE myf___ingtable
   SET id = id
   WHERE id < 5
  AND ( SELECT @uids := CONCAT_WS(',', CAST(id AS CHAR CHARACTER SET utf8), @uids) );
SELECT @uids;

I had to CAST the id (dunno why)... or I cannot get the @uids content (it was a blob) Btw many thanks for Pomyk answer!

how to display a javascript var in html body

<script type="text/javascript">_x000D_
        function get_param(param) {_x000D_
   var search =;_x000D_
   var compareKeyValuePair = function(pair) {_x000D_
      var key_value = pair.split('=');_x000D_
      var decodedKey = decodeURIComponent(key_value[0]);_x000D_
      var decodedValue = decodeURIComponent(key_value[1]);_x000D_
      if(decodedKey == param) return decodedValue;_x000D_
      return null;_x000D_
   var comparisonResult = null;_x000D_
   if(search.indexOf('&') > -1) {_x000D_
      var params = search.split('&');_x000D_
      for(var i = 0; i < params.length; i++) {_x000D_
         comparisonResult = compareKeyValuePair(params[i]); _x000D_
         if(comparisonResult !== null) {_x000D_
   } else {_x000D_
      comparisonResult = compareKeyValuePair(search);_x000D_
   return comparisonResult;_x000D_
var parcelNumber = get_param('parcelNumber'); //abc_x000D_
var registryId  = get_param('registryId'); //abc_x000D_
var registrySectionId = get_param('registrySectionId'); //abc_x000D_
var apartmentNumber = get_param('apartmentNumber'); //abc_x000D_

then in the page i call the values like so:

 <td class="tinfodd"> <script  type="text/javascript">_x000D_

What is an alternative to execfile in Python 3?

According to the documentation, instead of





Kotlin Ternary Conditional Operator

There is no ternary operator in kotlin, as the if else block returns value

so, you can do: val max = if (a > b) a else b instead of java's max = (a > b) ? b : c

We can also use when construction, it also return value:

val max = when(a > b) {
    true -> a
    false -> b

Here is link for kotlin documentation : Control Flow: if, when, for, while

Finding last occurrence of substring in string, replacing that

A one liner would be :


How to get file creation date/time in Bash/Debian?

Note that if you've got your filesystem mounted with noatime for performance reasons, then the atime will likely show the creation time. Given that noatime results in a massive performance boost (by removing a disk write for every time a file is read), it may be a sensible configuration option that also gives you the results you want.

How to create multidimensional array

Declared without value assignment.

2 dimensions...

var arrayName = new Array(new Array());

3 dimensions...

var arrayName = new Array(new Array(new Array()));

Failed to connect to mysql at with user root access denied for user 'root'@'localhost'(using password:YES)

Access the database as a user administrator (root user maybe). Check the right one user privileges to the database.

mysql >SHOW GRANTS FOR <username>;

Assign full user privileges to the database from localhost

mysql> GRANT ALL PRIVILEGES ON <databasename>.* TO '<username>'@'localhost' IDENTIFIED BY '<password>';

in case of error in connecting to the database from third-party programs, for example MySQL WORKBENCH, assign privileges to the user to the database from any host MYSQL Grant all privileges to database from any host

mysql> GRANT ALL PRIVILEGES ON <databasename>.* TO '<username>'@'%' IDENTIFIED BY '<password>';

deleted object would be re-saved by cascade (remove deleted object from associations)

Some how all the above solutions did not worked in hibernate 5.2.10.Final.

But setting the map to null as below worked for me:


How to convert a string to number in TypeScript?

Here is a modified version of the StrToNumber function. As before,

  1. It allows an optional sign to appear in front or behind the numeric value.
  2. It performs a check to verify there is only one sign at the head or tail of the string.
  3. If an error occurs, a "passed" default value is returned.

This response is a possible solution that is better suited to the initial question than my previous post.

   static StrToNumber(val: string, defaultVal:number = 0): number_x000D_
   {        _x000D_
      let result:number = defaultVal;      _x000D_
      if(val == null) _x000D_
         return result;            _x000D_
      if(val.length == 0) _x000D_
         return result;      _x000D_
      val = val.trim();_x000D_
      if(val.length == 0) _x000D_
      let sign:number = 1;     _x000D_
      // . obtain sign from string, and place result in "sign" local variable. The Sign naturally defaults to positive_x000D_
      //     1 for positive, -1 for negative._x000D_
      // . remove sign character from val. _x000D_
      //      Note, before the function returns, the result is multiplied by the sign local variable to reflect the sign._x000D_
      // . error check for multiple sign characters_x000D_
      // . error check to make sure sign character is at the head or tail of the string_x000D_
      //              _x000D_
      {  _x000D_
         let positiveSignIndex = val.indexOf('+');_x000D_
         let negativeSignIndex = val.indexOf('-');_x000D_
         let nTailIndex = val.length-1;_x000D_
         // make sure both negative and positive signs are not in the string_x000D_
         if( (positiveSignIndex != -1) && (negativeSignIndex != -1) ) _x000D_
             return result;_x000D_
         // handle postive sign_x000D_
         if (positiveSignIndex != -1)_x000D_
            // make sure there is only one sign character_x000D_
            if( (positiveSignIndex != val.lastIndexOf('+')) )_x000D_
             return result;     _x000D_
             // make sure the sign is at the head or tail_x000D_
             if( (positiveSignIndex > 0) && (positiveSignIndex < nTailIndex )  )_x000D_
                 return result;_x000D_
             // remove sign from string_x000D_
             val = val.replace("+","").trim();                 _x000D_
         }    _x000D_
         // handle negative sign_x000D_
         if (negativeSignIndex != -1)_x000D_
            // make sure there is only one sign character_x000D_
            if( (negativeSignIndex != val.lastIndexOf('-')) )_x000D_
             return result;     _x000D_
             // make sure the sign is at the head or tail_x000D_
             if( (negativeSignIndex > 0) && (negativeSignIndex < nTailIndex )  )_x000D_
                 return result;_x000D_
             // remove sign from string_x000D_
             val = val.replace("-","").trim();  _x000D_
             sign = -1;                 _x000D_
         }               _x000D_
         // make sure text length is greater than 0_x000D_
         //       _x000D_
         if(val.length == 0) _x000D_
            return result;                             _x000D_
      }   _x000D_
      // convert string to a number_x000D_
      var r = +(<any>val);_x000D_
      if( (r != null) && (!isNaN(r)) )_x000D_
      {          _x000D_
         result = r*sign;         _x000D_
      return(result);    _x000D_

How to convert password into md5 in jquery?

Download and include this plugin

<script src=""></script>

and use like

if(CryptoJS.MD5($("#txtOldPassword").val())) != oldPassword) {


//Following lines shows md5 value
//var hash = CryptoJS.MD5("Message");

Javascript - object key->value

Use this syntax:


Note that obj.x is the same as obj["x"] for all valid JS identifiers, but the latter form accepts all string as keys (not just valid identifiers).

obj["Hey, this is ... neat?"] = 42

CSS disable text selection

I agree with Someth Victory, you need to add a specific class to some elements you want to be unselectable.

Also, you may add this class in specific cases using javascript. Example here Making content unselectable with help of CSS.

Not equal to != and !== in PHP

$a !== $b TRUE if $a is not equal to $b, or they are not of the same type

Please Refer to

img tag displays wrong orientation

This answer builds on bsap's answer using Exif-JS , but doesn't rely on jQuery and is fairly compatible even with older browsers. The following are example html and js files:


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN"
      .rotate90 {
       -webkit-transform: rotate(90deg);
       -moz-transform: rotate(90deg);
       -o-transform: rotate(90deg);
       -ms-transform: rotate(90deg);
       transform: rotate(90deg);
      .rotate180 {
       -webkit-transform: rotate(180deg);
       -moz-transform: rotate(180deg);
       -o-transform: rotate(180deg);
       -ms-transform: rotate(180deg);
       transform: rotate(180deg);
      .rotate270 {
       -webkit-transform: rotate(270deg);
       -moz-transform: rotate(270deg);
       -o-transform: rotate(270deg);
       -ms-transform: rotate(270deg);
       transform: rotate(270deg);
    <img src="pic/pic03.jpg" width="200" alt="Cat 1" id="campic" class="camview">
    <script type="text/javascript" src="exif.js"></script>
    <script type="text/javascript" src="rotate.js"></script>


var newimg = document.getElementById('campic');
function getExif() {
    EXIF.getData(newimg, function() {
            var orientation = EXIF.getTag(this, "Orientation");
            if(orientation == 6) {
                newimg.className = "camview rotate90";
            } else if(orientation == 8) {
                newimg.className = "camview rotate270";
            } else if(orientation == 3) {
                newimg.className = "camview rotate180";

Delete from two tables in one query

The OP is just missing the table aliases after the delete

DELETE t1, t2 
FROM table1 t1 LEFT JOIN table2 t2 ON = 
WHERE = some_id

How to avoid 'undefined index' errors?

Set each index in the array at the beginning (or before the $output array is used) would probably be the easiest solution for your case.


$output['admin_link'] = ""
$output['alternate_title'] = ""
$output['access_info'] = ""
$output['description'] = ""
$output['url'] = ""

Also not really relevant for your case but where you said you were new to PHP and this is not really immediately obvious isset() can take multiple arguments. So in stead of this:

if(isset($var1) && isset($var2) && isset($var3) ...){
    // all are set

You can do:

if(isset($var1, $var2, $var3)){
   // all are set 

store and retrieve a class object in shared preference

You can use Complex Preferences Android - by Felipe Silvestre library to store your custom objects. Basically, it's using GSON mechanism to store objects.

To save object into prefs:

User user = new User();

ComplexPreferences complexPreferences = ComplexPreferences.getComplexPreferences(
     this, "mypref", MODE_PRIVATE);
complexPreferences.putObject("user", user);

And to retrieve it back:

ComplexPreferences complexPreferences = ComplexPreferences.getComplexPreferences(this, "mypref", MODE_PRIVATE);
User user = complexPreferences.getObject("user", User.class);

How to remove leading and trailing zeros in a string? Python

Remove leading + trailing '0':

list = [i.strip('0') for i in listOfNum ]

Remove leading '0':

list = [ i.lstrip('0') for i in listOfNum ]

Remove trailing '0':

list = [ i.rstrip('0') for i in listOfNum ]

Append to the end of a file in C

Following the documentation of fopen:

``a'' Open for writing. The file is created if it does not exist. The stream is positioned at the end of the file. Subsequent writes to the file will always end up at the then cur- rent end of file, irrespective of any intervening fseek(3) or similar.

So if you pFile2=fopen("myfile2.txt", "a"); the stream is positioned at the end to append automatically. just do:

FILE *pFile;
FILE *pFile2;
char buffer[256];

pFile=fopen("myfile.txt", "r");
pFile2=fopen("myfile2.txt", "a");
if(pFile==NULL) {
    perror("Error opening file.");
else {
    while(fgets(buffer, sizeof(buffer), pFile)) {
        fprintf(pFile2, "%s", buffer);

Get current cursor position in a textbox

It looks OK apart from the space in your ID attribute, which is not valid, and the fact that you're replacing the value of your input before checking the selection.

function textbox()_x000D_
        var ctl = document.getElementById('Javascript_example');_x000D_
        var startPos = ctl.selectionStart;_x000D_
        var endPos = ctl.selectionEnd;_x000D_
        alert(startPos + ", " + endPos);_x000D_
<input id="Javascript_example" name="one" type="text" value="Javascript example" onclick="textbox()">

Also, if you're supporting IE <= 8 you need to be aware that those browsers do not support selectionStart and selectionEnd.

Python recursive folder read

If you prefer an (almost) Oneliner:

from pathlib import Path

lookuppath = '.' #use your path
filelist = [str(item) for item in Path(lookuppath).glob("**/*") if Path(item).is_file()]

In this case you will get a list with just the paths of all files located recursively under lookuppath. Without str() you will get PosixPath() added to each path.

Convert to Datetime MM/dd/yyyy HH:mm:ss in Sql Server

Declare @month as char(2)
Declare @date as char(2)
Declare @year as char(4)
declare @time as char(8)
declare @customdate as varchar(20)

set @month = MONTH(GetDate());
set @date = Day(GetDate());
set @year = year(GetDate());

set @customdate= @month+'/'+@date+'/'+@year+' '+ CONVERT(varchar(8), GETDATE(),108);

Serializing/deserializing with memory stream

This code works for me:

public void Run()
    Dog myDog = new Dog();
    myDog.Name= "Foo";
    myDog.Color = DogColor.Brown;

    System.Console.WriteLine("{0}", myDog.ToString());

    MemoryStream stream = SerializeToStream(myDog);

    Dog newDog = (Dog)DeserializeFromStream(stream);

    System.Console.WriteLine("{0}", newDog.ToString());

Where the types are like this:

public enum DogColor

public class Dog
    public String Name
        get; set;

    public DogColor Color

    public override String ToString()
        return String.Format("Dog: {0}/{1}", Name, Color);

and the utility methods are:

public static MemoryStream SerializeToStream(object o)
    MemoryStream stream = new MemoryStream();
    IFormatter formatter = new BinaryFormatter();
    formatter.Serialize(stream, o);
    return stream;

public static object DeserializeFromStream(MemoryStream stream)
    IFormatter formatter = new BinaryFormatter();
    stream.Seek(0, SeekOrigin.Begin);
    object o = formatter.Deserialize(stream);
    return o;

Java keytool easy way to add server cert from url/port

Just expose dnozay's answer to a function so that we can import multiple certificates at the same time.

#!/usr/bin/env sh


import_cert() {
  local HOST=$1
  local PORT=$2

  # get the SSL certificate
  openssl s_client -connect ${HOST}:${PORT} </dev/null | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > ${HOST}.cert

  # delete the old alias and then import the new one
  keytool -delete -keystore ${KEYSTORE_FILE} -storepass ${KEYSTORE_PASS} -alias ${HOST} &> /dev/null

  # create a keystore and import certificate
  keytool -import -noprompt -trustcacerts \
      -alias ${HOST} -file ${HOST}.cert \
      -keystore ${KEYSTORE_FILE} -storepass ${KEYSTORE_PASS}

  rm ${HOST}.cert

import_cert 443
import_cert 443
import_cert 443 # google

How do I define and use an ENUM in Objective-C?

In the .h:

typedef enum {
} PlayerState;

Disable firefox same origin policy

The cors-everywhere addon works for me until Firefox 68, after 68 I need to adjust 'privacy.file_unique_origin' -> false (by open 'about:config') to solve 'CORS request not HTTP' for new CORS same-origin rule introduced.

Copy/duplicate database without using mysqldump

The best way to clone database tables without mysqldump:

  1. Create a new database.
  2. Create clone-queries with query:

    SET @NewSchema = 'your_new_db';
    SET @OldSchema = 'your_exists_db';
    SELECT CONCAT('CREATE TABLE ',@NewSchema,'.',table_name, ' LIKE ', TABLE_SCHEMA ,'.',table_name,';INSERT INTO ',@NewSchema,'.',table_name,' SELECT * FROM ', TABLE_SCHEMA ,'.',table_name,';') 
    FROM information_schema.TABLES where TABLE_SCHEMA = @OldSchema AND TABLE_TYPE != 'VIEW';
  3. Run that output!

But note, script above just fast clone tables - not views, triggers and user-functions: you can fast get structure by mysqldump --no-data --triggers -uroot -ppassword , and then use to clone only insert statement .

Why it is actual question? Because uploading of mysqldumps is ugly slow if DB is over 2Gb. And you can't clone InnoDB tables just by copying DB files (like snapshot backuping).

View content of H2 or HSQLDB in-memory database

What about comfortably viewing (and also editing) the content over ODBC & MS-Access, Excel? Softwareversions::

  • H2 Version:1.4.196
  • Win 10 Postgres ODBC Driver Version: psqlodbc_09_03_0210
  • For Win7 ODBC Client: win7_psqlodbc_09_00_0101-x64.msi

H2 Server:

For JDBC Clients to connect:
public class DBStarter {
    public static final String BASEDIR = "/C:/Trader/db/";
    public static final String DB_URL = BASEDIR + "trader;CIPHER=AES;IFEXISTS=TRUE;MVCC=true;LOCK_TIMEOUT=10000;CACHE_SIZE=131072;CACHE_TYPE=TQ";

  static void startServer() throws SQLException {
        Server tcpServer = Server.createTcpServer(
                "-tcpPort", "9092",
//                "-trace",
                "-baseDir", BASEDIR
        System.out.println("H2 JDBC Server started:  " + tcpServer.getStatus());

        Server pgServer = Server.createPgServer(
                "-pgPort", "10022",
                "-key", "traderdb", DB_URL
        System.out.println("H2 ODBC PGServer started: " + pgServer.getStatus());


Windows10 ODBC Datasource Configuration which can be used by any ODBC client: In Databse field the name given in '-key' parameter has to be used. ODBC Config

counting the number of lines in a text file

I think your question is, "why am I getting one more line than there is in the file?"

Imagine a file:

line 1
line 2
line 3

The file may be represented in ASCII like this:

line 1\nline 2\nline 3\n

(Where \n is byte 0x10.)

Now let's see what happens before and after each getline call:

Before 1: line 1\nline 2\nline 3\n
  Stream: ^
After 1:  line 1\nline 2\nline 3\n
  Stream:         ^

Before 2: line 1\nline 2\nline 3\n
  Stream:         ^
After 2:  line 1\nline 2\nline 3\n
  Stream:                 ^

Before 2: line 1\nline 2\nline 3\n
  Stream:                 ^
After 2:  line 1\nline 2\nline 3\n
  Stream:                         ^

Now, you'd think the stream would mark eof to indicate the end of the file, right? Nope! This is because getline sets eof if the end-of-file marker is reached "during it's operation". Because getline terminates when it reaches \n, the end-of-file marker isn't read, and eof isn't flagged. Thus, myfile.eof() returns false, and the loop goes through another iteration:

Before 3: line 1\nline 2\nline 3\n
  Stream:                         ^
After 3:  line 1\nline 2\nline 3\n
  Stream:                         ^ EOF

How do you fix this? Instead of checking for eof(), see if .peek() returns EOF:

while(myfile.peek() != EOF){
    getline ...

You can also check the return value of getline (implicitly casting to bool):

    cout<< ...

How do I log a Python error with debug information?

This answer builds up from the above excellent ones.

In most applications, you won't be calling logging.exception(e) directly. Most likely you have defined a custom logger specific for your application or module like this:

# Set the name of the app or module
my_logger = logging.getLogger('NEM Sequencer')
# Set the log level

# Let's say we want to be fancy and log to a graylog2 log server
graylog_handler = graypy.GELFHandler('some_server_ip', 12201)

In this case, just use the logger to call the exception(e) like this:

except ZeroDivisionError, e:

[ :Unexpected operator in shell programming

you have to use bash instead or rewrite your script using standard sh

sh -c 'test "$choose" = "y" -o "$choose" = "Y"'

Extract substring in Bash

A little late, but I just ran across this problem and found the following:

host:/tmp$ asd=someletters_12345_moreleters.ext 
host:/tmp$ echo `expr $asd : '.*_\(.*\)_'`

I used it to get millisecond resolution on an embedded system that does not have %N for date:

set `grep "now at" /proc/timer_list`
fraction=`expr $nano : '.*\(...\)......'`
$debug nano is $nano, fraction is $fraction

How to get the exact local time of client?

I found this function is very useful during all of my projects. you can also use it.

    let date = new Date();
    var tz = date.toString().split("GMT")[1].split(" (")[0];
    tz = tz.substring(1,5);
    let hOffset = parseInt(tz[0]+tz[1]);
    let mOffset = parseInt(tz[2]+tz[3]);
    let offset = date.getTimezoneOffset() * 60 * 1000;
    let localTime = date.getTime();
    let utcTime = localTime + offset;
    let austratia_brisbane = utcTime + (3600000 * hOffset) + (60000 * mOffset);
    let customDate = new Date(austratia_brisbane);

    let data = {
        day: customDate.getDate(),
        month: customDate.getMonth() + 1,
        year: customDate.getFullYear(),
        hour: customDate.getHours(),
        min: customDate.getMinutes(),
        second: customDate.getSeconds(),
        raw: customDate,
        stringDate: customDate.toString()

    return data;

this will give you the time depending on your time zone.


What's the yield keyword in JavaScript?

Yeild keyword in javaScript function makes it generator,

what is generator in javaScript?

A generator is a function that produces a sequence of results instead of a single value, i.e you generate ?a series of values

Meaning generators helps us work asynchronously with the help iterators, Oh now what the hack iterators are? really?

Iterators are mean through which we are able to access items one at a time

from where iterator help us accessing item one at a time? it help us accessing items through generator functions,

generator functions are those in which we use yeild keyword, yield keyword help us in pausing and resuming execution of function

here is quick example

function *getMeDrink() {

    let question1 = yield 'soda or beer' // execution will pause here because of yield

 if (question1 == 'soda') {

            return 'here you get your soda'


    if (question1 == 'beer') {

        let question2 = yield 'Whats your age' // execution will pause here because of yield

        if (question2 > 18) {

            return "ok you are eligible for it"

        } else {

            return 'Shhhh!!!!'


let _getMeDrink = getMeDrink() // initialize it  // "soda or beer"'beer').value  // "Whats your age"'20').value  // "ok you are eligible for it" // undefined

let me brifly explain what is going on

you noticed execution is being paused at each yeild keyword and we are able to access first yield with help of iterator .next()

this iterates to all yield keywords one at a time and then returns undefined when there is no more yield keywords left in simple words you can say yield keyword is break point where function each time pauses and only resume when call it using iterator

for our case: this is example of iterator that is helping us accessing each break point in function

Example of Generators: async/await

if you see implementation of async/await you will see generator functions & promises are used to make async/await work

please point out any suggestions is welcomed

How to lowercase a pandas dataframe string column if it has missing values?

Apply lambda function

df['original_category'] = df['original_category'].apply(lambda x:x.lower())

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

I've got the silimar problem. The solution was to migrate db ( syncdb or schemamigration --auto <table name> if you use south).

Session state can only be used when enableSessionState is set to true either in a configuration

Following answer from below given path worked fine.

I found a solution that worked perfectly! Add the following to web.config:

<!-- UrlRewriter code here -->
<remove name="Session" />
<add name="Session" type="System.Web.SessionState.SessionStateModule" preCondition="" />

Hope this helps someone else!

Best way to encode text data for XML

System.XML handles the encoding for you, so you don't need a method like this.

Evaluate a string with a switch in C++

Switch value must have an Integral type. Also, since you know that differenciating character is in position 7, you could switch on But you are not sure the user entered 8 characters. He may as well have done some typing mistake. So you are to surround your switch statement within a Try Catch. Something with this flavour

using namespace std;
int main() {
    string a;

    switch ( {
    case '1':
        cout<<"It pressed number 1"<<endl;
    case '2':
        cout<<"It pressed number 2"<<endl;
    case '3':
        cout<<"It pressed number 3"<<endl;
        cout<<"She put no choice"<<endl;

    return 0;

The default clause in switch statement captures cases when users input is at least 8 characters, but not in {1,2,3}.

Alternatively, you can switch on values in an enum.


Fetching 7th character with operator[]() does not perform bounds check, so that behavior would be undefined. we use at() from std::string, which is bounds-checked, as explained here.

Calculate relative time in C#

jquery.timeago plugin

Jeff, because Stack Overflow uses jQuery extensively, I recommend the jquery.timeago plugin.


  • Avoid timestamps dated "1 minute ago" even though the page was opened 10 minutes ago; timeago refreshes automatically.
  • You can take full advantage of page and/or fragment caching in your web applications, because the timestamps aren't calculated on the server.
  • You get to use microformats like the cool kids.

Just attach it to your timestamps on DOM ready:

jQuery(document).ready(function() {

This will turn all abbr elements with a class of timeago and an ISO 8601 timestamp in the title:

<abbr class="timeago" title="2008-07-17T09:24:17Z">July 17, 2008</abbr>

into something like this:

<abbr class="timeago" title="July 17, 2008">4 months ago</abbr>

which yields: 4 months ago. As time passes, the timestamps will automatically update.

Disclaimer: I wrote this plugin, so I'm biased.

How do I connect to this localhost from another computer on the same network?

That's definitely possible. We'll take a general case with Apache here.

Let's say you're a big Symfony2 fan and you would like to access your symfony website at http://symfony.local/ from 4 different computers (the main one hosting your website, as well as a Mac, a Windows and a Linux distro connected (wireless or not) to the main computer.

General Sketch:

enter image description here

1 Set up a virtual host:

You first need to set up a virtual host in your apache httpd-vhosts.conf file. On XAMP, you can find this file here: C:\xampp\apache\conf\extra\httpd-vhosts.conf. On MAMP, you can find this file here: Applications/MAMP/conf/apache/extra/httpd-vhosts.conf. This step prepares the Web server on your computer for handling symfony.local requests. You need to provide the name of the Virtual Host as well as the root/main folder of your website. To do this, add the following line at the end of that file. You need to change the DocumentRoot to wherever your main folder is. Here I have taken /Applications/MAMP/htdocs/Symfony/ as the root of my website.

<VirtualHost *:80>
    DocumentRoot "/Applications/MAMP/htdocs/Symfony/"
    ServerName symfony.local

2 Configure your hosts file:

For the client (your browser in that case) to understand what symfony.local really means, you need to edit the hosts file on your computer. Everytime you type an URL in your browser, your computer tries to understand what it means! symfony.local doesn't mean anything for a computer. So it will try to resolve the name symfony.local to an IP address. It will do this by first looking into the hosts file on your computer to see if he can match an IP address to what you typed in the address bar. If it can't, then it will ask DNS servers. The trick here is to append the following to your hosts file.

  • On MAC, this file is in /private/etc/hosts;
  • On LINUX, this file is in /etc/hosts;
  • On WINDOWS, this file is in \Windows\system32\private\etc\hosts;
  • On WINDOWS 7, this file is in \Windows\system32\drivers\etc\hosts;
  • On WINDOWS 10, this file is in \Windows\system32\drivers\etc\hosts;

Hosts file

# Host Database
# localhost is used to configure the loopback interface
#...           symfony.local

From now on, everytime you type symfony.local on this computer, your computer will use the loopback interface to connect to symfony.local. It will understand that you want to work on localhost (

3 Access symfony.local from an other computer:

We finally arrive to your main question which is:

How can I now access my website through an other computer?

Well this is now easy! We just need to tell the other computers how they could find symfony.local! How do we do this?

3a Get the IP address of the computer hosting the website:

We first need to know the IP address on the computer that hosts the website (the one we've been working on since the very beginning). In the terminal, on MAC and LINUX type ifconfig |grep inet, on WINDOWS type ipconfig. Let's assume the IP address of this computer is

3b Edit the hosts file on the computer you are trying to access the website from.:

Again, on MAC, this file is in /private/etc/hosts; on LINUX, in /etc/hosts; and on WINDOWS, in \Windows\system32\private\etc\hosts (if you're using WINDOWS 7, this file is in \Windows\system32\drivers\etc\hosts).. The trick is now to use the IP address of the computer we are trying to access/talk to:

# Host Database
# localhost is used to configure the loopback interface
#...         symfony.local

4 Finally enjoy the results in your browser

You can now go into your browser and type http://symfony.local to beautifully see your website on different computers! Note that you can apply the same strategy if you are a OSX user to test your website on Internet Explorer via Virtual Box (if you don't want to use a Windows computer). This is beautifully explained in Crafting Your Windows / IE Test Environment on OSX.

You can also access your localhost from mobile devices

You might wonder how to access your localhost website from a mobile device. In some cases, you won't be able to modify the hosts file (iPhone, iPad...) on your device (jailbreaking excluded).

Well, the solution then is to install a proxy server on the machine hosting the website and connect to that proxy from your iphone. It's actually very well explained in the following posts and is not that long to set up:

On a Mac, I would recommend: Testing a Mac OS X web site using a local hostname on a mobile device: Using SquidMan as a proxy. It's a 100% free solution. Some people can also use Charles as a proxy server but it's 50$.

On Linux, you can adapt the Mac OS way above by using Squid as a proxy server.

On Windows, you can do that using Fiddler. The solution is described in the following post: Monitoring iPhone traffic with Fiddler

Edit 23/11/2017: Hey I don't want to modify my Hosts file

@Dre. Any possible way to access the website from another computer by not editing the host file manually? let's say I have 100 computers wanted to access the website

This is an interesting question, and as it is related to the OP question, let me help.

You would have to do a change on your network so that every machine knows where your website is hosted. Most everyday routers don't do that so you would have to run your own DNS Server on your network.

Let's pretend you have a router ( This router has a DHCP server and allocates IP addresses to 100 machines on the network.

Now, let's say you have, same as above, on the same network, a machine at which has your website. We will call that machine pompei.

$ echo $HOSTNAME

Same as before, that machine pompei at runs an HTTP Server which serves your website symfony.local.

For every machine to know that symfony.local is hosted on pompei we will now need a custom DNS Server on the network which knows where symfony.local is hosted. Devices on the network will then be able to resolve domain names served by pompei internally.

3 simple steps.

Step 1: DNS Server

Set-up a DNS Server on your network. Let's have it on pompei for convenience and use something like dnsmasq.

Dnsmasq provides Domain Name System (DNS) forwarder, ....

We want pompei to run DNSmasq to handle DNS requests Hey, pompei, where is symfony.local and respond Hey, sure think, it is on but don't take my word for it.

Go ahead install dnsmasq, dnsmasq configuration file is typically in /etc/dnsmasq.conf depending on your environment.

I personally use no-resolv and google servers server= server=

*Note:* ALWAYS restart DNSmasq if modifying /etc/hosts file as no changes will take effect otherwise.

Step 2: Firewall

To work, pompei needs to allow incoming and outgoing 'domain' packets, which are going from and to port 53. Of course! These are DNS packets and if pompei does not allow them, there is no way for your DNS server to be reached at all. Go ahead and open that port 53. On linux, you would classically use iptables for this.

Sharing what I came up with but you will very likely have to dive into your firewall and understand everything well.

# Allow outbound DNS port 53
 iptables -A INPUT -p tcp --dport 53 -j ACCEPT
 iptables -A INPUT -p udp --dport 53 -j ACCEPT

 iptables -A OUTPUT -p tcp --dport 53 -j ACCEPT
 iptables -A OUTPUT -p udp --dport 53 -j ACCEPT

 iptables -A INPUT -p udp --sport 53 -j ACCEPT
 iptables -A INPUT -p tcp --sport 53 -j ACCEPT

 iptables -A OUTPUT -p tcp --sport 53 -j ACCEPT
 iptables -A OUTPUT -p udp --sport 53 -j ACCEPT

Step 3: Router

Tell your router that your dns server is on now. Most of the time, you can just login into your router and change this manually very easily.

That's it, When you are on a machine and ask for symfony.local, it will ask your DNS Server where symfony.local is hosted, and as soon as it has received its answer from the DNS server, will then send the proper HTTP request to pompei on

I let you play with this and enjoy the ride. These 2 steps are the main guidelines, so you will have to debug and spend a few hours if this is the first time you do it. Let's say this is a bit more advanced networking, there are primary DNS Server, secondary DNS Servers, etc.. Good luck!

Is it better to use C void arguments "void foo(void)" or not "void foo()"?

void foo(void);

That is the correct way to say "no parameters" in C, and it also works in C++.


void foo();

Means different things in C and C++! In C it means "could take any number of parameters of unknown types", and in C++ it means the same as foo(void).

Variable argument list functions are inherently un-typesafe and should be avoided where possible.

How to deal with missing src/test/java source folder in Android/Maven project?

I solve the problem by creating a folder named "src/test/resources" first, then i rename the folder to "src/test/java" ,finally create a "src/test/resources" folder again .It works .

Default session timeout for Apache Tomcat applications

Open $CATALINA_BASE/conf/web.xml and find this

<!-- ==================== Default Session Configuration ================= -->
<!-- You can set the default session timeout (in minutes) for all newly   -->
<!-- created sessions by modifying the value below.                       -->


all webapps implicitly inherit from this default web descriptor. You can override session-config as well as other settings defined there in your web.xml.

This is actually from my Tomcat 7 (Windows) but I think 5.5 conf is not very different

What is the difference between functional and non-functional requirements?

A functional requirement describes what a software system should do, while non-functional requirements place constraints on how the system will do so.

Let me elaborate.

An example of a functional requirement would be:

  • A system must send an email whenever a certain condition is met (e.g. an order is placed, a customer signs up, etc).

A related non-functional requirement for the system may be:

  • Emails should be sent with a latency of no greater than 12 hours from such an activity.

The functional requirement is describing the behavior of the system as it relates to the system's functionality. The non-functional requirement elaborates a performance characteristic of the system.

Typically non-functional requirements fall into areas such as:

  • Accessibility
  • Capacity, current and forecast
  • Compliance
  • Documentation
  • Disaster recovery
  • Efficiency
  • Effectiveness
  • Extensibility
  • Fault tolerance
  • Interoperability
  • Maintainability
  • Privacy
  • Portability
  • Quality
  • Reliability
  • Resilience
  • Response time
  • Robustness
  • Scalability
  • Security
  • Stability
  • Supportability
  • Testability

A more complete list is available at Wikipedia's entry for non-functional requirements.

Non-functional requirements are sometimes defined in terms of metrics (i.e. something that can be measured about the system) to make them more tangible. Non-functional requirements may also describe aspects of the system that don't relate to its execution, but rather to its evolution over time (e.g. maintainability, extensibility, documentation, etc.).

How to use Angular2 templates with *ngFor to create a table out of nested arrays?

I am a fan of keeping logic out of the template as much as possible. I would suggest creating a helper function that returns the data that you care about to the template. For instance:

getItemsForDisplay():String[] {
 return [].concat.apply([], => group.items));

<tr *ngFor="let item of getItemsForDisplay()"><td>{{item}}</td></tr>

This will let you keep your presentation free of special logic. This also lets you use your datasource "directly".

python error: no module named pylab

I installed python-numpy python-scipy python-matplotlib, but it didn't work for me and I got the same error. Pylab isn't recognized without matplotlib. So I used this:

from matplotlib import pylab
from pylab import *

and worked for me.

How to export MySQL database with triggers and procedures?

May be it's obvious for expert users of MYSQL but I wasted some time while trying to figure out default value would not export functions. So I thought to mention here that --routines param needs to be set to true to make it work.

mysqldump --routines=true -u <user> my_database > my_database.sql