Programs & Examples On #Spuserfield

Printing out a number in assembly language?

DOS Print 32 bit value stored in EAX with hexadecimal output (for 80386+)
(on 64 bit OS use DOSBOX)

    mov ax,@DATA        ; get the address of the data segment
    mov ds,ax           ; store the address in the data segment register
    mov eax,0FFFFFFFFh  ; 32 bit value (0 - FFFFFFFF) for example
; convert the value in EAX to hexadecimal ASCIIs
    mov di,OFFSET ASCII ; get the offset address
    mov cl,8            ; number of ASCII
P1: rol eax,4           ; 1 Nibble (start with highest byte)
    mov bl,al
    and bl,0Fh          ; only low-Nibble
    add bl,30h          ; convert to ASCII
    cmp bl,39h          ; above 9?
    jna short P2
    add bl,7            ; "A" to "F"
P2: mov [di],bl         ; store ASCII in buffer
    inc di              ; increase target address
    dec cl              ; decrease loop counter
    jnz P1              ; jump if cl is not equal 0 (zeroflag is not set)
; Print string
    mov ah,9            ; DS:DX->'$'-terminated string
    int 21h             ; maybe redirected under DOS 2+ for output to file
                        ; (using pipe character">") or output to printer

  ; terminate program...

ASCII DB "00000000",0Dh,0Ah,"$" ; buffer for ASCII string

Alternative string output directly to the videobuffer without using software interupts:

; Print string
    mov ax,0B800h       ; segment address of textmode video buffer
    mov es,ax           ; store address in extra segment register

    mov si,OFFSET ASCII ; get the offset address of the string

; using a fixed target address for example (screen page 0)
; Position`on screen = (Line_number*80*2) + (Row_number*2)

    mov di,(10*80*2)+(10*2)
    mov cl,8            ; number of ASCII
    cld                 ; clear direction flag

P3: lodsb  ; get the ASCII from the address in DS:SI + increase si
    stosb  ; write ASCII directly to the screen using ES:DI + increase di
    inc di ; step over attribut byte
    dec cl ; decrease counter
    jnz P3 ; repeat (print only 8 ASCII, not used bytes are: 0Dh,0Ah,"$")

; Hint: this directly output to the screen do not touch or move the cursor
; but feel free to modify..

Nested iframes, AKA Iframe Inception

I guess your problem is that jQuery is not loaded in your iframes.

The safest approach is to rely on pure DOM-based methods to parse your content.

Or else, start with jQuery, and then once inside your iframes, test once if typeof window.jQuery == 'undefined', if it's true, jQuery is not enabled inside it and fallback on DOM-based method.

How to load Spring Application Context

Add this at the start of main

ApplicationContext context = new ClassPathXmlApplicationContext("path/to/applicationContext.xml");

JobLauncher launcher=(JobLauncher)context.getBean("launcher");
Job job=(Job)context.getBean("job");

//Get as many beans you want
//Now do the thing you were doing inside test method
StopWatch sw = new StopWatch();
sw.start();, jobParameters);
//initialize the log same way inside main">>> TIME ELAPSED:" + sw.prettyPrint());

javascript clear field value input

 var input= $(this);    
 input.innerHTML = '';

Blank HTML SELECT without blank item in dropdown list

     <option value="" style="display:none;"></option>
     <option value="0">aaaa</option>
     <option value="1">bbbb</option>

Disabling submit button until all fields have values

This works well since all the inputs have to meet the condition of not null.

$(function () {
    $('#submits').attr('disabled', true);
    $('#input_5').change(function () {
        if ($('#input_1').val() != '' && $('#input_2').val() != '' && $('#input_3').val() != '' && $('#input_4').val() != '' && $('#input_5').val() != '') {
            $('#submit').attr('disabled', false);
        } else {
            $('#submit').attr('disabled', true);

How to check if type is Boolean

That's what typeof is there for. The parentheses are optional since it is an operator.

if (typeof variable === "boolean"){
  // variable is a boolean

Does Arduino use C or C++?

Arduino doesn't run either C or C++. It runs machine code compiled from either C, C++ or any other language that has a compiler for the Arduino instruction set.

C being a subset of C++, if Arduino can "run" C++ then it can "run" C.

If you don't already know C nor C++, you should probably start with C, just to get used to the whole "pointer" thing. You'll lose all the object inheritance capabilities though.

Run an Ansible task only when the variable contains a specific string

use this

when: "{{ 'value' in variable1}}"

instead of

when: "'value' in {{variable1}}"

Also for string comparison you can use

when: "{{ variable1 == 'value' }}"

Get current url in Angular

You can make use of location service available in @angular/common and via this below code you can get the location or current URL

import { Component, OnInit } from '@angular/core';
import { Location } from '@angular/common';
import { Router } from '@angular/router';

  selector: 'app-top-nav',
  templateUrl: './top-nav.component.html',
  styleUrls: ['./top-nav.component.scss']
export class TopNavComponent implements OnInit {

  route: string;

  constructor(location: Location, router: Router) { => {
      if(location.path() != ''){
        this.route = location.path();
      } else {
        this.route = 'Home'

  ngOnInit() {


here is the reference link from where I have copied thing to get location for my project.

How to convert JSON data into a Python object

JSON to python object

The follwing code creates dynamic attributes with the objects keys recursively.

JSON object - fb_data.json:

    "name": "John Smith",
    "hometown": {
        "name": "New York",
        "id": 123
    "list": [
            "key": 1
    "object": {
        "key": {
            "key": 1

On the conversion we have 3 cases:

  • lists
  • dicts (new object)
  • bool, int, float and str
import json

class AppConfiguration(object):
    def __init__(self, data=None):
        if data is None:
            with open("fb_data.json") as fh:
                data = json.loads(
            data = dict(data)

        for key, val in data.items():
            setattr(self, key, self.compute_attr_value(val))

    def compute_attr_value(self, value):
        if isinstance(value, list):
            return [self.compute_attr_value(x) for x in value]
        elif isinstance(value, dict):
            return AppConfiguration(value)
            return value

if __name__ == "__main__":
    instance = AppConfiguration()


Now the key, value pairs are attributes - objects.


John Smith
New York

Paste JSON as Code

Supports TypeScript, Python, Go, Ruby, C#, Java, Swift, Rust, Kotlin, C++, Flow, Objective-C, JavaScript, Elm, and JSON Schema.

  • Interactively generate types and (de-)serialization code from JSON, JSON Schema, and TypeScript
  • Paste JSON/JSON Schema/TypeScript as code

enter image description here

quicktype infers types from sample JSON data, then outputs strongly typed models and serializers for working with that data in your desired programming language.


# Generated by
# To change quicktype's target language, run command:
#   "Set quicktype target language"

from typing import List, Union

class Hometown:
    name: str
    id: int

    def __init__(self, name: str, id: int) -> None: = name = id

class Key:
    key: int

    def __init__(self, key: int) -> None:
        self.key = key

class Object:
    key: Key

    def __init__(self, key: Key) -> None:
        self.key = key

class FbData:
    name: str
    hometown: Hometown
    list: List[Union[Key, int, str]]
    object: Object

    def __init__(self, name: str, hometown: Hometown, list: List[Union[Key, int, str]], object: Object) -> None: = name
        self.hometown = hometown
        self.list = list
        self.object = object

This extension is available for free in the Visual Studio Code Marketplace.

How do I check in python if an element of a list is empty?

I got around this with len() and a simple if/else statement.

List elements will come back as an integer when wrapped in len() (1 for present, 0 for absent)

l = []

print(len(l)) # Prints 0

if len(l) == 0:
    print("Element is empty")
    print("Element is NOT empty")


Element is empty    

How do I vertically align something inside a span tag?

Be aware that the line-height approach fails if you have a long sentence in the span which breaks the line because there's not enough space. In this case, you would have two lines with a gap with the height of the N pixels specified in the property.

I stuck into it when I wanted to show an image with vertically centered text on its right side which works in a responsive web application. As a base I use the approach suggested by Eric Nickus and Felipe Tadeo.

If you want to achieve:


and this:


.container {_x000D_
    background: url( "" ) no-repeat;_x000D_
    display: inline-block;_x000D_
    background-size: 40px 40px; /* image's size */_x000D_
    height: 40px; /* image's height */_x000D_
    padding-left: 50px; /* image's width plus 10 px (margin between text and image) */_x000D_
.container span {_x000D_
    height: 40px; /* image's height */_x000D_
    display: table-cell;_x000D_
    vertical-align: middle;_x000D_
<span class="container">_x000D_
    <span>This is a centered sentence next to an image</span>_x000D_

How do I access the $scope variable in browser's console using AngularJS?

To add and enhance the other answers, in the console, enter $($0) to get the element. If it's an Angularjs application, a jQuery lite version is loaded by default.

If you are not using jQuery, you can use angular.element($0) as in:


To check if you have jQuery and the version, run this command in the console:


If you have inspected an element, the currently selected element is available via the command line API reference $0. Both Firebug and Chrome have this reference.

However, the Chrome developer tools will make available the last five elements (or heap objects) selected through the properties named $0, $1, $2, $3, $4 using these references. The most recently selected element or object can be referenced as $0, the second most recent as $1 and so on.

Here is the Command Line API reference for Firebug that lists it's references.

$($0).scope() will return the scope associated with the element. You can see its properties right away.

Some other things that you can use are:

  • View an elements parent scope:


  • You can chain this too:


  • You can look at the root scope:


  • If you highlighted a directive with isolate scope, you can look at it with:


See Tips and Tricks for Debugging Unfamiliar Angularjs Code for more details and examples.

How can I find all the subsets of a set, with exactly n elements?

Without using itertools:

In Python 3 you can use yield from to add a subset generator method to buit-in set class:

class SetWithSubset(set):
    def subsets(self):
        s1 = []
        s2 = list(self)

        def recfunc(i=0):            
            if i == len(s2):
                yield frozenset(s1)
                yield from recfunc(i + 1)
                s1.append(s2[ i ])
                yield from recfunc(i + 1)

        yield from recfunc()

For example below snippet works as expected:

x = SetWithSubset({1,2,3,5,6})
{2,3} in x.subsets()            # True
set() in x.subsets()            # True
x in x.subsets()                # True
x|{7} in x.subsets()            # False
set([5,3]) in x.subsets()       # True - better alternative: set([5,3]) < x
len(x.subsets())                # 32

How to get rid of "Unnamed: 0" column in a pandas DataFrame?

To get ride of all Unnamed columns, you can also use regex such as df.drop(df.filter(regex="Unname"),axis=1, inplace=True)

Find the most frequent number in a NumPy array

I like the solution by JoshAdel.

But there is just one catch.

The np.bincount() solution only works on numbers.

If you have strings, collections.Counter solution will work for you.

ParseError: not well-formed (invalid token) using cElementTree

I was having the same error (with ElementTree). In my case it was because of encodings, and I was able to solve it without having to use an external library. Hope this helps other people finding this question based on the title. (reference)

import xml.etree.ElementTree as ET
parser = ET.XMLParser(encoding="utf-8")
tree = ET.fromstring(xmlstring, parser=parser)

EDIT: Based on comments, this answer might be outdated. But this did work back when it was answered...

Accessing session from TWIG template

The way to access a session variable in Twig is:

{{ app.session.get('name_variable') }}

Updating a local repository with changes from a GitHub repository

With an already-set origin master, you just have to use the below command -

git pull ""

How to add new DataRow into DataTable?

try table.Rows.add(row); after your for statement.

Counting the Number of keywords in a dictionary in python

The number of distinct words (i.e. count of entries in the dictionary) can be found using the len() function.

> a = {'foo':42, 'bar':69}
> len(a)

To get all the distinct words (i.e. the keys), use the .keys() method.

> list(a.keys())
['foo', 'bar']

Comparing object properties in c#

This method will get properties of the class and compare the values for each property. If any of the values are different, it will return false, else it will return true.

public static bool Compare<T>(T Object1, T object2)
    //Get the type of the object
    Type type = typeof(T);

    //return false if any of the object is false
    if (Object1 == null || object2 == null)
        return false;

    //Loop through each properties inside class and get values for the property from both the objects and compare
    foreach (System.Reflection.PropertyInfo property in type.GetProperties())
        if (property.Name != "ExtensionData")
            string Object1Value = string.Empty;
            string Object2Value = string.Empty;
            if (type.GetProperty(property.Name).GetValue(Object1, null) != null)
                Object1Value = type.GetProperty(property.Name).GetValue(Object1, null).ToString();
            if (type.GetProperty(property.Name).GetValue(object2, null) != null)
                Object2Value = type.GetProperty(property.Name).GetValue(object2, null).ToString();
            if (Object1Value.Trim() != Object2Value.Trim())
                return false;
    return true;


bool isEqual = Compare<Employee>(Object1, Object2)

Can grep show only words that match search pattern?

Try grep -o

grep -oh "\w*th\w*" *

Edit: matching from Phil's comment

From the docs:

-h, --no-filename
    Suppress the prefixing of file names on output. This is the default
    when there is only  one  file  (or only standard input) to search.
-o, --only-matching
    Print  only  the matched (non-empty) parts of a matching line,
    with each such part on a separate output line.

Could not create the Java virtual machine

Set the JVM memory:

export _JAVA_OPTIONS=-Xmx512M

Getting an element from a Set

The contract of the hash code makes clear that:

"If two objects are equal according to the Object method, then calling the hashCode method on each of the two objects must produce the same integer result."

So your assumption:

"To clarify, the equals method is overridden, but it only checks one of the fields, not all. So two Foo objects that are considered equal can actually have different values, that's why I can't just use foo."

is wrong and you are breaking the contract. If we look at the "contains" method of Set interface, we have that:

boolean contains(Object o);
Returns true if this set contains the specified element. More formally, returns true if and only if this set contains an element "e" such that o==null ? e==null : o.equals(e)

To accomplish what you want, you can use a Map where you define the key and store your element with the key that defines how objects are different or equal to each other.

JUnit: how to avoid "no runnable methods" in test utils classes

I was also facing a similar issue ("no runnable methods..") on running the simplest of simple piece of code (Using @Test, @Before etc.) and found the solution nowhere. I was using Junit4 and Eclipse SDK version 4.1.2. Resolved my problem by using the latest Eclipse SDK 4.2.2. I hope this helps people who are struggling with a somewhat similar issue.

How do I parse a YAML file in Ruby?

Here is the one liner i use, from terminal, to test the content of yml file(s):

$ ruby  -r yaml -r pp  -e 'pp YAML.load_file("/Users/za/project/application.yml")'
    {"root"=>"WARN", "org"=>{"springframework"=>{"security"=>"DEBUG"}}}}}

Can not deserialize instance of java.lang.String out of START_OBJECT token

Resolved the problem using Jackson library. Prints are called out of Main class and all POJO classes are created. Here is the code snippets.

public class MainClass {
  public static void main(String[] args) throws JsonParseException, 
       JsonMappingException, IOException {

String jsonStr = "{\r\n" + "    \"id\": 2,\r\n" + " \"socket\": \"0c317829-69bf- 
            + " \"type\": \"getDashboard\",\r\n" + "    \"data\": {\r\n"
            + "     \"workstationUuid\": \"ddec1caa-a97f-4922-833f- 
            632da07ffc11\"\r\n" + " },\r\n"
            + " \"reply\": true\r\n" + "}";

    ObjectMapper mapper = new ObjectMapper();

    MyPojo details = mapper.readValue(jsonStr, MyPojo.class);

    System.out.println("Value for getFirstName is: " + details.getId());
    System.out.println("Value for getLastName  is: " + details.getSocket());
    System.out.println("Value for getChildren is: " + 
    System.out.println("Value for getChildren is: " + details.getReply());


public class MyPojo {
    private String id;

    private Data data;

    private String reply;

    private String socket;

    private String type;

    public String getId() {
        return id;

    public void setId(String id) { = id;

    public Data getData() {
        return data;

    public void setData(Data data) { = data;

    public String getReply() {
        return reply;

    public void setReply(String reply) {
        this.reply = reply;

    public String getSocket() {
        return socket;

    public void setSocket(String socket) {
        this.socket = socket;

    public String getType() {
        return type;

    public void setType(String type) {
        this.type = type;

public class Data {
    private String workstationUuid;

    public String getWorkstationUuid() {
        return workstationUuid;

    public void setWorkstationUuid(String workstationUuid) {
        this.workstationUuid = workstationUuid;


Value for getFirstName is: 2
Value for getLastName  is: 0c317829-69bf-43d6-b598-7c0c550635bb
Value for getChildren is: ddec1caa-a97f-4922-833f-632da07ffc11
Value for getChildren is: true

NotificationCenter issue on Swift 3

Swift 3 & 4

Swift 3, and now Swift 4, have replaced many "stringly-typed" APIs with struct "wrapper types", as is the case with NotificationCenter. Notifications are now identified by a struct Notfication.Name rather than by String. For more details see the now legacy Migrating to Swift 3 guide

Swift 2.2 usage:

// Define identifier
let notificationIdentifier: String = "NotificationIdentifier"

// Register to receive notification
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(YourClassName.methodOfReceivedNotification(_:)), name: notificationIdentifier, object: nil)

// Post a notification
NSNotificationCenter.defaultCenter().postNotificationName(notificationIdentifier, object: nil)

Swift 3 & 4 usage:

// Define identifier
let notificationName = Notification.Name("NotificationIdentifier")

// Register to receive notification
NotificationCenter.default.addObserver(self, selector: #selector(YourClassName.methodOfReceivedNotification), name: notificationName, object: nil)

// Post notification notificationName, object: nil)

// Stop listening notification
NotificationCenter.default.removeObserver(self, name: notificationName, object: nil)

All of the system notification types are now defined as static constants on Notification.Name; i.e. .UIApplicationDidFinishLaunching, .UITextFieldTextDidChange, etc.

You can extend Notification.Name with your own custom notifications in order to stay consistent with the system notifications:

// Definition:
extension Notification.Name {
    static let yourCustomNotificationName = Notification.Name("yourCustomNotificationName")

// Usage: .yourCustomNotificationName, object: nil)

Swift 4.2 usage:

Same as Swift 4, except now system notifications names are part of UIApplication. So in order to stay consistent with the system notifications you can extend UIApplication with your own custom notifications instead of Notification.Name :

// Definition:
UIApplication {
    public static let yourCustomNotificationName = Notification.Name("yourCustomNotificationName")

// Usage: UIApplication.yourCustomNotificationName, object: nil)

What is the difference between `let` and `var` in swift?

Everyone has pretty much answered this but here's a way you can remember what's what

Let will always say the same think of "let" as let this work for once and always as for "var" variable's can always change hence them being called variable's

How to find if a file contains a given string using Windows command line

From other post:

    find /c "string" file >NUL
    if %errorlevel% equ 1 goto notfound
        echo found
    goto done
        echo notfound
    goto done

Use the /i switch when you want case insensitive checking:

    find /i /c "string" file >NUL

Or something like: if not found write to file.

    find /c "%%P" file.txt  || ( echo %%P >> newfile.txt )

Or something like: if found write to file.

    find /c "%%P" file.txt  && ( echo %%P >> newfile.txt )

Or something like:

    find /c "%%P" file.txt  && ( echo found ) || ( echo not found )

Java Reflection Performance

There is some overhead with reflection, but it's a lot smaller on modern VMs than it used to be.

If you're using reflection to create every simple object in your program then something is wrong. Using it occasionally, when you have good reason, shouldn't be a problem at all.

How to access parent scope from within a custom directive *with own scope* in AngularJS?

If you are using ES6 Classes and ControllerAs syntax, you need to do something slightly different.

See the snippet below and note that vm is the ControllerAs value of the parent Controller as used in the parent HTML

myApp.directive('name', function() {
  return {
    // no scope definition
    link : function(scope, element, attrs, ngModel) {


JavaScriptSerializer - JSON serialization of enum as string

ASP.NET Core way:

public class Startup
  public IServiceProvider ConfigureServices(IServiceCollection services)
    services.AddMvc().AddJsonOptions(options =>
      options.SerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());

Check if SQL Connection is Open or Closed

The .NET documentation says: State Property: A bitwise combination of the ConnectionState values

So I think you should check


instead of

myConnection.State != ConnectionState.Open

because State can have multiple flags.

How do I set up Visual Studio Code to compile C++ code?

First of all, goto extensions (Ctrl + Shift + X) and install 2 extensions:

  1. Code Runner
  2. C/C++

Then, then reload the VS Code and select a play button on the top of the right corner your program runs in the output terminal. You can see output by Ctrl + Alt + N. To change other features goto user setting. enter image description here

How do I concatenate text in a query in sql server?

The only way would be to convert your text field into an nvarchar field.

Select Cast(notes as nvarchar(4000)) + 'SomeText'
From NotesTable a

Otherwise, I suggest doing the concatenation in your application.

How to Return partial view of another controller by controller?

Simply you could use:


py2exe - generate single executable file

I've been able to create a single exe file with all resources embeded into the exe. I'm building on windows. so that will explain some of the os.system calls i'm using.

First I tried converting all my images into bitmats and then all my data files into text strings. but this caused the final exe to be very very large.

After googleing for a week i figured out how to alter py2exe script to meet my needs.

here is the patch link on sourceforge i submitted, please post comments so we can get it included in the next distribution.

this explanes all the changes made, i've simply added a new option to the setup line. here is my

i'll try to comment it as best I can. Please know that my is complex do to the fact that i'm access the images by filename. so I must store a list to keep track of them.

this is from a want-to-b screen saver I was trying to make.

I use exec to generate my setup at run time, its easyer to cut and paste like that.

exec "setup(console=[{'script': '', 'icon_resources': [(0, 'ICON.ico')],\
      'file_resources': [%s], 'other_resources': [(u'INDEX', 1, resource_string[:-1])]}],\
      options={'py2exe': py2exe_options},\
      zipfile = None )" % (bitmap_string[:-1])


script = py script i want to turn to an exe

icon_resources = the icon for the exe

file_resources = files I want to embed into the exe

other_resources = a string to embed into the exe, in this case a file list.

options = py2exe options for creating everything into one exe file

bitmap_strings = a list of files to include

Please note that file_resources is not a valid option untill you edit your file as described in the link above.

first time i've tried to post code on this site, if I get it wrong don't flame me.

from distutils.core import setup
import py2exe #@UnusedImport
import os

#delete the old build drive
os.system("rmdir /s /q dist")

#setup my option for single file output
py2exe_options = dict( ascii=True,  # Exclude encodings
                       excludes=['_ssl',  # Exclude _ssl
                                 'pyreadline', 'difflib', 'doctest', 'locale',
                                 'optparse', 'pickle', 'calendar', 'pbd', 'unittest', 'inspect'],  # Exclude standard library
                       dll_excludes=['msvcr71.dll', 'w9xpopen.exe',
                       #compressed=None,  # Compress
                       bundle_files = 1,
                       optimize = 2                        

#storage for the images
bitmap_string = '' 
resource_string = ''
index = 0

print "compile image list"                          

for image_name in os.listdir('images/'):
    if image_name.endswith('.jpg'):
        bitmap_string += "( " + str(index+1) + "," + "'" + 'images/' + image_name + "'),"
        resource_string += image_name + " "
        index += 1

print "Starting build\n"

exec "setup(console=[{'script': '', 'icon_resources': [(0, 'ICON.ico')],\
      'file_resources': [%s], 'other_resources': [(u'INDEX', 1, resource_string[:-1])]}],\
      options={'py2exe': py2exe_options},\
      zipfile = None )" % (bitmap_string[:-1])

print "Removing Trash"
os.system("rmdir /s /q build")
os.system("del /q *.pyc")
print "Build Complete"

ok, thats it for the now the magic needed access the images. I developed this app without py2exe in mind then added it later. so you'll see access for both situations. if the image folder can't be found it tries to pull the images from the exe resources. the code will explain it. this is part of my sprite class and it uses a directx. but you can use any api you want or just access the raw data. doesn't matter.

def init(self):
    frame = self.env.frame
    use_resource_builtin = True
    if os.path.isdir(SPRITES_FOLDER):
        use_resource_builtin = False
        image_list = LoadResource(0, u'INDEX', 1).split(' ')

    for (model, file) in SPRITES.items():
        texture = POINTER(IDirect3DTexture9)()
        if use_resource_builtin: 
            data = LoadResource(0, win32con.RT_RCDATA, image_list.index(file)+1) #windll.kernel32.FindResourceW(hmod,typersc,idrsc)               
            d3dxdll.D3DXCreateTextureFromFileInMemory(frame.device,   #Pointer to an IDirect3DDevice9 interface
                                              data,                #Pointer to the file in memory
                                              len(data),           #Size of the file in memory
                                              byref(texture))      #ppTexture
            d3dxdll.D3DXCreateTextureFromFileA(frame.device, #@UndefinedVariable
                                               SPRITES_FOLDER + file,
        self.model_sprites[model] = texture
    #    raise Exception("'sprites' folder is not present!")

Any questions fell free to ask.

How to send email in ASP.NET C#

Try using this code instead. Note: In the "from address" give your correct email id and password.

protected void btn_send_Click(object sender, EventArgs e)

    System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
    mail.To.Add("to gmail address");
    mail.From = new MailAddress("from gmail address", "Email head", System.Text.Encoding.UTF8);
    mail.Subject = "This mail is send from application";
    mail.SubjectEncoding = System.Text.Encoding.UTF8;
    mail.Body = "This is Email Body Text";
    mail.BodyEncoding = System.Text.Encoding.UTF8;
    mail.IsBodyHtml = true;
    mail.Priority = MailPriority.High;
    SmtpClient client = new SmtpClient();
    client.Credentials = new System.Net.NetworkCredential("from gmail address", "your gmail account password");
    client.Port = 587;
    client.Host = "";
    client.EnableSsl = true;
        Page.RegisterStartupScript("UserMsg", "<script>alert('Successfully Send...');if(alert){ window.location='SendMail.aspx';}</script>");
    catch (Exception ex)
        Exception ex2 = ex;
        string errorMessage = string.Empty;
        while (ex2 != null)
            errorMessage += ex2.ToString();
            ex2 = ex2.InnerException;
        Page.RegisterStartupScript("UserMsg", "<script>alert('Sending Failed...');if(alert){ window.location='SendMail.aspx';}</script>");

How to get text box value in JavaScript

Set id for the textbox. ie,

<input type="text" name="txtJob" value="software engineer" id="txtJob"> 

In javascript

var jobValue = document.getElementById('txtJob').value

In Jquery

 var jobValue =  $("#txtJob").val();

C# - Create SQL Server table programmatically

For managing DataBase Objects in SQL Server i would suggest using Server Management Objects

Transfer files to/from session I'm logged in with PuTTY

If you have to do private key validation; at Command Prompt(cmd), run


set PATH=C:\PuttySetupLocation


pscp -i C:/MyPrivateKeyFile.ppk C:/MySourceFile.jar [email protected]:/home/ubuntu

Also, if you need extra options look at the following link.

PYODBC--Data source name not found and no default driver specified

Create a DSN something like this (ASEDEV) for your connection and try to use DSN instead of DRIVER like below:

enter code here
import pyodbc
cnxn = pyodbc.connect('DSN=ASEDEV;User ID=sa;Password=sybase123')
mycur = cnxn.cursor()
mycur.execute("select * from master..sysdatabases")
row = mycur.fetchone()
while row:
    row = mycur.fetchone()`

How to compile for Windows on Linux with gcc/g++?

I've used mingw on Linux to make Windows executables in C, I suspect C++ would work as well.

I have a project, ELLCC, that packages clang and other things as a cross compiler tool chain. I use it to compile clang (C++), binutils, and GDB for Windows. Follow the download link at for pre-compiled binaries for several Linux hosts.

How to set a default value for an existing column

The correct way to do this is as follows:

  1. Run the command:

    sp_help [table name] 
  2. Copy the name of the CONSTRAINT.


  4. Run the command below:


set background color: Android

By the way, a good tip on quickly selecting color on the newer versions of AS is simply to type #fff and then using the color picker on the side of the code to choose the one you want. Quick and easier than remembering all the color hexadecimals. For example:


What's the difference between "Request Payload" vs "Form Data" as seen in Chrome dev tools Network tab

The Request Payload - or to be more precise: payload body of a HTTP Request - is the data normally send by a POST or PUT Request. It's the part after the headers and the CRLF of a HTTP Request.

A request with Content-Type: application/json may look like this:

POST /some-path HTTP/1.1
Content-Type: application/json

{ "foo" : "bar", "name" : "John" }

If you submit this per AJAX the browser simply shows you what it is submitting as payload body. That’s all it can do because it has no idea where the data is coming from.

If you submit a HTML-Form with method="POST" and Content-Type: application/x-www-form-urlencoded or Content-Type: multipart/form-data your request may look like this:

POST /some-path HTTP/1.1
Content-Type: application/x-www-form-urlencoded


In this case the form-data is the request payload. Here the Browser knows more: it knows that bar is the value of the input-field foo of the submitted form. And that’s what it is showing to you.

So, they differ in the Content-Type but not in the way data is submitted. In both cases the data is in the message-body. And Chrome distinguishes how the data is presented to you in the Developer Tools.

How can I Remove .DS_Store files from a Git repository?

No need to remove .DS_STORE locally

Just add it to .gitignore file

The .gitignore file is just a text file that tells Git which files or folders to ignore in a project.


  • nano .gitignore
  • Write .DS_Store Then click CTRL+X > y > Hit Return
  • git status To have a last look at your changes
  • git add .gitignore
  • git commit -m 'YOUR COMMIT MESSAGE'
  • git push origin master

How to alter a column and change the default value?

In case the above does not work for you (i.e.: you are working with new SQL or Azure) try the following:

1) drop existing column constraint (if any):

ALTER TABLE [table_name] DROP CONSTRAINT DF_my_constraint

2) create a new one:

ALTER TABLE [table_name] ADD CONSTRAINT DF_my_constraint  DEFAULT getdate() FOR column_name;

How do I get the localhost name in PowerShell?

Don't forget that all your old console utilities work just fine in PowerShell:

PS> hostname

How to import csv file in PHP?

I know that this has been asked more than three years ago. But the answer accepted is not extremely useful.

The following code is more useful.

$File = 'loginevents.csv';

$arrResult  = array();
$handle     = fopen($File, "r");
if(empty($handle) === false) {
    while(($data = fgetcsv($handle, 1000, ",")) !== FALSE){
        $arrResult[] = $data;

How to reverse apply a stash?

According to the git-stash manpage, "A stash is represented as a commit whose tree records the state of the working directory, and its first parent is the commit at HEAD when the stash was created," and git stash show -p gives us "the changes recorded in the stash as a diff between the stashed state and its original parent.

To keep your other changes intact, use git stash show -p | patch --reverse as in the following:

$ git init
Initialized empty Git repository in /tmp/repo/.git/

$ echo Hello, world >messages

$ git add messages

$ git commit -am 'Initial commit'
[master (root-commit)]: created 1ff2478: "Initial commit"
 1 files changed, 1 insertions(+), 0 deletions(-)
 create mode 100644 messages

$ echo Hello again >>messages

$ git stash

$ git status
# On branch master
nothing to commit (working directory clean)

$ git stash apply
# On branch master
# Changed but not updated:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#       modified:   messages
no changes added to commit (use "git add" and/or "git commit -a")

$ echo Howdy all >>messages

$ git diff
diff --git a/messages b/messages
index a5c1966..eade523 100644
--- a/messages
+++ b/messages
@@ -1 +1,3 @@
 Hello, world
+Hello again
+Howdy all

$ git stash show -p | patch --reverse
patching file messages
Hunk #1 succeeded at 1 with fuzz 1.

$ git diff
diff --git a/messages b/messages
index a5c1966..364fc91 100644
--- a/messages
+++ b/messages
@@ -1 +1,2 @@
 Hello, world
+Howdy all


A light improvement to this is to use git apply in place of patch:

git stash show -p | git apply --reverse

Alternatively, you can also use git apply -R as a shorthand to git apply --reverse.

I've been finding this really handy lately...

Replace a newline in TSQL

REPLACE(@string, CHAR(13) + CHAR(10), '')

How do I make a div full screen?

<div id="placeholder" style="position:absolute; top:0; right:0; bottom:0; left:0;"></div>

Send auto email programmatically

Sending email programmatically with Kotlin.

  • simple email sending, not all the other features (like attachments).
  • TLS is always on
  • Only 1 gradle email dependency needed also.

I also found this list of email POP services really helpful:

How to use:

    val auth = EmailService.UserPassAuthenticator("yourUser", "yourPass")
    val to = listOf(InternetAddress("[email protected]"))
    val from = InternetAddress("[email protected]")
    val email = EmailService.Email(auth, to, from, "Test Subject", "Hello Body World")
    val emailService = EmailService("yourSmtpServer", 587)

    GlobalScope.launch { // or however you do background threads

The code:

import java.util.*
import javax.mail.*
import javax.mail.internet.InternetAddress
import javax.mail.internet.MimeBodyPart
import javax.mail.internet.MimeMessage
import javax.mail.internet.MimeMultipart

class EmailService(private var server: String, private var port: Int) {

    data class Email(
        val auth: Authenticator,
        val toList: List<InternetAddress>,
        val from: Address,
        val subject: String,
        val body: String

    class UserPassAuthenticator(private val username: String, private val password: String) : Authenticator() {
        override fun getPasswordAuthentication(): PasswordAuthentication {
            return PasswordAuthentication(username, password)

    fun send(email: Email) {
        val props = Properties()
        props["mail.smtp.auth"] = "true"
        props["mail.user"] = email.from
        props[""] = server
        props["mail.smtp.port"] = port
        props["mail.smtp.starttls.enable"] = "true"
        props[""] = server
        props["mail.mime.charset"] = "UTF-8"
        val msg: Message = MimeMessage(Session.getDefaultInstance(props, email.auth))
        msg.sentDate = Calendar.getInstance().time
        msg.setRecipients(Message.RecipientType.TO, email.toList.toTypedArray())
//      msg.setRecipients(Message.RecipientType.CC, email.ccList.toTypedArray())
//      msg.setRecipients(Message.RecipientType.BCC, email.bccList.toTypedArray())
        msg.replyTo = arrayOf(email.from)

        msg.addHeader("X-Mailer", CLIENT_NAME)
        msg.addHeader("Precedence", "bulk")
        msg.subject = email.subject

        msg.setContent(MimeMultipart().apply {
            addBodyPart(MimeBodyPart().apply {
                setText(email.body, "iso-8859-1")
                //setContent(email.htmlBody, "text/html; charset=UTF-8")

    companion object {
        const val CLIENT_NAME = "Android StackOverflow programmatic email"


dependencies {
    implementation 'com.sun.mail:android-mail:1.6.4'
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.3"


<uses-permission name="android.permission.INTERNET" />

How to use unicode characters in Windows command line?


chcp 65001

which will change the code page to UTF-8. Also, you need to use Lucida console fonts.

The breakpoint will not currently be hit. No symbols have been loaded for this document in a Silverlight application

My problem was a "return" middle of the code. so after return breakepoint won't work.

How do I stop a program when an exception is raised in Python?

import sys

  sys.exit(1) # exiing with a non zero value is better for returning from an error

Is it possible to CONTINUE a loop from an exception?

Notice you can use WHEN exception THEN NULL the same way as you would use WHEN exception THEN continue. Example:

        extension_already_exists  EXCEPTION;
        PRAGMA EXCEPTION_INIT(extension_already_exists, -20007);
        l_hidden_col_name  varchar2(32);
        FOR t IN (  SELECT table_name, cast(extension as varchar2(200)) ext
                    FROM all_stat_extensions
                    WHERE owner='{{ prev_schema }}'
                      and droppable='YES'
                    ORDER BY 1
                l_hidden_col_name := dbms_stats.create_extended_stats('{{ schema }}', t.table_name, t.ext);
                WHEN extension_already_exists THEN NULL;   -- ignore exception and go to next loop iteration
        END LOOP;

Printing with sed or awk a line following a matching pattern

Never use the word "pattern" as is it highly ambiguous. Always use "string" or "regexp" (or in shell "globbing pattern"), whichever it is you really mean.

The specific answer you want is:

awk 'f{print;f=0} /regexp/{f=1}' file

or specializing the more general solution of the Nth record after a regexp (idiom "c" below):

awk 'c&&!--c; /regexp/{c=1}' file

The following idioms describe how to select a range of records given a specific regexp to match:

a) Print all records from some regexp:

awk '/regexp/{f=1}f' file

b) Print all records after some regexp:

awk 'f;/regexp/{f=1}' file

c) Print the Nth record after some regexp:

awk 'c&&!--c;/regexp/{c=N}' file

d) Print every record except the Nth record after some regexp:

awk 'c&&!--c{next}/regexp/{c=N}1' file

e) Print the N records after some regexp:

awk 'c&&c--;/regexp/{c=N}' file

f) Print every record except the N records after some regexp:

awk 'c&&c--{next}/regexp/{c=N}1' file

g) Print the N records from some regexp:

awk '/regexp/{c=N}c&&c--' file

I changed the variable name from "f" for "found" to "c" for "count" where appropriate as that's more expressive of what the variable actually IS.

How to get Spinner selected item value to string?

String Text = mySpinner.getSelectedItem().toString();


mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        Object item = parent.getItemAtPosition(position);
    public void onNothingSelected(AdapterView<?> parent) {

How to Lazy Load div background images

Lazy loading images using above mentioned plugins uses conventional way of attaching listener to scroll events or by making use of setInterval and is highly non-performant as each call to getBoundingClientRect() forces the browser to re-layout the entire page and will introduce considerable jank to your website.

Use Lozad.js (just 569 bytes with no dependencies), which uses InteractionObserver to lazy load images performantly.

How to extract a substring using regex

as in javascript:


the actual regexp is: /'([^']+)'/

if you use the non greedy modifier (as per another post) it's like this:


it is cleaner.

Best way to do Version Control for MS Excel

After searching for ages and trying out many different tools, I've found my answer to the vba version control problem here:

It's a simple excel addin for which the code can be found here

There are no duplicate modules after importing. It exports your code automatically, as soon as you save your workbook, without modifying any existing workbooks. It comes together with a vba code formatter.

How to get the current location latitude and longitude in android

Before couple of months, I created GPSTracker library to help me to get GPS locations. In case you need to view GPSTracker > getLocation



<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />


import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {

    TextView textview;

    protected void onCreate(Bundle savedInstanceState) {

        // check if GPS enabled
        GPSTracker gpsTracker = new GPSTracker(this);

        if (gpsTracker.getIsGPSTrackingEnabled())
            String stringLatitude = String.valueOf(gpsTracker.latitude);
            textview = (TextView)findViewById(;

            String stringLongitude = String.valueOf(gpsTracker.longitude);
            textview = (TextView)findViewById(;

            String country = gpsTracker.getCountryName(this);
            textview = (TextView)findViewById(;

            String city = gpsTracker.getLocality(this);
            textview = (TextView)findViewById(;

            String postalCode = gpsTracker.getPostalCode(this);
            textview = (TextView)findViewById(;

            String addressLine = gpsTracker.getAddressLine(this);
            textview = (TextView)findViewById(;
            // can't get location
            // GPS or Network is not enabled
            // Ask user to enable GPS/network in settings

    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(, menu);
        return true;

GPS Tracker

import java.util.List;
import java.util.Locale;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;

 * Create this Class from tutorial : 
 * For Geocoder read this :

public class GPSTracker extends Service implements LocationListener {

    // Get Class Name
    private static String TAG = GPSTracker.class.getName();

    private final Context mContext;

    // flag for GPS Status
    boolean isGPSEnabled = false;

    // flag for network status
    boolean isNetworkEnabled = false;

    // flag for GPS Tracking is enabled 
    boolean isGPSTrackingEnabled = false;

    Location location;
    double latitude;
    double longitude;

    // How many Geocoder should return our GPSTracker
    int geocoderMaxResults = 1;

    // The minimum distance to change updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

    // Declaring a Location Manager
    protected LocationManager locationManager;

    // Store LocationManager.GPS_PROVIDER or LocationManager.NETWORK_PROVIDER information
    private String provider_info;

    public GPSTracker(Context context) {
        this.mContext = context;

     * Try to get my current location by GPS or Network Provider
    public void getLocation() {

        try {
            locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);

            //getting GPS status
            isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

            //getting network status
            isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            // Try to get location if you GPS Service is enabled
            if (isGPSEnabled) {
                this.isGPSTrackingEnabled = true;

                Log.d(TAG, "Application use GPS Service");

                 * This provider determines location using
                 * satellites. Depending on conditions, this provider may take a while to return
                 * a location fix.

                provider_info = LocationManager.GPS_PROVIDER;

            } else if (isNetworkEnabled) { // Try to get location if you Network Service is enabled
                this.isGPSTrackingEnabled = true;

                Log.d(TAG, "Application use Network State to get GPS coordinates");

                 * This provider determines location based on
                 * availability of cell tower and WiFi access points. Results are retrieved
                 * by means of a network lookup.
                provider_info = LocationManager.NETWORK_PROVIDER;


            // Application can use GPS or Network Provider
            if (!provider_info.isEmpty()) {

                if (locationManager != null) {
                    location = locationManager.getLastKnownLocation(provider_info);
        catch (Exception e)
            Log.e(TAG, "Impossible to connect to LocationManager", e);

     * Update GPSTracker latitude and longitude
    public void updateGPSCoordinates() {
        if (location != null) {
            latitude = location.getLatitude();
            longitude = location.getLongitude();

     * GPSTracker latitude getter and setter
     * @return latitude
    public double getLatitude() {
        if (location != null) {
            latitude = location.getLatitude();

        return latitude;

     * GPSTracker longitude getter and setter
     * @return
    public double getLongitude() {
        if (location != null) {
            longitude = location.getLongitude();

        return longitude;

     * GPSTracker isGPSTrackingEnabled getter.
     * Check GPS/wifi is enabled
    public boolean getIsGPSTrackingEnabled() {

        return this.isGPSTrackingEnabled;

     * Stop using GPS listener
     * Calling this method will stop using GPS in your app
    public void stopUsingGPS() {
        if (locationManager != null) {

     * Function to show settings alert dialog
    public void showSettingsAlert() {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        //Setting Dialog Title

        //Setting Dialog Message

        //On Pressing Setting button
        alertDialog.setPositiveButton(R.string.action_settings, new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) 
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);

        //On pressing cancel button
        alertDialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) 

     * Get list of address by latitude and longitude
     * @return null or List<Address>
    public List<Address> getGeocoderAddress(Context context) {
        if (location != null) {

            Geocoder geocoder = new Geocoder(context, Locale.ENGLISH);

            try {
                 * Geocoder.getFromLocation - Returns an array of Addresses 
                 * that are known to describe the area immediately surrounding the given latitude and longitude.
                List<Address> addresses = geocoder.getFromLocation(latitude, longitude, this.geocoderMaxResults);

                return addresses;
            } catch (IOException e) {
                Log.e(TAG, "Impossible to connect to Geocoder", e);

        return null;

     * Try to get AddressLine
     * @return null or addressLine
    public String getAddressLine(Context context) {
        List<Address> addresses = getGeocoderAddress(context);

        if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);
            String addressLine = address.getAddressLine(0);

            return addressLine;
        } else {
            return null;

     * Try to get Locality
     * @return null or locality
    public String getLocality(Context context) {
        List<Address> addresses = getGeocoderAddress(context);

        if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);
            String locality = address.getLocality();

            return locality;
        else {
            return null;

     * Try to get Postal Code
     * @return null or postalCode
    public String getPostalCode(Context context) {
        List<Address> addresses = getGeocoderAddress(context);

        if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);
            String postalCode = address.getPostalCode();

            return postalCode;
        } else {
            return null;

     * Try to get CountryName
     * @return null or postalCode
    public String getCountryName(Context context) {
        List<Address> addresses = getGeocoderAddress(context);
        if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);
            String countryName = address.getCountryName();

            return countryName;
        } else {
            return null;

    public void onLocationChanged(Location location) {

    public void onStatusChanged(String provider, int status, Bundle extras) {

    public void onProviderEnabled(String provider) {

    public void onProviderDisabled(String provider) {

    public IBinder onBind(Intent intent) {
        return null;


If the method / answer doesn't work. You need to use the official Google Provider: FusedLocationProviderApi.

Article: Getting the Last Known Location

How to add two edit text fields in an alert dialog

Check this code in alert box have edit textview when click OK it displays on screen using toast.

public void onCreate(Bundle savedInstanceState) {

    final AlertDialog.Builder alert = new AlertDialog.Builder(this);
    final EditText input = new EditText(this);
    alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            String value = input.getText().toString().trim();
            Toast.makeText(getApplicationContext(), value, 

    alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {

Formatting a field using ToText in a Crystal Reports formula field

if(isnull({uspRptMonthlyGasRevenueByGas;1.YearTotal})) = true then

The above logic should be what you are looking for.

How to push local changes to a remote git repository on bitbucket

Use git push origin master instead.

You have a repository locally and the initial git push is "pushing" to it. It's not necessary to do so (as it is local) and it shows everything as up-to-date. git push origin master specifies a a remote repository (origin) and the branch located there (master).

For more information, check out this resource.

How to place two forms on the same page?

Give the submit buttons for both forms different names and use PHP to check which button has submitted data.

Form one button - btn1 Form two button -btn2

PHP Code:


Android Room - simple select query - Cannot access database on the main thread

With lambda its easy to run with AsyncTask

 AsyncTask.execute(() -> //run your query here );

Check string for palindrome

public boolean isPalindrome(String abc){
    if(abc != null && abc.length() > 0){
        char[] arr = abc.toCharArray();
        for (int i = 0; i < arr.length/2; i++) {
            if(arr[i] != arr[arr.length - 1 - i]){
                return false;
        return true;
    return false;

How to break lines at a specific character in Notepad++?

I have no idea how it can work automatically, but you can copy "], " together with new line and then use replace function.

How to read html from a url in python 3

Try the 'requests' module, it's much simpler.

#pip install requests for installation

import requests

url = ''
r = requests.get(url)

more info here >

How to write html code inside <?php ?>, I want write html code within the PHP script so that it can be echoed from Backend

Try it like,

    $name='your name';
    echo '<table>


    echo '<table>

How can I convert an image into Base64 string using JavaScript?

You can use the HTML5 <canvas> for it:

Create a canvas, load your image into it and then use toDataURL() to get the Base64 representation (actually, it's a data: URL, but it contains the Base64-encoded image).

Calling stored procedure from another stored procedure SQL Server

You could add an OUTPUT parameter to test2, and set it to the new id straight after the INSERT using:


Then in test1, retrieve it like so:

-- Now use @NewId as needed

How to empty the message in a text area with jquery?

A comment to jarijira

Well I have had many issues with .html and .empty() methods for inputs o. If the id represents an input and not another type of html selector like

or use the .val() function to manipulate.

For example: this is the proper way to manipulate input values

<textarea class="form-control" id="someInput"></textarea>

$(document).ready(function () {
     var newVal='test'
     $('#someInput').val('') //clear input value
     $('#someInput').val(newVal) //override w/ the new value
     newVal= $('#someInput').val(newVal) //get input value


For improper, but sometimes works For example: this is the proper way to manipulate input values

<textarea class="form-control" id="someInput"></textarea>

$(document).ready(function () {
     var newVal='test'
     $('#someInput').html('') //clear input value
     $('#someInput').empty() //clear html inside of the id
     $('#someInput').html(newVal) //override the html inside of text area w/ string could be '<div>test3</div>
     really overriding with a string manipulates the value, but this is not the best practice as you do not put things besides strings or values inside of an input. 
     newVal= $('#someInput').val(newVal) //get input value


An issue that I had was I was using the $getJson method and I was indeed able to use .html calls to manipulate my inputs. However, whenever I had an error or fail on the getJSON I could no longer change my inputs using the .clear and .html calls. I could still return the .val(). After some experimentation and research I discovered that you should only use the .val() function to make changes to input fields.

Conda uninstall one package and one package only

You can use conda remove --force.

The documentation says:

--force               Forces removal of a package without removing packages
                      that depend on it. Using this option will usually
                      leave your environment in a broken and inconsistent

Find the day of a week

Use the lubridate package and function wday:

df$date <- as.Date(df$date)
wday(df$date, label=TRUE)
[1] Wed   Wed   Thurs
Levels: Sun < Mon < Tues < Wed < Thurs < Fri < Sat

Get folder name from full file path

This can also be done like so;

var directoryName = System.IO.Path.GetFileName(@"c:\projects\roott\wsdlproj\devlop\beta2\text");

How to change a DIV padding without affecting the width/height ?

Sounds like you're looking to simulate the IE6 box model. You could use the CSS 3 property box-sizing: border-box to achieve this. This is supported by IE8, but for Firefox you would need to use -moz-box-sizing and for Safari/Chrome, use -webkit-box-sizing.

IE6 already computes the height wrong, so you're good in that browser, but I'm not sure about IE7, I think it will compute the height the same in quirks mode.

How to serialize Joda DateTime with Jackson JSON processor?

Meanwhile Jackson registers the Joda module automatically when the JodaModule is in classpath. I just added jackson-datatype-joda to Maven and it worked instantly.


JSON output:

{"created" : "2017-03-28T05:59:27.258Z"}

android get all contacts

Get all contacts in less than a second and without any load in your activity. Follow my steps works like a charm.

ArrayList<Contact> contactList = new ArrayList<>();

private static final String[] PROJECTION = new String[]{

private void getContactList() {
    ContentResolver cr = getContentResolver();

    Cursor cursor = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, PROJECTION, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
    if (cursor != null) {
        HashSet<String> mobileNoSet = new HashSet<String>();
        try {
            final int nameIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
            final int numberIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);

            String name, number;
            while (cursor.moveToNext()) {
                name = cursor.getString(nameIndex);
                number = cursor.getString(numberIndex);
                number = number.replace(" ", "");
                if (!mobileNoSet.contains(number)) {
                    contactList.add(new Contact(name, number));
                    Log.d("hvy", "onCreaterrView  Phone Number: name = " + name
                            + " No = " + number);
        } finally {


public class Contact {
public String name;
public String phoneNumber;

public Contact() {

public Contact(String name, String phoneNumber ) { = name;
    this.phoneNumber = phoneNumber;

public String getName() {
    return name;

public void setName(String name) { = name;

public String getPhoneNumber() {
    return phoneNumber;

public void setPhoneNumber(String phoneNumber) {
    this.phoneNumber = phoneNumber;



  • less than a second
  • without load
  • ascending order
  • without duplicate contacts

What does .pack() do?

The pack method sizes the frame so that all its contents are at or above their preferred sizes. An alternative to pack is to establish a frame size explicitly by calling setSize or setBounds (which also sets the frame location). In general, using pack is preferable to calling setSize, since pack leaves the frame layout manager in charge of the frame size, and layout managers are good at adjusting to platform dependencies and other factors that affect component size.

From Java tutorial

You should also refer to Javadocs any time you need additional information on any Java API

long long int vs. long int vs. int64_t in C++

Do you want to know if a type is the same type as int64_t or do you want to know if something is 64 bits? Based on your proposed solution, I think you're asking about the latter. In that case, I would do something like

template<typename T>
bool is_64bits() { return sizeof(T) * CHAR_BIT == 64; } // or >= 64

Replacing some characters in a string with another character

You might find this link helpful:

In general,

To replace the first match of $substring with $replacement:


To replace all matches of $substring with $replacement:


EDIT: Note that this applies to a variable named $string.

How to get JavaScript variable value in PHP

You need to add this value to the form data that is submitted to the server. You can use

<input type="hidden" value="1" name="profile_viewer_uid" id="profile_viewer_uid">

inside your form tag.

An existing connection was forcibly closed by the remote host - WCF

I found that you can get this error if the returned object has getter only auto properties that are initialized in the constructor (with C# 6.0 syntax).

I believe this is due to WCF deserializing objects on the client side using a parameter-less constructor then setting the properties on the object. It needs to have a set available (it can be private) to fill the object, otherwise it'll fail.

How can I replace the deprecated set_magic_quotes_runtime in php?

I used FPDF v. 1.53 and didn't want to upgrade because of possible side effects. I used the following code according to Yacoby:

Line 1164:

if (version_compare(PHP_VERSION, '5.3.0', '<')) {

Line 1203:

if (version_compare(PHP_VERSION, '5.3.0', '<')) {

Laravel: Get Object From Collection By Attribute

As from Laravel 5.5 you can use firstWhere()

In you case:

$green_foods = $foods->firstWhere('color', 'green');

Evaluate empty or null JSTL c tags

This code is correct but if you entered a lot of space (' ') instead of null or empty string return false.

To correct this use regular expresion (this code below check if the variable is null or empty or blank the same as org.apache.commons.lang.StringUtils.isNotBlank) :

<%@ taglib uri="" prefix="fn" %>
        <c:if test="${not empty description}">
            <c:set var="description" value="${fn:replace(description, ' ', '')}" />
            <c:if test="${not empty description}">
                  The description is not blank.

How to prevent a browser from storing passwords

I would create a session variable and randomize it. Then build the id and name values based on the session variable. Then on login interrogate the session var you created.

if (!isset($_SESSION['autoMaskPassword'])) {
    $bytes = random_bytes(16);
    $_SESSION['autoMask_password'] = bin2hex($bytes);

<input type="password" name="<?=$_SESSION['autoMaskPassword']?>" placeholder="password">

CSS3 Transform Skew One Side

Maybe you want to use CSS "clip-path" (Works with transparency and background)

"clip-path" reference:



/* With percent */_x000D_
.element-percent {_x000D_
  background: red;_x000D_
  width: 150px;_x000D_
  height: 48px;_x000D_
  display: inline-block;_x000D_
  clip-path: polygon(0 0, 100% 0%, 75% 100%, 0% 100%);_x000D_
/* With pixel */_x000D_
.element-pixel {_x000D_
  background: blue;_x000D_
  width: 150px;_x000D_
  height: 48px;_x000D_
  display: inline-block;_x000D_
  clip-path: polygon(0 0, 100% 0%, calc(100% - 32px) 100%, 0% 100%);_x000D_
/* With background */_x000D_
.element-background {_x000D_
  background: url( no-repeat center/cover;_x000D_
  width: 150px;_x000D_
  height: 48px;_x000D_
  display: inline-block;_x000D_
  clip-path: polygon(0 0, 100% 0%, calc(100% - 32px) 100%, 0% 100%);_x000D_
<div class="element-percent"></div>_x000D_
<br />_x000D_
<div class="element-pixel"></div>_x000D_
<br />_x000D_
<div class="element-background"></div>

Testing javascript with Mocha - how can I use console.log to debug a test?

What Mocha options are you using?

Maybe it is something to do with reporter (-R) or ui (-ui) being used?


works fine during my test runs, though sometimes mixed in a little goofy. Presumably due to the async nature of the test run.

Here are the options (mocha.opts) I'm using:

--require should
-R spec
--ui bdd

Hmm..just tested without any mocha.opts and console.log still works.

Find duplicate lines in a file and count how many time each line was duplicated?

To find and count duplicate lines in multiple files, you can try the following command:

sort <files> | uniq -c | sort -nr


cat <files> | sort | uniq -c | sort -nr

How do I correctly setup and teardown for my pytest class with tests?

This might help

In my test suite, I group my test cases into classes. For the setup and teardown I need for all the test cases in that class, I use the setup_class(cls) and teardown_class(cls) classmethods.

And for the setup and teardown I need for each of the test case, I use the setup_method(method) and teardown_method(methods)


lh = <got log handler from logger module>

class TestClass:
    def setup_class(cls):"starting class: {} execution".format(cls.__name__))

    def teardown_class(cls):"starting class: {} execution".format(cls.__name__))

    def setup_method(self, method):"starting execution of tc: {}".format(method.__name__))

    def teardown_method(self, method):"starting execution of tc: {}".format(method.__name__))

    def test_tc1(self):

    def test_tc2(self):

Now when I run my tests, when the TestClass execution is starting, it logs the details for when it is beginning execution, when it is ending execution and same for the methods..

You can add up other setup and teardown steps you might have in the respective locations.

Hope it helps!

Create a simple Login page using eclipse and mysql

You Can simply Use One Jsp Page To accomplish the task.

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.sql.*"%>
<!DOCTYPE html>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
        String username=request.getParameter("user_name");
        String password=request.getParameter("password");
        String role=request.getParameter("role");
            Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/t_fleet","root","root");
            Statement st=con.createStatement();
            String query="select * from tbl_login where user_name='"+username+"' and password='"+password+"' and role='"+role+"'";
            ResultSet rs=st.executeQuery(query);
                session.setAttribute( "user_name",rs.getString(2));

        catch(Exception e)


I have use username, password and role to get into the system. One more thing to implement is you can do page permission checking through jsp and javascript function.

How to hide Table Row Overflow?

Here´s something I tried. Basically, I put the "flexible" content (the td which contains lines that are too long) in a div container that´s one line high, with hidden overflow. Then I let the text wrap into the invisible. You get breaks at wordbreaks though, not just a smooth cut-off.

table {
    width: 100%;

.hideend {
    white-space: normal;
    overflow: hidden;
    max-height: 1.2em;
    min-width: 50px;
.showall {

        <td><div class="showall">Show all</div></td>
            <div class="hideend">Be a bit flexible about hiding stuff in a long sentence</div>
            <div class="showall">Show all this too</div>

How to get request URL in Spring Boot RestController

Add a parameter of type UriComponentsBuilder to your controller method. Spring will give you an instance that's preconfigured with the URI for the current request, and you can then customize it (such as by using MvcUriComponentsBuilder.relativeTo to point at a different controller using the same prefix).

Getting indices of True values in a boolean list

TL; DR: use np.where as it is the fastest option. Your options are np.where, itertools.compress, and list comprehension.

See the detailed comparison below, where it can be seen np.where outperforms both itertools.compress and also list comprehension.

>>> from itertools import compress
>>> import numpy as np
>>> t = [False, False, False, False, True, True, False, True, False, False, False, False, False, False, False, False]`
>>> t = 1000*t
  • Method 1: Using list comprehension
>>> %timeit [i for i, x in enumerate(t) if x]
457 µs ± 1.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
  • Method 2: Using itertools.compress
>>> %timeit list(compress(range(len(t)), t))
210 µs ± 704 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)
  • Method 3 (the fastest method): Using numpy.where
>>> %timeit np.where(t)
179 µs ± 593 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

Javascript Date - set just the date, ignoring time?

How about .toDateString()?

Alternatively, use .getDate(), .getMonth(), and .getYear()?

In my mind, if you want to group things by date, you simply want to access the date, not set it. Through having some set way of accessing the date field, you can compare them and group them together, no?

Check out all the fun Date methods here: MDN Docs

Edit: If you want to keep it as a date object, just do this:

var newDate = new Date(oldDate.toDateString());

Date's constructor is pretty smart about parsing Strings (though not without a ton of caveats, but this should work pretty consistently), so taking the old Date and printing it to just the date without any time will result in the same effect you had in the original post.

How to do constructor chaining in C#

All those answers are good, but I'd like to add a note on constructors with a little more complex initializations.

class SomeClass {
    private int StringLength;
    SomeClass(string x) {
         // this is the logic that shall be executed for all constructors.
         // you dont want to duplicate it.
         StringLength = x.Length;
    SomeClass(int a, int b): this(TransformToString(a, b)) {
    private static string TransformToString(int a, int b) {
         var c = a + b;
         return $"{a} + {b} = {c}";

Allthogh this example might as well be solved without this static function, the static function allows for more complex logic, or even calling methods from somewhere else.

Remove all unused resources from an android project

shift double click on Windows then type "unused", you will find an option Remove unused Resources,

 android {
        buildTypes {
            release {
                minifyEnabled true
                shrinkResources true

when you set these settings on, AS will automatically remove unused resources.

How to remove a package from Laravel using composer?

Got it working... The steps to remove a package from Laravel are:

  1. Remove declaration from composer.json (in "require" section)
  2. Remove Service Provider from config/app.php (reference in "providers" array)
  3. Remove any Class Aliases from config/app.php
  4. Remove any references to the package from your code :-)
  5. Run composer update vendor/package-name. This will remove the package folder from the vendor folder and will rebuild the composer autoloading map.
  6. Manually delete the published files (read the comment by zwacky)

It will remove the package folder from Vendor folder

Custom CSS for <audio> tag?

There is not currently any way to style HTML5 <audio> players using CSS. Instead, you can leave off the control attribute, and implement your own controls using Javascript. If you don't want to implement them all on your own, I'd recommend using an existing themeable HTML5 audio player, such as jPlayer.

How to view transaction logs in SQL Server 2008

You could use the undocumented

DBCC LOG(databasename, typeofoutput)

where typeofoutput:

0: Return only the minimum of information for each operation -- the operation, its context and the transaction ID. (Default)
1: As 0, but also retrieve any flags and the log record length.
2: As 1, but also retrieve the object name, index name, page ID and slot ID.
3: Full informational dump of each operation.
4: As 3 but includes a hex dump of the current transaction log row.

For example, DBCC LOG(database, 1)

You could also try fn_dblog.

For rolling back a transaction using the transaction log I would take a look at Stack Overflow post Rollback transaction using transaction log.

Error: Cannot find module '../lib/utils/unsupported.js' while using Ionic

On Mac OS X (10.12.6), I resolved this issue by doing the following:

brew uninstall --force node
brew install node

I then got an error complaining that node postinstall failed, and to rerun brew postinstall node

I then got an error:

permission denied @ rb_sysopen /usr/local/lib/node_modules/npm/bin/npx

I resolved that error by:

sudo chown -R $(whoami):admin /usr/local/lib/node_modules

And now I don't get this error any more.

setting an environment variable in virtualenv

Locally within an virtualenv there are two methods you could use to test this. The first is a tool which is installed via the Heroku toolbelt ( The tool is foreman. It will export all of your environment variables that are stored in a .env file locally and then run app processes within your Procfile.

The second way if you're looking for a lighter approach is to have a .env file locally then run:

export $(cat .env)

Xml serialization - Hide null values

You can define some default values and it prevents the fields from being serialized.

    [XmlElement, DefaultValue("")]
    string data;

    [XmlArray, DefaultValue(null)]
    List<string> data;

How to use C++ in Go

There's talk about interoperability between C and Go when using the gcc Go compiler, gccgo. There are limitations both to the interoperability and the implemented feature set of Go when using gccgo, however (e.g., limited goroutines, no garbage collection).

Convert iterator to pointer?

The direct answer to your question is yes. If foo is a vector, you can do this: &foo[1].

This only works for vectors however, because the standard says that vectors implement storage by using contigious memory.

But you still can (and probably should) pass iterators instead of raw pointers because it is more expressive. Passing iterators does not make a copy of the vector.

How to create a QR code reader in a HTML5 website?

The algorithm that drives is a JavaScript implementation of I haven't tried how reliable it is yet, but that's certainly the easier plug-and-play solution (client- or server-side) out of the two.

How to loop over grouped Pandas dataframe?

You can iterate over the index values if your dataframe has already been created.

df = df.groupby('l_customer_id_i').agg(lambda x: ','.join(x))
for name in df.index:
    print name
    print df.loc[name]

Git error: src refspec master does not match any

The quick possible answer: When you first successfully clone an empty git repository, the origin has no master branch. So the first time you have a commit to push you must do:

git push origin master

Which will create this new master branch for you. Little things like this are very confusing with git.

If this didn't fix your issue then it's probably a gitolite-related issue:

Your conf file looks strange. There should have been an example conf file that came with your gitolite. Mine looks like this:

repo    phonegap                                                                                                                                                                           
    RW+     =   myusername otherusername                                                                                                                                               

repo    gitolite-admin                                                                                                                                                                         
    RW+     =   myusername                                                                                                                                                               

Please make sure you're setting your conf file correctly.

Gitolite actually replaces the gitolite user's account with a modified shell that doesn't accept interactive terminal sessions. You can see if gitolite is working by trying to ssh into your box using the gitolite user account. If it knows who you are it will say something like "Hi XYZ, you have access to the following repositories: X, Y, Z" and then close the connection. If it doesn't know you, it will just close the connection.

Lastly, after your first git push failed on your local machine you should never resort to creating the repo manually on the server. We need to know why your git push failed initially. You can cause yourself and gitolite more confusion when you don't use gitolite exclusively once you've set it up.

Didn't find class ""?

I had the same issue and solved just add a piece of code, If you are getting this issue means you had already completed all the steps that need to use Firebase. You just need to create a class that extends the Application (public class Application_CrashReport extends Application ) and add this class in mainifest file and In that class just override the below method

protected void attachBaseContext(Context base) {

and add MultiDex.install(this); in that method means

protected void attachBaseContext(Context base) {

Note :- Don't forget to follow above steps

php timeout - set_time_limit(0); - don't work

Check the php.ini

ini_set('max_execution_time', 300); //300 seconds = 5 minutes

ini_set('max_execution_time', 0); //0=NOLIMIT

How to change content on hover

This exact example is present on mozilla developers page:


As you can see it even allows you to create tooltips! :) Also, instead of embedding the actual text in your CSS, you may use content: attr(data-descr);, and store it in data-descr="ADD" attribute of your HTML tag (which is nice because you can e.g translate it)

CSS content can only be usef with :after and :before pseudo-elements, so you can try to proceed with something like this:

.item a span:after{
  position: relative;
  content: 'NEW'
.item:hover a span:after {
  content: 'ADD';

The CSS :after pseudo-element matches a virtual last child of the selected element. Typically used to add cosmetic content to an element, by using the content CSS property. This element is inline by default.

ORA-12505: TNS:listener does not currently know of SID given in connect descriptor (DBD ERROR: OCIServerAttach)

The following worked for me (Windows 7):

oradim -shutdown -sid enter_sid_here
oradim -startup -sid enter_sid_here

(with enter_sid_here replaced by the SID)

Differences between fork and exec

fork() splits the current process into two processes. Or in other words, your nice linear easy to think of program suddenly becomes two separate programs running one piece of code:

 int pid = fork();

 if (pid == 0)
     printf("I'm the child");
     printf("I'm the parent, my child is %i", pid);
     // here we can kill the child, but that's not very parently of us

This can kind of blow your mind. Now you have one piece of code with pretty much identical state being executed by two processes. The child process inherits all the code and memory of the process that just created it, including starting from where the fork() call just left off. The only difference is the fork() return code to tell you if you are the parent or the child. If you are the parent, the return value is the id of the child.

exec is a bit easier to grasp, you just tell exec to execute a process using the target executable and you don't have two processes running the same code or inheriting the same state. Like @Steve Hawkins says, exec can be used after you forkto execute in the current process the target executable.

Key value pairs using JSON

A "JSON object" is actually an oxymoron. JSON is a text format describing an object, not an actual object, so data can either be in the form of JSON, or deserialised into an object.

The JSON for that would look like this:


Once you have parsed the JSON into a Javascript object (called data in the code below), you can for example access the object for KEY2 and it's properties like this:

var obj = data.KEY2;

If you have the key as a string, you can use index notation:

var key = 'KEY3';
var obj = data[key];

Registry Key '...' has value '1.7', but '1.6' is required. Java 1.7 is Installed and the Registry is Pointing to it

In the START menu type "regedit" to open the Registry editor

Go to "HKEY_LOCAL_MACHINE" on the left-hand side registry explorer/tree menu

Click "SOFTWARE" within the "HKEY_LOCAL_MACHINE" registries

Click "JavaSoft" within the "SOFTWARE" registries

Click "Java Runtime Environment" within the "JavaSoft" list of registries here you can see different versions of installed java

Click "Java Runtime Environment"- On right hand side you will get 4-5 rows . Please select "CurrentVersion" and right Click( select modify option) Change version to "1.7"

Now the magic has been completed

how to detect search engine bots with php?

I use this function ... part of the regex comes from prestashop but I added some more bot to it.

    public function isBot()
    $bot_regex = '/BotLink|bingbot|AhrefsBot|ahoy|AlkalineBOT|anthill|appie|arale|araneo|AraybOt|ariadne|arks|ATN_Worldwide|Atomz|bbot|Bjaaland|Ukonline|borg\-bot\/0\.9|boxseabot|bspider|calif|christcrawler|CMC\/0\.01|combine|confuzzledbot|CoolBot|cosmos|Internet Cruiser Robot|cusco|cyberspyder|cydralspider|desertrealm, desert realm|digger|DIIbot|grabber|downloadexpress|DragonBot|dwcp|ecollector|ebiness|elfinbot|esculapio|esther|fastcrawler|FDSE|FELIX IDE|ESI|fido|H?m?h?kki|KIT\-Fireball|fouineur|Freecrawl|gammaSpider|gazz|gcreep|golem|googlebot|griffon|Gromit|gulliver|gulper|hambot|havIndex|hotwired|htdig|iajabot|INGRID\/0\.1|Informant|InfoSpiders|inspectorwww|irobot|Iron33|JBot|jcrawler|Teoma|Jeeves|jobo|image\.kapsi\.net|KDD\-Explorer|ko_yappo_robot|label\-grabber|larbin|legs|Linkidator|linkwalker|Lockon|logo_gif_crawler|marvin|mattie|mediafox|MerzScope|NEC\-MeshExplorer|MindCrawler|udmsearch|moget|Motor|msnbot|muncher|muninn|MuscatFerret|MwdSearch|sharp\-info\-agent|WebMechanic|NetScoop|newscan\-online|ObjectsSearch|Occam|Orbsearch\/1\.0|packrat|pageboy|ParaSite|patric|pegasus|perlcrawler|phpdig|piltdownman|Pimptrain|pjspider|PlumtreeWebAccessor|PortalBSpider|psbot|Getterrobo\-Plus|Raven|RHCS|RixBot|roadrunner|Robbie|robi|RoboCrawl|robofox|Scooter|Search\-AU|searchprocess|Senrigan|Shagseeker|sift|SimBot|Site Valet|skymob|SLCrawler\/2\.0|slurp|ESI|snooper|solbot|speedy|spider_monkey|SpiderBot\/1\.0|spiderline|nil|suke|http:\/\/www\.sygol\.com|tach_bw|TechBOT|templeton|titin|topiclink|UdmSearch|urlck|Valkyrie libwww\-perl|verticrawl|Victoria|void\-bot|Voyager|VWbot_K|crawlpaper|wapspider|WebBandit\/1\.0|webcatcher|T\-H\-U\-N\-D\-E\-R\-S\-T\-O\-N\-E|WebMoose|webquest|webreaper|webs|webspider|WebWalker|wget|winona|whowhere|wlm|WOLP|WWWC|none|XGET|Nederland\.zoek|AISearchBot|woriobot|NetSeer|Nutch|YandexBot|YandexMobileBot|SemrushBot|FatBot|MJ12bot|DotBot|AddThis|baiduspider|SeznamBot|mod_pagespeed|CCBot|\/Bot|m2e/i';
    $userAgent = empty($_SERVER['HTTP_USER_AGENT']) ? FALSE : $_SERVER['HTTP_USER_AGENT'];
    $isBot = !$userAgent || preg_match($bot_regex, $userAgent);

    return $isBot;

Anyway take care that some bots uses browser like user agent to fake their identity
( I got many russian ip that has this behaviour on my site )

One distinctive feature of most of the bot is that they don't carry any cookie and so no session is attached to them.
( I am not sure how but this is for sure the best way to track them )

How to debug Lock wait timeout exceeded on MySQL?

Extrapolating from Rolando's answer above, it is these that are blocking your query:

---TRANSACTION 0 620783788, not started, process no 29956, OS thread id 1196472640
MySQL thread id 5341773, query id 189708353 viget

If you need to execute your query and can not wait for the others to run, kill them off using the MySQL thread id:

kill 5341773 <replace with your thread id>

(from within mysql, not the shell, obviously)

You have to find the thread IDs from the:

show engine innodb status\G

command, and figure out which one is the one that is blocking the database.

How can I prevent java.lang.NumberFormatException: For input string: "N/A"?

Obviously you can't parse N/A to int value. you can do something like following to handle that NumberFormatException .

   String str="N/A";
   try {
        int val=Integer.parseInt(str);
   }catch (NumberFormatException e){
       System.out.println("not a number"); 

setting request headers in selenium

With the solutions already discussed above the most reliable one is using Browsermob-Proxy

But while working with the remote grid machine, Browsermob-proxy isn't really helpful.

This is how I fixed the problem in my case. Hopefully, might be helpful for anyone with a similar setup.

  1. Add the ModHeader extension to the chrome browser

How to download the Modheader? Link

ChromeOptions options = new ChromeOptions();
options.addExtensions(new File(C://Downloads//modheader//modheader.crx));

// Set the Desired capabilities 
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(ChromeOptions.CAPABILITY, options);

// Instantiate the chrome driver with capabilities
WebDriver driver = new RemoteWebDriver(new URL(YOUR_HUB_URL), options);
  1. Go to the browser extensions and capture the Local Storage context ID of the ModHeader

Capture ID from ModHeader

  1. Navigate to the URL of the ModHeader to set the Local Storage Context


// set the context on the extension so the localStorage can be accessed

Where `idgpnmonknjnojddfkpgkljpfnnfcklj` is the value captured from the Step# 2
  1. Now add the headers to the request using Javascript


         "localStorage.setItem('profiles', JSON.stringify([{  title: 'Selenium', hideComment: true, appendMode: '', 
             headers: [                        
               {enabled: true, name: 'token-1', value: 'value-1', comment: ''},
               {enabled: true, name: 'token-2', value: 'value-2', comment: ''}
             respHeaders: [],
             filters: []

Where token-1, value-1, token-2, value-2 are the request headers and values that are to be added.

  1. Now navigate to the required web-application.


Angular.js How to change an elements css class on click and to remove all others


<span ng-class="{'item-text-wrap':viewMore}" ng-click="viewMore= !viewMore"></span>

git push to specific branch

If your Local branch and remote branch is the same name then you can just do it:

git push origin branchName

When your local and remote branch name is different then you can just do it:

git push origin localBranchName:remoteBranchName

Hide html horizontal but not vertical scrollbar

Using wrap=virtual in your HTML form boxes gets rid of the horizontal scrollbar at the bottom of the box:

  <textarea name= "enquiry" rows="4" cols="30" wrap="virtual"></textarea>

See example here : (Tested on FF and IE)

Unlink of file Failed. Should I try again?

As stated above, something else is holding the files. Thing is that program doesnt look suspicious for us. I was trying to do a git pull from console, while having GitKraken opened. Closing GitKraken fixed the problem.

How to delete directory content in Java?

You can't delete an File array. As all of the other answers suggest, you must delete each individual file before deleting the folder...

final File[] files = outputFolder.listFiles();
for (File f: files) f.delete();

Changing background color of selected cell?

I had a recent issue with an update to Swift 5 where the table view would flash select and then deselect the selected cell. I tried several of the solutions here and none worked. The solution is setting clearsSelectionOnViewWillAppear to false.

I had previously used the UIView and selectedBackgroundColor property, so I kept with that approach.

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  let cell = tableView.dequeueReusableCell(withIdentifier: "popoverCell", for: indexPath) as! PopoverCell

  let backgroundView = UIView()
  backgroundView.backgroundColor = Color.Blue
  cell.selectedBackgroundView = backgroundView

Below are the changes I needed for Swift 5. The property clearsSelectionOnViewWillAppear was the reason my cells were deselecting. The following select was necessary on first load.

override func viewDidLoad() {

  clearsSelectionOnViewWillAppear = false
  popoverTableView.selectRow(at: selectedIndexPath, animated: false, scrollPosition: .none)

How can I convert spaces to tabs in Vim or Linux?

1 - If you have spaces and want tabs.

First, you need to decide how many spaces will have a single tab. That said, suppose you have lines with leading 4 spaces, or 8... Than you realize you probably want a tab to be 4 spaces. Now with that info, you do:

:set ts=4
:set noet

There is a problem here! This sequence of commands will look for all your text, not only spaces in the begin of the line. That mean a string like: "Hey,?this????is?4?spaces" will become "Hey,?this?is?4?spaces", but its not! its a tab!.

To settle this little problem I recomend a search, instead of retab.


This search will look in the whole file for any lines starting with whatever number of tabs, followed by 4 spaces, and substitute it for whatever number of tabs it found plus one.

This, unfortunately, will not run at once!

At first, the file will have lines starting with spaces. The search will then convert only the first 4 spaces to a tab, and let the following...

You need to repeat the command. How many times? Until you get a pattern not found. I cannot think of a way to automatize the process yet. But if you do:


You are probably done. This command repeats the last search/replace for 10 times. Its not likely your program will have so many indents. If it has, just repeat again @@.

Now, just to complete the answer. I know you asked for the opposite, but you never know when you need to undo things.

2 - You have tabs and want spaces.

First, decide how many spaces you want your tabs to be converted to. Lets say you want each tab to be 2 spaces. You then do:

:set ts=2
:set et

This would have the same problem with strings. But as its better programming style to not use hard tabs inside strings, you actually are doing a good thing here. If you really need a tab inside a string, use \t.

When to use async false and async true in ajax function in jquery

ShowPopUpForToDoList: function (id, apprId, tab) {
    var snapShot = "isFromAlert";
    if (tab != "Request")
        snapShot = "isFromTodoList";
        type: "GET",
        url: common.GetRootUrl('ActionForm/SetParamForToDoList'),
        data: { id: id, tab: tab },
        success: function (data) {
            ActionForm.EditActionFormPopup(id, snapShot);

Here SetParamForToDoList will be excecuted first after the function ActionForm.EditActionFormPopup will fire.

How to get substring in C

If you just want to print the substrings ...

size_t i, slen = strlen(s);
for (i = 0; i < slen; i += 4) {
  printf("%.4s\n", s + i);

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver in Eclipse

It is because the WEB-INF folder does not exist at the location in the sub directory in the error. You either compile the application to use the WEB-INF folder under public_html OR copy the WEB-INF folder in sub folder as in the error above.

How to use icons and symbols from "Font Awesome" on Native Android Application

In case you only need a few font awesome icons, you can also use to generate normal pixel images. But if you add new icons/buttons regularly I'd recommend the .ttf version as its more flexible.

Set cellpadding and cellspacing in CSS?


The default behavior of the browser is equivalent to:

table {border-collapse: collapse;}
td    {padding: 0px;}

         Enter image description here


Sets the amount of space between the contents of the cell and the cell wall

table {border-collapse: collapse;}
td    {padding: 6px;}

        Enter image description here


Controls the space between table cells

table {border-spacing: 2px;}
td    {padding: 0px;}

        Enter image description here


table {border-spacing: 2px;}
td    {padding: 6px;}

        Enter image description here

Both (special)

table {border-spacing: 8px 2px;}
td    {padding: 6px;}

        Enter image description here

Note: If there is border-spacing set, it indicates border-collapse property of the table is separate.

Try it yourself!

Here you can find the old HTML way of achieving this.

Missing artifact

You can also create a project repository. It's useful if more developers are working on the same project, and the library must be included in the project.

  • First, create a repository structure in your project's lib directory, and then copy the library into it. The library must have following name-format: <artifactId>-<version>.jar


  • Create pom file next to the library file, and put following information into it:

    <?xml version="1.0" encoding="UTF-8"?>
     <project xsi:schemaLocation="" xmlns=""
  • At this point, you should have this directory structure:

    <your_project_dir>/lib/com/microsoft/sqlserver/sqljdbc4/4.2/sqljdbc4-4.2.jar <your_project_dir>/lib/com/microsoft/sqlserver/sqljdbc4/4.2/sqljdbc4-4.2.pom

  • Go to your project's pom file and add new repository:

             <id>Project repository</id>
  • Finally, add a dependency on the library:


Update 2017-03-04

It seems like the library can be obtained from publicly available repository. @see nirmal's and Jacek Grzelaczyk's answers for more details.

Update 2020-11-04

Currently Maven has a convenient target install which allow you to deploy an existing package into a project / file repository without the need of creating POM files manually. It will generate those files for you.

mvn install:install-file \
    -Dfile=sqljdbc4.jar \ \
    -DartifactId=sqljdbc4 \
    -Dversion=4.2 \
    -Dpackaging=jar \

Where can I find MySQL logs in phpMyAdmin?

If you are using XAMPP as your server, you'll find a logs directory as a child of the XAMPP directory. If you have not tried XAMPP, which runs on any system (Windows, Mac OS & Linux) find more here:

How to select top n rows from a datatable/dataview in ASP.NET


Simple if else onclick then do?

The preferred modern method is to use addEventListener either by adding the event listener direct to the element or to a parent of the elements (delegated).

An example, using delegated events, might be

var box = document.getElementById('box');_x000D_
document.getElementById('buttons').addEventListener('click', function(evt) {_x000D_
  var target =;_x000D_
  if ( === 'yes') {_x000D_ = 'red';_x000D_
  } else if ( === 'no') {_x000D_ = 'green';_x000D_
  } else {_x000D_ = 'purple';_x000D_
}, false);
#box {_x000D_
  width: 200px;_x000D_
  height: 200px;_x000D_
  background-color: red;_x000D_
#buttons {_x000D_
  margin-top: 50px;_x000D_
<div id='box'></div>_x000D_
<div id='buttons'>_x000D_
  <button id='yes'>yes</button>_x000D_
  <button id='no'>no</button>_x000D_
  <p>Click one of the buttons above.</p>_x000D_

Understanding MongoDB BSON Document size limit

Perhaps storing a blog post -> comments relation in a non-relational database is not really the best design.

You should probably store comments in a separate collection to blog posts anyway.


See comments below for further discussion.

Calling a function on bootstrap modal open

if somebody still has a problem the only thing working perfectly for me by useing ( :

 $('#editModal').on('', function () {
       console.log('edit modal loaded');

            dateFormat: 'yy-mm-dd',
            clearBtn: true,
            rtl: false,
            todayHighlight: true,
            toggleActive: true,
            changeYear: true,
            changeMonth: true

How can I divide two integers stored in variables in Python?

The 1./2 syntax works because 1. is a float. It's the same as 1.0. The dot isn't a special operator that makes something a float. So, you need to either turn one (or both) of the operands into floats some other way -- for example by using float() on them, or by changing however they were calculated to use floats -- or turn on "true division", by using from __future__ import division at the top of the module.

gitbash command quick reference

git-bash uses standard unix commands.

ls for directory listing cd for change directory

more here -> Not all of these will work, but the file based ones mostly do.

"Press Any Key to Continue" function in C

Try this:-

printf("Let the Battle Begin!\n");
printf("Press Any Key to Continue\n");

getch() is used to get a character from console but does not echo to the screen.

Why would one use nested classes in C++?

I don't use nested classes much, but I do use them now and then. Especially when I define some kind of data type, and I then want to define a STL functor designed for that data type.

For example, consider a generic Field class that has an ID number, a type code and a field name. If I want to search a vector of these Fields by either ID number or name, I might construct a functor to do so:

class Field
  unsigned id_;
  string name_;
  unsigned type_;

  class match : public std::unary_function<bool, Field>
    match(const string& name) : name_(name), has_name_(true) {};
    match(unsigned id) : id_(id), has_id_(true) {};
    bool operator()(const Field& rhs) const
      bool ret = true;
      if( ret && has_id_ ) ret = id_ == rhs.id_;
      if( ret && has_name_ ) ret = name_ == rhs.name_;
      return ret;
      unsigned id_;
      bool has_id_;
      string name_;
      bool has_name_;

Then code that needs to search for these Fields can use the match scoped within the Field class itself:

vector<Field>::const_iterator it = find_if(fields.begin(), fields.end(), Field::match("FieldName"));

How do I search a Perl array for a matching string?

Perl string match can also be used for a simple yes/no.

my @foo=("hello", "world", "foo", "bar");

if ("@foo" =~ /\bhello\b/){
    print "found";
    print "not found";

How to remove the focus from a TextBox in WinForms?

You can also set the forms activecontrol property to null like

ActiveControl = null;

How to Alter a table for Identity Specification is identity SQL Server

You cannot "convert" an existing column into an IDENTITY column - you will have to create a new column as INT IDENTITY:

ALTER TABLE ProductInProduct 


OK, so there is a way of converting an existing column to IDENTITY. If you absolutely need this - check out this response by Martin Smith with all the gory details.

JQuery .hasClass for multiple values in an if statement

Here is a slight variation on answer offered by jfriend00:

$.fn.hasAnyClass = function() {
    var classes = arguments[0].split(" ");
    for (var i = 0; i < classes.length; i++) {
        if (this.hasClass(classes[i])) {
            return true;
    return false;

Allows use of same syntax as .addClass() and .removeClass(). e.g., .hasAnyClass('m320 m768') Needs bulletproofing, of course, as it assumes at least one argument.

How to remove commits from a pull request

If you're removing a commit and don't want to keep its changes @ferit has a good solution.

If you want to add that commit to the current branch, but doesn't make sense to be part of the current pr, you can do the following instead:

  1. use git rebase -i HEAD~n
  2. Swap the commit you want to remove to the bottom (most recent) position
  3. Save and exit
  4. use git reset HEAD^ --soft to uncommit the changes and get them back in a staged state.
  5. use git push --force to update the remote branch without your removed commit.

Now you'll have removed the commit from your remote, but will still have the changes locally.

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

In Designer, activate the centralWidget and assign a layout, e.g. horizontal or vertical layout. Then your QFormLayout will automatically resize.

Image of Designer

Always make sure, that all widgets have a layout! Otherwise, automatic resizing will break with that widget!

See also

Controls insist on being too large, and won't resize, in QtDesigner

How do I truly reset every setting in Visual Studio 2012?

How to hard reset Visual Studio instance

When developing extensions sometimes you just mess up, others someone else does. If you start getting errors loading even the most mundane extensions, these are the instructions to hard reset your instance.

Close Visual Studio (if you haven’t already).
Open the registry editor (regedit.exe)
Delete the HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\{version}
Delete the HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\{version}_Config
Delete the %LOCALAPPDATA%\Microsoft\VisualStudio\{version} directory.

Enjoy your brand new Visual Studio instance.

  • Use {version}=10.0 for Visual Studio 2010
  • Use {version}=11.0 for Visual Studio 2012
  • Use {version}=12.0 for Visual Studio 2013

If on the other side you want to reset the experimental hive you can do the same to with the ‘{version}Exp’ ones.

Happy coding!


How do you share constants in NodeJS modules?

import and export (prob need something like babel as of 2018 to use import)


export const BLUE = 'BLUE'
export const RED = 'RED'


import * as types from './types.js'

const MyApp = () => {
  let colour = types.RED

convert json ipython notebook(.ipynb) to .py file

According to you are looking for the nbconvert command with the --to script option.

ipython nbconvert notebook.ipynb --to script

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

My resolution was to login using the Windows Login then go to security>Logins locate the troubled ID And retype the used password. The restart the services...

Fixing Segmentation faults in C++

Sometimes the crash itself isn't the real cause of the problem-- perhaps the memory got smashed at an earlier point but it took a while for the corruption to show itself. Check out valgrind, which has lots of checks for pointer problems (including array bounds checking). It'll tell you where the problem starts, not just the line where the crash occurs.

How to export SQL Server database to MySQL?

You can do this easily by using Data Loader tool. I have already done this before using this tool and found it good.

Converting .NET DateTime to JSON

the conversion from 1970,1,1 needs the double rounded to zero decimal places i thinks

DateTime d1 = new DateTime(1970, 1, 1);
DateTime d2 = dt.ToUniversalTime();
TimeSpan ts = new TimeSpan(d2.Ticks - d1.Ticks);
return Math.Round( ts.TotalMilliseconds,0);

on the client side i use

new Date(+data.replace(/\D/g, ''));

Find row where values for column is maximal in a pandas DataFrame

Very simple: we have df as below and we want to print a row with max value in C:

A  B  C
x  1  4
y  2  10
z  5  9


df.loc[df['C'] == df['C'].max()]   # condition check


y 2 10

jQuery Scroll to bottom of page/iframe


I use this code to scroll the chat when new messages arrive.

What's the best way to cancel event propagation between nested ng-click calls?

<div ng-click="methodName(event)"></div>

IN controller use

$scope.methodName = function(event) { 

Execute SQL script from command line

If you use Integrated Security, you might want to know that you simply need to use -E like this:

sqlcmd -S Serverinstance -E -i import_file.sql

Is this how you define a function in jQuery?

The following example show you how to define a function in jQuery. You will see a button “Click here”, when you click on it, we call our function “myFunction()”.

    $.myFunction = function(){ 
      alert('You have successfully defined the function!'); 

You can see an example here: How to define a function in jQuery?

Horizontal Scroll Table in Bootstrap/CSS

@Ciwan. You're right. The table goes to full width (much too wide). Not a good solution. Better to do this:


.scrollme {
    overflow-x: auto;


<div class="scrollme">                        
  <table class="table table-responsive"> ...

Edit: changing scroll-y to scroll-x

How to find my php-fpm.sock?

Check the config file, the config path is /etc/php5/fpm/pool.d/www.conf, there you'll find the path by config and if you want you can change it.

well you're correct, you need to replace listen = to listen = /var/run/php5-fpm/php5-fpm.sock, then you need to run sudo service php5-fpm restart, and make sure it says that it restarted correctly, if not then make sure that /var/run/ has a folder called php5-fpm, or make it listen to /var/run/php5-fpm.sock cause i don't think the folder inside /var/run is created automatically, i remember i had to edit the start up script to create that folder, otherwise even if you mkdir /var/run/php5-fpm after restart that folder will disappear and the service starting will fail.

How to upload a file in Django?

I must say I find the documentation at django confusing. Also for the simplest example why are forms being mentioned? The example I got to work in the is :-

for key, file in request.FILES.items():
    path =
    dest = open(path, 'w')
    if file.multiple_chunks:
        for c in file.chunks():

The html file looks like the code below, though this example only uploads one file and the code to save the files handles many :-

<form action="/upload_file/" method="post" enctype="multipart/form-data">{% csrf_token %}
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />

These examples are not my code, they have been optained from two other examples I found. I am a relative beginner to django so it is very likely I am missing some key point.

How can I decode HTML characters in C#?

If there is no Server context (i.e your running offline), you can use HttpUtility.HtmlDecode.

Remove a symlink to a directory

# this works:
rm foo
# versus this, which doesn't:
rm foo/

Basically, you need to tell it to delete a file, not delete a directory. I believe the difference between rm and rmdir exists because of differences in the way the C library treats each.

At any rate, the first should work, while the second should complain about foo being a directory.

If it doesn't work as above, then check your permissions. You need write permission to the containing directory to remove files.

How to list active connections on PostgreSQL?

Following will give you active connections/ queries in postgres DB-

FROM pg_stat_activity
WHERE state = 'active';

You may use 'idle' instead of active to get already executed connections/queries.

Does java.util.List.isEmpty() check if the list itself is null?

In addition to Lion's answer i can say that you better use if(CollectionUtils.isNotEmpty(test)){...} This also checks for null, so no manual check is not needed.

Python Prime number checker

max=int(input("Find primes upto what numbers?"))
for x in range(2,max+1):
    for y in range(2,int(x**0.5)+1) :
        if x%y==0:

    if isPrime:

How to print a string multiple times?

The question is a bit unclear can't you just repeat the for loop?


for i in a:
    print i

for i in a:
    print i

How to add buttons like refresh and search in ToolBar in Android?

OK, I got the icons because I wrote in menu.xml android:showAsAction="ifRoom" instead of app:showAsAction="ifRoom" since i am using v7 library.

However the title is coming at center of extended toolbar. How to make it appear at the top?

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

//get the value of a gridview
public string getUpdatingGridviewValue(GridView gridviewEntry, string fieldEntry)
    {//start getGridviewValue
        //scan gridview for cell value
            string result = Convert.ToString(functionsOther.getCurrentTime()); 
            for(int i = 0; i < gridviewEntry.HeaderRow.Cells.Count; i++)
                {//start i for
                    if(gridviewEntry.HeaderRow.Cells[i].Text == fieldEntry)
                        {//start check field match
                            result = gridviewEntry.Rows[rowUpdateIndex].Cells[i].Text;
                        }//end check field match
                }//end i for
            return result;
    }//end getGridviewValue

Pure CSS collapse/expand div

Depending on what browsers/devices you are looking to support, or what you are prepared to put up with for non-compliant browsers you may want to check out the <summary> and <detail> tags. They are for exactly this purpose. No css is required at all as the collapsing and showing are part of the tags definition/formatting.

I've made an example here:

<summary>This is what you want to show before expanding</summary>
<p>This is where you put the details that are shown once expanded</p>

Browser support varies. Try in webkit for best results. Other browsers may default to showing all the solutions. You can perhaps fallback to the hide/show method described above.

Add User to Role ASP.NET Identity

Below is an alternative implementation of a 'create user' controller method using Claims based roles.

The created claims then work with the Authorize attribute e.g. [Authorize(Roles = "Admin, User.*, User.Create")]

    // POST api/User/Create
    public async Task<IHttpActionResult> Create([FromBody]CreateUserModel model)
        if (!ModelState.IsValid)
            return BadRequest(ModelState);

        // Generate long password for the user
        var password = System.Web.Security.Membership.GeneratePassword(25, 5);

        // Create the user
        var user = new ApiUser() { UserName = model.UserName };
        var result = await UserManager.CreateAsync(user, password);
        if (!result.Succeeded)
            return GetErrorResult(result);

        // Add roles (permissions) for the user
        foreach (var perm in model.Permissions)
            await UserManager.AddClaimAsync(user.Id, new Claim(ClaimTypes.Role, perm));

        return Ok<object>(new { UserName = user.UserName, Password = password });

What does the "@" symbol do in Powershell?

PowerShell will actually treat any comma-separated list as an array:


So the @ is optional in those cases. However, for associative arrays, the @ is required:


Officially, @ is the "array operator." You can read more about it in the documentation that installed along with PowerShell, or in a book like "Windows PowerShell: TFM," which I co-authored.

OpenCV NoneType object has no attribute shape

This is because the path of image is wrong or the name of image you write is incorrect .

how to check? first try to print the image using print(img) if it prints 'None' that means you have given wrong image path correct that path and try again.

How can I pass arguments to anonymous functions in JavaScript?


<input type="button" value="Click me" id="myButton">
    var myButton = document.getElementById("myButton");
    var test = "zipzambam";
    myButton.onclick = function(eventObject) {
        if (!eventObject) {
            eventObject = window.event;
        if (! {
   = eventObject.srcElement;
    (function(myMessage) {

How to "properly" create a custom object in JavaScript?

To continue off of bobince's answer

In es6 you can now actually create a class

So now you can do:

class Shape {
    constructor(x, y) {
        this.x = x;
        this.y = y;

    toString() {
        return `Shape at ${this.x}, ${this.y}`;

So extend to a circle (as in the other answer) you can do:

class Circle extends Shape {
    constructor(x, y, r) {
        super(x, y);
        this.r = r;

    toString() {
        let shapeString = super.toString();
        return `Circular ${shapeString} with radius ${this.r}`;

Ends up a bit cleaner in es6 and a little easier to read.

Here is a good example of it in action:

class Shape {_x000D_
  constructor(x, y) {_x000D_
    this.x = x;_x000D_
    this.y = y;_x000D_
  toString() {_x000D_
    return `Shape at ${this.x}, ${this.y}`;_x000D_
class Circle extends Shape {_x000D_
  constructor(x, y, r) {_x000D_
    super(x, y);_x000D_
    this.r = r;_x000D_
  toString() {_x000D_
    let shapeString = super.toString();_x000D_
    return `Circular ${shapeString} with radius ${this.r}`;_x000D_
let c = new Circle(1, 2, 4);_x000D_
console.log('' + c, c);

Spring RestTemplate - how to enable full debugging/logging of requests/responses?

Logging RestTemplate

Option 1. Open debug logging.

Configurate RestTemplate

  • By default the RestTemplate relies on standard JDK facilities to establish HTTP connections. You can switch to use a different HTTP library such as Apache HttpComponents

    @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { RestTemplate restTemplate =; return restTemplate; }

Configurate logging

  • application.yml

    logging: level: org.springframework.web.client.RestTemplate: DEBUG

Option 2. Using Interceptor

Wrapper Response


import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.util.StreamUtils;

public final class BufferingClientHttpResponseWrapper implements ClientHttpResponse {

    private final ClientHttpResponse response;

    private byte[] body;

    BufferingClientHttpResponseWrapper(ClientHttpResponse response) {
        this.response = response;

    public HttpStatus getStatusCode() throws IOException {
        return this.response.getStatusCode();

    public int getRawStatusCode() throws IOException {
        return this.response.getRawStatusCode();

    public String getStatusText() throws IOException {
        return this.response.getStatusText();

    public HttpHeaders getHeaders() {
        return this.response.getHeaders();

    public InputStream getBody() throws IOException {
        if (this.body == null) {
            this.body = StreamUtils.copyToByteArray(this.response.getBody());
        return new ByteArrayInputStream(this.body);

    public void close() {

Implement Interceptor

package com.example.logging;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;

public class LoggingRestTemplate implements ClientHttpRequestInterceptor {

    private final static Logger LOGGER = LoggerFactory.getLogger(LoggingRestTemplate.class);

    public ClientHttpResponse intercept(HttpRequest request, byte[] body,
            ClientHttpRequestExecution execution) throws IOException {
        traceRequest(request, body);
        ClientHttpResponse response = execution.execute(request, body);
        return traceResponse(response);

    private void traceRequest(HttpRequest request, byte[] body) throws IOException {
        if (!LOGGER.isDebugEnabled()) {
                "==========================request begin==============================================");
        LOGGER.debug("URI                 : {}", request.getURI());
        LOGGER.debug("Method            : {}", request.getMethod());
        LOGGER.debug("Headers         : {}", request.getHeaders());
        LOGGER.debug("Request body: {}", new String(body, "UTF-8"));
                "==========================request end================================================");

    private ClientHttpResponse traceResponse(ClientHttpResponse response) throws IOException {
        if (!LOGGER.isDebugEnabled()) {
            return response;
        final ClientHttpResponse responseWrapper = new BufferingClientHttpResponseWrapper(response);
        StringBuilder inputStringBuilder = new StringBuilder();
        BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(responseWrapper.getBody(), "UTF-8"));
        String line = bufferedReader.readLine();
        while (line != null) {
            line = bufferedReader.readLine();
                "==========================response begin=============================================");
        LOGGER.debug("Status code    : {}", responseWrapper.getStatusCode());
        LOGGER.debug("Status text    : {}", responseWrapper.getStatusText());
        LOGGER.debug("Headers            : {}", responseWrapper.getHeaders());
        LOGGER.debug("Response body: {}", inputStringBuilder.toString());
                "==========================response end===============================================");
        return responseWrapper;


Configurate RestTemplate

public RestTemplate restTemplate(RestTemplateBuilder builder) {
    RestTemplate restTemplate =;
    restTemplate.setInterceptors(Collections.singletonList(new LoggingRestTemplate()));
    return restTemplate;

Configurate logging

  • Check the package of LoggingRestTemplate, for example in application.yml:

    logging: level: com.example.logging: DEBUG

Option 3. Using httpcomponent

Import httpcomponent dependency


Configurate RestTemplate

public RestTemplate restTemplate(RestTemplateBuilder builder) {
    RestTemplate restTemplate =;
    restTemplate.setRequestFactory(new HttpComponentsAsyncClientHttpRequestFactory());
    return restTemplate;

Configurate logging

  • Check the package of LoggingRestTemplate, for example in application.yml:

    logging: level: org.apache.http: DEBUG

What is the difference between aggregation, composition and dependency?

Aggregation and composition are almost completely identical except that composition is used when the life of the child is completely controlled by the parent.


Car -> Tires

The Tires can be taken off of the Car object and installed on a different one. Also, if the car gets totaled, the tires do not necessarily have to be destroyed.


Body -> Blood Cell

When the Body object is destroyed the BloodCells get destroyed with it.


A relationship between two objects where changing one may affect the other.

how to implement Pagination in reactJs

I have tried to recreate the simple pagination example given by piotr-berebecki which was great. But when there will be a lot of pages then the pagination will overflow in the screen. So, I used previous and back button along with forward and backward button to stream back and forth between the pages. And for design part I have used bootstrap 3.

You can customize no of pages to display in pagination using the pagebound values. Make sure to use same value for upperPageBound and pageBound.

    class TodoApp extends React.Component {
          constructor() {
            this.state = {
              todos: ['a','b','c','d','e','f','g','h','i','j','k','l','m',
              currentPage: 1,
              todosPerPage: 3,
              upperPageBound: 3,
              lowerPageBound: 0,
              isPrevBtnActive: 'disabled',
              isNextBtnActive: '',
              pageBound: 3
            this.handleClick = this.handleClick.bind(this);
            this.btnDecrementClick = this.btnDecrementClick.bind(this);
            this.btnIncrementClick = this.btnIncrementClick.bind(this);
            this.btnNextClick = this.btnNextClick.bind(this);
            this.btnPrevClick = this.btnPrevClick.bind(this);
            // this.componentDidMount = this.componentDidMount.bind(this);
            this.setPrevAndNextBtnClass = this.setPrevAndNextBtnClass.bind(this);
          componentDidUpdate() {
                $('ul li#'+this.state.currentPage).addClass('active');
          handleClick(event) {
            let listid = Number(;
              currentPage: listid
            $('ul li#'+listid).addClass('active');
          setPrevAndNextBtnClass(listid) {
            let totalPage = Math.ceil(this.state.todos.length / this.state.todosPerPage);
            this.setState({isNextBtnActive: 'disabled'});
            this.setState({isPrevBtnActive: 'disabled'});
            if(totalPage === listid && totalPage > 1){
                this.setState({isPrevBtnActive: ''});
            else if(listid === 1 && totalPage > 1){
                this.setState({isNextBtnActive: ''});
            else if(totalPage > 1){
                this.setState({isNextBtnActive: ''});
                this.setState({isPrevBtnActive: ''});
          btnIncrementClick() {
              this.setState({upperPageBound: this.state.upperPageBound + this.state.pageBound});
              this.setState({lowerPageBound: this.state.lowerPageBound + this.state.pageBound});
              let listid = this.state.upperPageBound + 1;
              this.setState({ currentPage: listid});
          btnDecrementClick() {
            this.setState({upperPageBound: this.state.upperPageBound - this.state.pageBound});
            this.setState({lowerPageBound: this.state.lowerPageBound - this.state.pageBound});
            let listid = this.state.upperPageBound - this.state.pageBound;
            this.setState({ currentPage: listid});
        btnPrevClick() {
            if((this.state.currentPage -1)%this.state.pageBound === 0 ){
                this.setState({upperPageBound: this.state.upperPageBound - this.state.pageBound});
                this.setState({lowerPageBound: this.state.lowerPageBound - this.state.pageBound});
            let listid = this.state.currentPage - 1;
            this.setState({ currentPage : listid});
        btnNextClick() {
            if((this.state.currentPage +1) > this.state.upperPageBound ){
                this.setState({upperPageBound: this.state.upperPageBound + this.state.pageBound});
                this.setState({lowerPageBound: this.state.lowerPageBound + this.state.pageBound});
            let listid = this.state.currentPage + 1;
            this.setState({ currentPage : listid});
          render() {
            const { todos, currentPage, todosPerPage,upperPageBound,lowerPageBound,isPrevBtnActive,isNextBtnActive } = this.state;
            // Logic for displaying current todos
            const indexOfLastTodo = currentPage * todosPerPage;
            const indexOfFirstTodo = indexOfLastTodo - todosPerPage;
            const currentTodos = todos.slice(indexOfFirstTodo, indexOfLastTodo);

            const renderTodos =, index) => {
              return <li key={index}>{todo}</li>;

            // Logic for displaying page numbers
            const pageNumbers = [];
            for (let i = 1; i <= Math.ceil(todos.length / todosPerPage); i++) {

            const renderPageNumbers = => {
                if(number === 1 && currentPage === 1){
                        <li key={number} className='active' id={number}><a href='#' id={number} onClick={this.handleClick}>{number}</a></li>
                else if((number < upperPageBound + 1) && number > lowerPageBound){
                        <li key={number} id={number}><a href='#' id={number} onClick={this.handleClick}>{number}</a></li>
            let pageIncrementBtn = null;
            if(pageNumbers.length > upperPageBound){
                pageIncrementBtn = <li className=''><a href='#' onClick={this.btnIncrementClick}> &hellip; </a></li>
            let pageDecrementBtn = null;
            if(lowerPageBound >= 1){
                pageDecrementBtn = <li className=''><a href='#' onClick={this.btnDecrementClick}> &hellip; </a></li>
            let renderPrevBtn = null;
            if(isPrevBtnActive === 'disabled') {
                renderPrevBtn = <li className={isPrevBtnActive}><span id="btnPrev"> Prev </span></li>
                renderPrevBtn = <li className={isPrevBtnActive}><a href='#' id="btnPrev" onClick={this.btnPrevClick}> Prev </a></li>
            let renderNextBtn = null;
            if(isNextBtnActive === 'disabled') {
                renderNextBtn = <li className={isNextBtnActive}><span id="btnNext"> Next </span></li>
                renderNextBtn = <li className={isNextBtnActive}><a href='#' id="btnNext" onClick={this.btnNextClick}> Next </a></li>
            return (
                <ul id="page-numbers" className="pagination">

          <TodoApp />,

Working demo link :

Image : simple react pagination

How to temporarily exit Vim and go back

If you don't mind using your mouse a little bit:

  • Start your terminal,
  • select a file,
  • select Open Tab.

This creates a new tab on the terminal which you can run Vim on. Now use your mouse to shift to/from the terminal. I prefer this instead of always having to type (:shell and exit).

How do I set up IntelliJ IDEA for Android applications?

I had some issues that this didn't address in getting this environment set up on OSX. It had to do with the solution that I was maintaining having additional dependencies on some of the Google APIs. It wasn't enough to just download and install the items listed in the first response.

You have to download these.

  1. Run Terminal
  2. Navigate to the android/sdk directory
  3. Type "android" You will get a gui. Check the "Tools" directory and the latest Android API (at this time, it's 4.3 (API 18)).
  4. Click "Install xx packages" and go watch an episode of Breaking Bad or something. It'll take a while.
  5. Go back to IntelliJ and open the "Project Structure..." dialog (Cmd+;).
  6. In the left panel of the dialog, under "Project Settings," select Project. In the right panel, under "Project SDK," click "New..." > Android SDK and navigate to your android/sdk directory. Choose this and you will be presented with a dialog with which you can add the "Google APIs" build target. This is what I needed. You may need to do this more than once if you have multiple version targets.
  7. Now, under the left pane "Modules," with your project selected in the center pane, select the appropriate module under the "Dependencies" tab in the right pane.

1030 Got error 28 from storage engine

I had the same issue in AWS RDS. It was due to the Freeable Space (Hard Drive Storage Space) was Full. You need to increase your space, or remove some data.

Emulate Samsung Galaxy Tab

Matt provided a great link on how to add emulators for all Samsung devices.

To get the official Samsung Galaxy Tab emulator do the following:

  1. Open the Android SDK and AVD Manager
  2. Click on Available packages
  3. Expand the Third party Add-ons. There you will see Samsung Electronics add-ons.
  4. Once the add-on is installed create a new emulator. Under Target you will see the new Samsung Tab settings, select that.

That's it!

jQuery OR Selector?

Using a comma may not be sufficient if you have multiple jQuery objects that need to be joined.

The .add() method adds the selected elements to the result set:

// classA OR classB

It's more verbose than '.classA, .classB', but lets you build more complex selectors like the following:

// (classA which has <p> descendant) OR (<div> ancestors of classB)

Getting started with OpenCV 2.4 and MinGW on Windows 7

On Windows 64bits it´s works:

  1. Download opencv-3.0 (beta), MinGW (command line tool);
  2. Add above respective bin folder to PATH var;
  3. Create an folder "release" (could be any name) into ;
  4. Into created folder, open prompt terminal and exec the below commands;
  5. Copy and Past this command

    cmake -G "MinGW Makefiles" -D CMAKE_CXX_COMPILER=mingw32-g++.exe -D WITH_IPP=OFF MAKE_MAKE_PROGRAM=mingw32-make.exe ..\

  6. Execute this command mingw32-make

  7. Execute this command mingw32-make install