Programs & Examples On #Page caching

Hibernate: Automatically creating/updating the db tables based on entity classes

Sometimes depending on how the configuration is set, the long form and the short form of the property tag can also make the difference.

e.g. if you have it like:

<property name="" value="create"/>

try changing it to:

<property name="">create</property>

Understanding __get__ and __set__ and Python descriptors

I am trying to understand what Python's descriptors are and what they can be useful for.

Descriptors are class attributes (like properties or methods) with any of the following special methods:

  • __get__ (non-data descriptor method, for example on a method/function)
  • __set__ (data descriptor method, for example on a property instance)
  • __delete__ (data descriptor method)

These descriptor objects can be used as attributes on other object class definitions. (That is, they live in the __dict__ of the class object.)

Descriptor objects can be used to programmatically manage the results of a dotted lookup (e.g. foo.descriptor) in a normal expression, an assignment, and even a deletion.

Functions/methods, bound methods, property, classmethod, and staticmethod all use these special methods to control how they are accessed via the dotted lookup.

A data descriptor, like property, can allow for lazy evaluation of attributes based on a simpler state of the object, allowing instances to use less memory than if you precomputed each possible attribute.

Another data descriptor, a member_descriptor, created by __slots__, allow memory savings by allowing the class to store data in a mutable tuple-like datastructure instead of the more flexible but space-consuming __dict__.

Non-data descriptors, usually instance, class, and static methods, get their implicit first arguments (usually named cls and self, respectively) from their non-data descriptor method, __get__.

Most users of Python need to learn only the simple usage, and have no need to learn or understand the implementation of descriptors further.

In Depth: What Are Descriptors?

A descriptor is an object with any of the following methods (__get__, __set__, or __delete__), intended to be used via dotted-lookup as if it were a typical attribute of an instance. For an owner-object, obj_instance, with a descriptor object:

  • obj_instance.descriptor invokes
    descriptor.__get__(self, obj_instance, owner_class) returning a value
    This is how all methods and the get on a property work.

  • obj_instance.descriptor = value invokes
    descriptor.__set__(self, obj_instance, value) returning None
    This is how the setter on a property works.

  • del obj_instance.descriptor invokes
    descriptor.__delete__(self, obj_instance) returning None
    This is how the deleter on a property works.

obj_instance is the instance whose class contains the descriptor object's instance. self is the instance of the descriptor (probably just one for the class of the obj_instance)

To define this with code, an object is a descriptor if the set of its attributes intersects with any of the required attributes:

def has_descriptor_attrs(obj):
    return set(['__get__', '__set__', '__delete__']).intersection(dir(obj))

def is_descriptor(obj):
    """obj can be instance of descriptor or the descriptor class"""
    return bool(has_descriptor_attrs(obj))

A Data Descriptor has a __set__ and/or __delete__.
A Non-Data-Descriptor has neither __set__ nor __delete__.

def has_data_descriptor_attrs(obj):
    return set(['__set__', '__delete__']) & set(dir(obj))

def is_data_descriptor(obj):
    return bool(has_data_descriptor_attrs(obj))

Builtin Descriptor Object Examples:

  • classmethod
  • staticmethod
  • property
  • functions in general

Non-Data Descriptors

We can see that classmethod and staticmethod are Non-Data-Descriptors:

>>> is_descriptor(classmethod), is_data_descriptor(classmethod)
(True, False)
>>> is_descriptor(staticmethod), is_data_descriptor(staticmethod)
(True, False)

Both only have the __get__ method:

>>> has_descriptor_attrs(classmethod), has_descriptor_attrs(staticmethod)
(set(['__get__']), set(['__get__']))

Note that all functions are also Non-Data-Descriptors:

>>> def foo(): pass
>>> is_descriptor(foo), is_data_descriptor(foo)
(True, False)

Data Descriptor, property

However, property is a Data-Descriptor:

>>> is_data_descriptor(property)
>>> has_descriptor_attrs(property)
set(['__set__', '__get__', '__delete__'])

Dotted Lookup Order

These are important distinctions, as they affect the lookup order for a dotted lookup.

  1. First the above looks to see if the attribute is a Data-Descriptor on the class of the instance,
  2. If not, it looks to see if the attribute is in the obj_instance's __dict__, then
  3. it finally falls back to a Non-Data-Descriptor.

The consequence of this lookup order is that Non-Data-Descriptors like functions/methods can be overridden by instances.

Recap and Next Steps

We have learned that descriptors are objects with any of __get__, __set__, or __delete__. These descriptor objects can be used as attributes on other object class definitions. Now we will look at how they are used, using your code as an example.

Analysis of Code from the Question

Here's your code, followed by your questions and answers to each:

class Celsius(object):
    def __init__(self, value=0.0):
        self.value = float(value)
    def __get__(self, instance, owner):
        return self.value
    def __set__(self, instance, value):
        self.value = float(value)

class Temperature(object):
    celsius = Celsius()
  1. Why do I need the descriptor class?

Your descriptor ensures you always have a float for this class attribute of Temperature, and that you can't use del to delete the attribute:

>>> t1 = Temperature()
>>> del t1.celsius
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: __delete__

Otherwise, your descriptors ignore the owner-class and instances of the owner, instead, storing state in the descriptor. You could just as easily share state across all instances with a simple class attribute (so long as you always set it as a float to the class and never delete it, or are comfortable with users of your code doing so):

class Temperature(object):
    celsius = 0.0

This gets you exactly the same behavior as your example (see response to question 3 below), but uses a Pythons builtin (property), and would be considered more idiomatic:

class Temperature(object):
    _celsius = 0.0
    def celsius(self):
        return type(self)._celsius
    def celsius(self, value):
        type(self)._celsius = float(value)
  1. What is instance and owner here? (in get). What is the purpose of these parameters?

instance is the instance of the owner that is calling the descriptor. The owner is the class in which the descriptor object is used to manage access to the data point. See the descriptions of the special methods that define descriptors next to the first paragraph of this answer for more descriptive variable names.

  1. How would I call/use this example?

Here's a demonstration:

>>> t1 = Temperature()
>>> t1.celsius
>>> t1.celsius = 1
>>> t1.celsius
>>> t2 = Temperature()
>>> t2.celsius

You can't delete the attribute:

>>> del t2.celsius
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: __delete__

And you can't assign a variable that can't be converted to a float:

>>> t1.celsius = '0x02'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 7, in __set__
ValueError: invalid literal for float(): 0x02

Otherwise, what you have here is a global state for all instances, that is managed by assigning to any instance.

The expected way that most experienced Python programmers would accomplish this outcome would be to use the property decorator, which makes use of the same descriptors under the hood, but brings the behavior into the implementation of the owner class (again, as defined above):

class Temperature(object):
    _celsius = 0.0
    def celsius(self):
        return type(self)._celsius
    def celsius(self, value):
        type(self)._celsius = float(value)

Which has the exact same expected behavior of the original piece of code:

>>> t1 = Temperature()
>>> t2 = Temperature()
>>> t1.celsius
>>> t1.celsius = 1.0
>>> t2.celsius
>>> del t1.celsius
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: can't delete attribute
>>> t1.celsius = '0x02'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 8, in celsius
ValueError: invalid literal for float(): 0x02


We've covered the attributes that define descriptors, the difference between data- and non-data-descriptors, builtin objects that use them, and specific questions about use.

So again, how would you use the question's example? I hope you wouldn't. I hope you would start with my first suggestion (a simple class attribute) and move on to the second suggestion (the property decorator) if you feel it is necessary.

The AWS Access Key Id does not exist in our records

For me, I was relying on IAM EC2 roles to give access to our machines to specific resources.

I didn't even know there was a credentials file at ~/.aws/credentials, until I rotated/removed some of our accessKeys at the IAM console to tighten our security, and that suddenly made one of the scripts stop working on a single machine.

Deleting that credentials file fixed it for me.

Check if all values of array are equal

The accepted answer worked great but I wanted to add a tiny bit. It didn't work for me to use === because I was comparing arrays of arrays of objects, however throughout my app I've been using the fast-deep-equal package which I highly recommend. With that, my code looks like this:

let areAllEqual = arrs.every((val, i, arr) => equal(val, arr[0]) );

and my data looks like this:

      "ID": 28,
      "AuthorID": 121,
      "VisitTypeID": 2
      "ID": 115,
      "AuthorID": 121,
      "VisitTypeID": 1
      "ID": 121,
      "AuthorID": 121,
      "VisitTypeID": 1
      "ID": 121,
      "AuthorID": 121,
      "VisitTypeID": 1
      "ID": 5,
      "AuthorID": 121,
      "VisitTypeID": 1
      "ID": 121,
      "AuthorID": 121,
      "VisitTypeID": 1

Which is better, return value or out parameter?

I would prefer the following instead of either of those in this simple example.

public int Value
    private set;

But, they are all very much the same. Usually, one would only use 'out' if they need to pass multiple values back from the method. If you want to send a value in and out of the method, one would choose 'ref'. My method is best, if you are only returning a value, but if you want to pass a parameter and get a value back one would likely choose your first choice.

Timing a command's execution in PowerShell

Here's a function I wrote which works similarly to the Unix time command:

function time {
        [switch]$quiet = $false
    $start = Get-Date
    try {
        if ( -not $quiet ) {
            iex $command | Write-Host
        } else {
            iex $command > $null
    } finally {
        $(Get-Date) - $start


How to match letters only using java regex, matches method?

Three problems here:

  1. Just use String.matches() - if the API is there, use it
  2. In java "matches" means "matches the entire input", which IMHO is counter-intuitive, so let your method's API reflect that by letting callers think about matching part of the input as your example suggests
  3. You regex matches only 1 character

I recommend you use code like this:

public boolean matches(String regex) {
    regex = "^.*" + regex + ".*$"; // pad with regex to allow partial matching
    System.out.println("abcABC   ".matches(regex));
    return "abcABC   ".matches(regex);

public static void main(String[] args) {
    HowEasy words = new HowEasy();
    words.matches("[a-zA-Z]+"); // added "+" (ie 1-to-n of) to character class

Understanding SQL Server LOCKS on SELECT queries

I have to add an important comment. Everyone is mentioning that NOLOCKreads only dirty data. This is not precise. It is also possible that you'll get same row twice or whole row is skipped during your read. Reason is that you could ask for some data in same time when SQL Server is re-balancing b-tree.

Check another threads

With the NOLOCK hint (or setting the isolation level of the session to READ UNCOMMITTED) you tell SQL Server that you don't expect consistency, so there are no guarantees. Bear in mind though that "inconsistent data" does not only mean that you might see uncommitted changes that were later rolled back, or data changes in an intermediate state of the transaction. It also means that in a simple query that scans all table/index data SQL Server may lose the scan position, or you might end up getting the same row twice.

How to get folder path for ClickOnce application

path is pointing to a subfolder under c:\Documents & Settings

That's right. ClickOnce applications are installed under the profile of the user who installed them. Did you take the path that retrieving the info from the executing assembly gave you, and go check it out?

On windows Vista and Windows 7, you will find the ClickOnce cache here:


On Windows XP, you will find it here:

C:\Documents and Settings\username\LocalSettings\Apps\2.0\obfuscatedfoldername\obfuscatedfoldername

HTML5 Email Validation

It is very difficult to validate Email correctly simply using HTML5 attribute "pattern". If you do not use a "pattern" someone@ will be processed. which is NOT valid email.

Using pattern="[a-zA-Z]{3,}@[a-zA-Z]{3,}[.]{1}[a-zA-Z]{2,}[.]{1}[a-zA-Z]{2,}" will require the format to be [email protected] however if the sender has a format like [email protected] (or similar) will not be validated to fix this you could put pattern="[a-zA-Z]{3,}@[a-zA-Z]{3,}[.]{1}[a-zA-Z]{2,}[.]{1}[a-zA-Z]{2,}[.]{1}[a-zA-Z]{2,}" this will validate " or or alike.

However using this, it will not permit [email protected] to validate. So as far as simply using HTML5 to validate email addresses is still not totally with us. To Complete this you would use something like this:

<input id="email" type="text" name="email" pattern="[a-zA-Z]{3,}@[a-zA-Z]{3,}[.]{1}[a-zA-Z]{2,}[.]{1}[a-zA-Z]{2,}" required placeholder="Enter you Email">
<input type="submit" value="Submit The Form">


<input id="email" type="text" name="email" pattern="[a-zA-Z]{3,}@[a-zA-Z]{3,}[.]{1}[a-zA-Z]{2,}[.]{1}[a-zA-Z]{2,}[.]{1}[a-zA-Z]{2,}" required placeholder="Enter you Email">
<input type="submit" value="Submit The Form">

However, I do not know how to validate both or all versions of email addresses using HTML5 pattern attribute.

Getting mouse position in c#

To get the position look at the OnMouseMove event. The MouseEventArgs will give you the x an y positions...

protected override void OnMouseMove(MouseEventArgs mouseEv) 

To set the mouse position use the Cursor.Position property.

What are the benefits to marking a field as `readonly` in C#?

There is a potential case where the compiler can make a performance optimization based on the presence of the readonly keyword.

This only applies if the read-only field is also marked as static. In that case, the JIT compiler can assume that this static field will never change. The JIT compiler can take this into account when compiling the methods of the class.

A typical example: your class could have a static read-only IsDebugLoggingEnabled field that is initialized in the constructor (e.g. based on a configuration file). Once the actual methods are JIT-compiled, the compiler may omit whole parts of the code when debug logging is not enabled.

I have not checked if this optimization is actually implemented in the current version of the JIT compiler, so this is just speculation.

Lazy Loading vs Eager Loading

Consider the below situation

public class Person{
    public String Name{get; set;}
    public String Email {get; set;}
    public virtual Employer employer {get; set;}

public List<EF.Person> GetPerson(){
    using(EF.DbEntities db = new EF.DbEntities()){
       return db.Person.ToList();

Now after this method is called, you cannot lazy load the Employer entity anymore. Why? because the db object is disposed. So you have to do Person.Include(x=> x.employer) to force that to be loaded.

Iterating over dictionaries using 'for' loops

Iterating over a dict iterates through its keys in no particular order, as you can see here:

(This is no longer the case in Python 3.6, but note that it's not guaranteed behaviour yet.)

>>> d = {'x': 1, 'y': 2, 'z': 3}
>>> list(d)
['y', 'x', 'z']
>>> d.keys()
['y', 'x', 'z']

For your example, it is a better idea to use dict.items():

>>> d.items()
[('y', 2), ('x', 1), ('z', 3)]

This gives you a list of tuples. When you loop over them like this, each tuple is unpacked into k and v automatically:

for k,v in d.items():
    print(k, 'corresponds to', v)

Using k and v as variable names when looping over a dict is quite common if the body of the loop is only a few lines. For more complicated loops it may be a good idea to use more descriptive names:

for letter, number in d.items():
    print(letter, 'corresponds to', number)

It's a good idea to get into the habit of using format strings:

for letter, number in d.items():
    print('{0} corresponds to {1}'.format(letter, number))

Init method in Spring Controller (annotation version)

There are several ways to intercept the initialization process in Spring. If you have to initialize all beans and autowire/inject them there are at least two ways that I know of that will ensure this. I have only testet the second one but I belive both work the same.

If you are using @Bean you can reference by initMethod, like this.

public class BeanConfiguration {

  public BeanA beanA() {
    return new BeanA();

public class BeanA {

  // method to be initialized after context is ready
  public void init() {


If you are using @Component you can annotate with @EventListener like this.

public class BeanB {

  public void onApplicationEvent(ContextRefreshedEvent event) {

In my case I have a legacy system where I am now taking use of IoC/DI where Spring Boot is the choosen framework. The old system brings many circular dependencies to the table and I therefore must use setter-dependency a lot. That gave me some headaches since I could not trust @PostConstruct since autowiring/injection by setter was not yet done. The order is constructor, @PostConstruct then autowired setters. I solved it with @EventListener annotation which wil run last and at the "same" time for all beans. The example shows implementation of InitializingBean aswell.

I have two classes (@Component) with dependency to each other. The classes looks the same for the purpose of this example displaying only one of them.

public class BeanA implements InitializingBean {
  private BeanB beanB;

  public BeanA() {

  private void postConstruct() {

  public void setBeanB(BeanB beanB) {
    log.debug("@Autowired beanB");
    this.beanB = beanB;

  public void afterPropertiesSet() throws Exception {

  public void onApplicationEvent(ContextRefreshedEvent event) {

This is the log output showing the order of the calls when the container starts.

2018-11-30 18:29:30.504 DEBUG 3624 --- [           main] com.example.demo.BeanA                   : Created...
2018-11-30 18:29:30.509 DEBUG 3624 --- [           main] com.example.demo.BeanB                   : Created...
2018-11-30 18:29:30.517 DEBUG 3624 --- [           main] com.example.demo.BeanB                   : @Autowired beanA
2018-11-30 18:29:30.518 DEBUG 3624 --- [           main] com.example.demo.BeanB                   : @PostConstruct
2018-11-30 18:29:30.518 DEBUG 3624 --- [           main] com.example.demo.BeanB                   : afterPropertiesSet()
2018-11-30 18:29:30.518 DEBUG 3624 --- [           main] com.example.demo.BeanA                   : @Autowired beanB
2018-11-30 18:29:30.518 DEBUG 3624 --- [           main] com.example.demo.BeanA                   : @PostConstruct
2018-11-30 18:29:30.518 DEBUG 3624 --- [           main] com.example.demo.BeanA                   : afterPropertiesSet()
2018-11-30 18:29:30.607 DEBUG 3624 --- [           main] com.example.demo.BeanA                   : @EventListener
2018-11-30 18:29:30.607 DEBUG 3624 --- [           main] com.example.demo.BeanB                   : @EventListener

As you can see @EventListener is run last after everything is ready and configured.

how to fix the issue "Command /bin/sh failed with exit code 1" in iphone

1) option : Please check run the script only when installing......  it is right to answer of this question

2) option : pod update, clean derive data,

How to list installed packages from a given repo using yum

On newer versions of yum, this information is stored in the "yumdb" when the package is installed. This is the only 100% accurate way to get the information, and you can use:

yumdb search from_repo repoid

(or repoquery and grep -- don't grep yum output). However the command "find-repos-of-install" was part of yum-utils for a while which did the best guess without that information:

As floyd said, a lot of repos. include a unique "dist" tag in their release, and you can look for that ... however from what you said, I guess that isn't the case for you?

Select All Rows Using Entity Framework

You can use this code to select all rows :

C# :

var allStudents = [modelname].[tablename].Select(x => x).ToList();

How to detect input type=file "change" for the same file?

Believe me, it will definitely help you!

// there I have called two `onchange event functions` due to some different scenario processing.

<input type="file" class="selectImagesHandlerDialog" 
    onclick="this.value=null;" accept="image/x-png,image/gif,image/jpeg" multiple 
    onchange="delegateMultipleFilesSelectionAndOpen(event); disposeMultipleFilesSelections(this);" />

// delegating multiple files select and open
var delegateMultipleFilesSelectionAndOpen = function (evt) {

  if (! return;

  var selectedPhotos =;
  // some continuous source


// explicitly removing file input value memory cache
var disposeMultipleFilesSelections = function () {
  this.val = null;

Hope this will help many of you guys.

replace String with another in java

The replace method is what you're looking for.

For example:

String replacedString = someString.replace("HelloBrother", "Brother");

Format cell if cell contains date less than today

Your first problem was you weren't using your compare symbols correctly.

< less than
> greater than
<= less than or equal to
>= greater than or equal to

To answer your other questions; get the condition to work on every cell in the column and what about blanks?

What about blanks?

Add an extra IF condition to check if the cell is blank or not, if it isn't blank perform the check. =IF(B2="","",B2<=TODAY())

Condition on every cell in column

enter image description here

How to change color of the back arrow in the new material theme?

Here's how I did it in Material Components:

<style name="AppTheme" parent="Theme.MaterialComponents.DayNight.NoActionBar">
    <item name="drawerArrowStyle">@style/AppTheme.DrawerArrowToggle</item>

<style name="AppTheme.DrawerArrowToggle" parent="Widget.AppCompat.DrawerArrowToggle">
    <item name="color">@android:color/white</item>

How do I create an iCal-type .ics file that can be downloaded by other users?

There is also this tool you can use. It supports multi-events .ics file creation. It also supports timezone as well.

ERROR in The Angular Compiler requires TypeScript >=3.1.1 and <3.2.0 but 3.2.1 was found instead

First install your targeted version

npm i [email protected] --save-dev --save-exact

Then before compiling do

   npm i

How can I see the size of a GitHub repository before cloning it?

There's a way to access this information through the GitHub API.

When retrieving information about a repository, a property named size is valued with the size of the whole repository (including all of its history), in kilobytes.

For instance, the Git repository weights around 124 MB. The size property of the returned JSON payload is valued to 124283.


The size is indeed expressed in kilobytes based on the disk usage of the server-side bare repository. However, in order to avoid wasting too much space with repositories with a large network, GitHub relies on Git Alternates. In this configuration, calculating the disk usage against the bare repository doesn't account for the shared object store and thus returns an "incomplete" value through the API call.

This information has been given by GitHub support.

AngularJS - Building a dynamic table based on a json

<table class="table table-striped table-condensed table-hover">
        <th ng-repeat="header in headers | filter:headerFilter | orderBy:headerOrder" width="{{header.width}}">{{header.label}}</th>
    <tr ng-repeat="user in users" ng-class-odd="'trOdd'" ng-class-even="'trEven'" ng-dblclick="rowDoubleClicked(user)">
        <td ng-repeat="(key,val) in user | orderBy:userOrder(key)">{{val}}</td>


refer this

Full Page <iframe>

Here's the working code. Works in desktop and mobile browsers. hope it helps. thanks for everyone responding.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
        <title>Test Layout</title>
        <style type="text/css">
            body, html
                margin: 0; padding: 0; height: 100%; overflow: hidden;

                position:absolute; left: 0; right: 0; bottom: 0; top: 0px; 
        <div id="content">
            <iframe width="100%" height="100%" frameborder="0" src="" />

Split String by delimiter position using oracle SQL

You want to use regexp_substr() for this. This should work for your example:

select regexp_substr(val, '[^/]+/[^/]+', 1, 1) as part1,
       regexp_substr(val, '[^/]+$', 1, 1) as part2
from (select 'F/P/O' as val from dual) t

Here, by the way, is the SQL Fiddle.

Oops. I missed the part of the question where it says the last delimiter. For that, we can use regex_replace() for the first part:

select regexp_replace(val, '/[^/]+$', '', 1, 1) as part1,
       regexp_substr(val, '[^/]+$', 1, 1) as part2
from (select 'F/P/O' as val from dual) t

And here is this corresponding SQL Fiddle.

Convert file: Uri to File in Android

Add in onActivityResult, getting docx, or pdf file

var imageUriPath = ""
imageUriPath =
    val split = (imageUri.path ? : "").split(":") //split the path.
  } else {
    imageUri.path ? : ""
val file = File(imageUriPath)

Passing environment-dependent variables in webpack

To add to the bunch of answers:

Use ExtendedDefinePlugin instead of DefinePlugin

npm install extended-define-webpack-plugin --save-dev.

ExtendedDefinePlugin is much simpler to use and is documented :-) link

Because DefinePlugin lacks good documentation, I want to help out, by saying that it actually works like #DEFINE in c#.

#if (DEBUG)
        Console.WriteLine("Debugging is enabled.");

Thus, if you want to understand how DefinePlugin works, read the c# #define doucmentation. link

Python function overloading

A possible option is to use the multipledispatch module as detailed here:

Instead of doing this:

def add(self, other):
    if isinstance(other, Foo):
    elif isinstance(other, Bar):
        raise NotImplementedError()

You can do this:

from multipledispatch import dispatch
@dispatch(int, int)
def add(x, y):
    return x + y    

@dispatch(object, object)
def add(x, y):
    return "%s + %s" % (x, y)

With the resulting usage:

>>> add(1, 2)

>>> add(1, 'hello')
'1 + hello'

Open file dialog and select a file using WPF controls and C#

Something like that should be what you need

private void button1_Click(object sender, RoutedEventArgs e)
    // Create OpenFileDialog 
    Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();

    // Set filter for file extension and default file extension 
    dlg.DefaultExt = ".png";
    dlg.Filter = "JPEG Files (*.jpeg)|*.jpeg|PNG Files (*.png)|*.png|JPG Files (*.jpg)|*.jpg|GIF Files (*.gif)|*.gif"; 

    // Display OpenFileDialog by calling ShowDialog method 
    Nullable<bool> result = dlg.ShowDialog();

    // Get the selected file name and display in a TextBox 
    if (result == true)
        // Open document 
        string filename = dlg.FileName;
        textBox1.Text = filename;

Child element click event trigger the parent click event

I faced the same problem and solve it by this method. html :

<div id="parentDiv">
   <div id="childDiv">


   } else {

function childEvent(){
    alert("child event");

function parentEvent(){
    alert("paren event");

php string to int

You can use the str_replace when you declare your variable $b like that :

$b = str_replace(" ", "", '88 8888');
echo (int)$b;

Or the most beautiful solution is to use intval :

$b = intval(str_replace(" ", "", '88 8888');
echo $b;

If your value '88 888' is from an other variable, just replace the '88 888' by the variable who contains your String.

How to represent a DateTime in Excel

Excel expects dates and times to be stored as a floating point number whose value depends on the Date1904 setting of the workbook, plus a number format such as "mm/dd/yyyy" or "hh:mm:ss" or "mm/dd/yyyy hh:mm:ss" so that the number is displayed to the user as a date / time.

Using SpreadsheetGear for .NET you can do this: worksheet.Cells["A1"].Value = DateTime.Now;

This will convert the DateTime to a double which is the underlying type which Excel uses for a Date / Time, and then format the cell with a default date and / or time number format automatically depending on the value.

SpreadsheetGear also has IWorkbook.DateTimeToNumber(DateTime) and NumberToDateTime(double) methods which convert from .NET DateTime objects to a double which Excel can use.

I would expect XlsIO to have something similar.

Disclaimer: I own SpreadsheetGear LLC

Set HTML dropdown selected option using JSTL

Assuming that you have a collection ${roles} of the elements to put in the combo, and ${selected} the selected element, It would go like this:

<select name='role'>
    <option value="${selected}" selected>${selected}</option>
    <c:forEach items="${roles}" var="role">
        <c:if test="${role != selected}">
            <option value="${role}">${role}</option>

UPDATE (next question)

You are overwriting the attribute "productSubCategoryName". At the end of the for loop, the last productSubCategoryName.

Because of the limitations of the expression language, I think the best way to deal with this is to use a map:

Map<String,Boolean> map = new HashMap<String,Boolean>();
for(int i=0;i<userProductData.size();i++){
    String productSubCategoryName=userProductData.get(i).getProductSubCategory();
    map.put(productSubCategoryName, true);
request.setAttribute("productSubCategoryMap", map);

And then in the JSP:

<select multiple="multiple" name="prodSKUs">
    <c:forEach items="${productSubCategoryList}" var="productSubCategoryList">
        <option value="${productSubCategoryList}" ${not empty productSubCategoryMap[productSubCategoryList] ? 'selected' : ''}>${productSubCategoryList}</option>

Substring with reverse index

slice works just fine in IE and other browsers, it's part of the specification and it's the most efficient method too:

//-> 456

slice Method (String) - MSDN
slice - Mozilla Developer Center

Accessing a Dictionary.Keys Key through a numeric index

You can also use SortedList and its Generic counterpart. These two classes and in Andrew Peters answer mentioned OrderedDictionary are dictionary classes in which items can be accessed by index (position) as well as by key. How to use these classes you can find: SortedList Class , SortedList Generic Class .

Jackson enum Serializing and DeSerializer

In the context of an enum, using @JsonValue now (since 2.0) works for serialization and deserialization.

According to the jackson-annotations javadoc for @JsonValue:

NOTE: when use for Java enums, one additional feature is that value returned by annotated method is also considered to be the value to deserialize from, not just JSON String to serialize as. This is possible since set of Enum values is constant and it is possible to define mapping, but can not be done in general for POJO types; as such, this is not used for POJO deserialization.

So having the Event enum annotated just as above works (for both serialization and deserialization) with jackson 2.0+.

Pass Arraylist as argument to function

Define it as

<return type> AnalyzeArray(ArrayList<Integer> list) {

insert multiple rows into DB2 database

other method

INSERT INTO tableName (col1, col2, col3, col4, col5)
select * from table(                        
                    (val1, val2, val3, val4, val5),   
                    (val1, val2, val3, val4, val5),   
                    (val1, val2, val3, val4, val5),   
                    (val1, val2, val3, val4, val5)    
                    ) tmp

How merge two objects array in angularjs?

You can use angular.extend(dest, src1, src2,...);

In your case it would be :

angular.extend($, data);

See documentation here :

Otherwise, if you only get new values from the server, you can do the following

for (var i=0; i<data.length; i++){

Illegal character in path at index 16

I ran into the same thing with the Bing Map API. URLEncoder just made things worse, but a replaceAll(" ","%20"); did the trick.

`ui-router` $stateParams vs. $state.params

EDIT: This answer is correct for version 0.2.10. As @Alexander Vasilyev pointed out it doesn't work in version 0.2.14.

Another reason to use $state.params is when you need to extract query parameters like this:

$stateProvider.state('a', {
  url: 'path/:id/:anotherParam/?yetAnotherParam',
  controller: 'ACtrl',

module.controller('ACtrl', function($stateParams, $state) {
  $state.params; // has id, anotherParam, and yetAnotherParam
  $stateParams;  // has id and anotherParam

How to find a value in an array and remove it by using PHP array functions?

First of all, as others mentioned, you will be using the "array_search()" & the "unset()" methodsas shown below:-

$arrayDummy = array( 'aaaa', 'bbbb', 'cccc', 'dddd', 'eeee', 'ffff', 'gggg' );
unset( $arrayDummy[array_search( 'dddd', $arrayDummy )] ); // Index 3 is getting unset here.
print_r( $arrayDummy ); // This will show the indexes as 0, 1, 2, 4, 5, 6.

Now to re-index the same array, without sorting any of the array values, you will need to use the "array_values()" method as shown below:-

$arrayDummy = array_values( $arrayDummy );
print_r( $arrayDummy ); // Now, you will see the indexes as 0, 1, 2, 3, 4, 5.

Hope it helps.

how to cancel/abort ajax request in axios

Using useEffect hook:

useEffect(() => {
  const ourRequest = Axios.CancelToken.source() // <-- 1st step

  const fetchPost = async () => {
    try {
      const response = await Axios.get(`endpointURL`, {
        cancelToken: ourRequest.token, // <-- 2nd step
    } catch (err) {
      console.log('There was a problem or request was cancelled.')

  return () => {
    ourRequest.cancel() // <-- 3rd step
}, [])

Note: For POST request, pass cancelToken as 3rd argument`endpointURL`, {data}, {
 cancelToken: ourRequest.token, // 2nd step

Still getting warning : Configuration 'compile' is obsolete and has been replaced with 'implementation'

Just updating google-service version did not work for me.

  • First make sure all your dependencies compile are replaced with implementation.
  • Update all dependencies in your project. Because if one of your dependency is having compile then your project will show this error. So update all dependencies version.

How does Java resolve a relative path in new File()?

When your path starts with a root dir i.e. C:\ in windows or / in Unix or in java resources path, it is considered to be an absolute path. Everything else is relative, so

new File("test.txt") is the same as new File("./test.txt")

new File("test/../test.txt") is the same as new File("./test/../test.txt")

The major difference between getAbsolutePath and getCanonicalPath is that the first one concatenates a parent and a child path, so it may contain dots: .. or .. getCanonicalPath will always return the same path for a particular file.

Note: File.equals uses an abstract form of a path (getAbsolutePath) to compare files, so this means that two File objects for the same might not be equal and Files are unsafe to use in collections like Map or Set.

Silent installation of a MSI package

The proper way to install an MSI silently is via the msiexec.exe command line as follows:

msiexec.exe /i c:\setup.msi /QN /L*V "C:\Temp\msilog.log"

Quick explanation:

 /L*V "C:\Temp\msilog.log"= verbose logging
 /QN = run completely silently
 /i = run install sequence 

There is a much more comprehensive answer here: Batch script to install MSI. This answer provides details on the msiexec.exe command line options and a description of how to find the "public properties" that you can set on the command line at install time. These properties are generally different for each MSI.

How to refresh the data in a jqGrid?

$('#grid').trigger( 'reloadGrid' );

Align text in a table header

For me none of the above worked. I think it is because I have two levels of header and a fixed width on level 1. So I couldn't align the text inside the corresponding columns on level 2.

|           lvl 1           |
| lvl 2 col a | lvl 2 col b |

I had to use the combination of width:auto and text:align-center :

<th style="width:auto;text-align:center">lvl 2 col a</th>
<th style="width:auto;text-align:center">lvl 2 col b</th>

WordPress Get the Page ID outside the loop

If you by any means searched this topic because of the post page (index page alternative when using static front page), then the right answer is this:

if (get_option('show_on_front') == 'page') {
    $page_id = get_option('page_for_posts');
    echo get_the_title($page_id);

(taken from Forrst | Echo WordPress "Posts Page" title - Some code from tammyhart)

How to parse my json string in C#(4.0)using Newtonsoft.Json package?

foreach (var data in dynObj.quizlist)
    foreach (var data1 in data.QUIZ.QPROP)
        Response.Write("Name" + ":" + + "<br>");
        Response.Write("Intro" + ":" + data1.intro + "<br>");
        Response.Write("Timeopen" + ":" + data1.timeopen + "<br>");
        Response.Write("Timeclose" + ":" + data1.timeclose + "<br>");
        Response.Write("Timelimit" + ":" + data1.timelimit + "<br>");
        Response.Write("Noofques" + ":" + data1.noofques + "<br>");

        foreach (var queprop in data1.QUESTION.QUEPROP)
            Response.Write("Questiontext" + ":" + queprop.questiontext  + "<br>");
            Response.Write("Mark" + ":" + queprop.mark  + "<br>");

Laravel-5 how to populate select box from database with id value and name value

I have added toArray() after pluck

$items = Item::get()->pluck('name', 'id')->toArray();

{{ Form::select('item_id', [null=>'Please Select'] + $items) }}

Delete item from state array in react

const [people, setPeople] = useState(data);

const handleRemove = (id) => {
   const newPeople = people.filter((person) => { !== id;
     setPeople( newPeople );

<button onClick={() => handleRemove(id)}>Remove</button>

How to change angular port from 4200 to any other

We have two ways to change default port number in Angular.

First way to cli command:

ng serve --port 2400 --open

Second way is by configuration at the location: ProjectName\node_modules\@angular-devkit\build-angular\src\dev-server\schema.json.

Make changes in schema.json file.

 "title": "Dev Server Target",
  "description": "Dev Server target options for Build Facade.",
  "type": "object",
  "properties": {
    "browserTarget": {
      "type": "string",
      "description": "Target to serve."
    "port": {
      "type": "number",
      "description": "Port to listen on.",
      "default": 2400

Recommended add-ons/plugins for Microsoft Visual Studio

VS Command Shell Command shell in the Output pane. Far from perfect, but often very, very useful. Faster and easier to get to than a separate cmd and has easier copy/paste support.

How do I change the background color of the ActionBar of an ActionBarActivity using XML?

This code may be helpful

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light">
    <!-- Customize your theme here. -->
<style name="Theme.MyTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- customize the color palette -->
    <item name="colorPrimary">@color/material_blue_500</item>
    <item name="colorPrimaryDark">@color/material_blue_700</item>
    <item name="colorAccent">@color/material_blue_500</item>
    <item name="colorControlNormal">@color/black</item>

<style name="CardViewStyle" parent="CardView.Light">
    <item name="android:state_pressed">@color/material_blue_700</item>
    <item name="android:state_focused">@color/material_blue_700</item>
    <!--<item name="android:background">?android:attr/selectableItemBackground</item>-->

MySQL: Curdate() vs Now()

For questions like this, it is always worth taking a look in the manual first. Date and time functions in the mySQL manual

CURDATE() returns the DATE part of the current time. Manual on CURDATE()

NOW() returns the date and time portions as a timestamp in various formats, depending on how it was requested. Manual on NOW().

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

C++ programs are translated to assembly programs during the generation of machine code from the source code. It would be virtually wrong to say assembly is slower than C++. Moreover, the binary code generated differs from compiler to compiler. So a smart C++ compiler may produce binary code more optimal and efficient than a dumb assembler's code.

However I believe your profiling methodology has certain flaws. The following are general guidelines for profiling:

  1. Make sure your system is in its normal/idle state. Stop all running processes (applications) that you started or that use CPU intensively (or poll over the network).
  2. Your datasize must be greater in size.
  3. Your test must run for something more than 5-10 seconds.
  4. Do not rely on just one sample. Perform your test N times. Collect results and calculate the mean or median of the result.

Easiest way to mask characters in HTML(5) text input

A little late, but a useful plugin that will actually use a mask to give a bit more restriction on user input.

<div class="col-sm-3 col-md-6 col-lg-4">
  <div class="form-group">
     <label for="addPhone">Phone Number *</label>
      <input id="addPhone" name="addPhone" type="text" class="form-control 
       required" data-mask="(999) 999-9999"placeholder>
    <span class="help-block">(999) 999-9999</span>

 <!-- Input Mask -->
 <script src="js/plugins/jasny/jasny-bootstrap.min.js"></script>

enter image description here

More info on the plugin

C++ Pass A String

The obvious way would be to call the function like this


Difference between a class and a module

Basically, the module cannot be instantiated. When a class includes a module, a proxy superclass is generated that provides access to all the module methods as well as the class methods.

A module can be included by multiple classes. Modules cannot be inherited, but this "mixin" model provides a useful type of "multiple inheritrance". OO purists will disagree with that statement, but don't let purity get in the way of getting the job done.

(This answer originally linked to, but that link and its domain are no longer active.)

Center a 'div' in the middle of the screen, even when the page is scrolled up or down?

I just found a new trick to center a box in the middle of the screen even if you don't have fixed dimensions. Let's say you would like a box 60% width / 60% height. The way to make it centered is by creating 2 boxes: a "container" box that position left: 50% top :50%, and a "text" box inside with reverse position left: -50%; top :-50%;

It works and it's cross browser compatible.

Check out the code below, you probably get a better explanation:

jQuery('.close a, .bg', '#message').on('click', function() {_x000D_
  return false;_x000D_
html, body {_x000D_
  min-height: 100%;_x000D_
#message {_x000D_
  height: 100%;_x000D_
  left: 0;_x000D_
  position: fixed;_x000D_
  top: 0;_x000D_
  width: 100%;_x000D_
#message .container {_x000D_
  height: 60%;_x000D_
  left: 50%;_x000D_
  position: absolute;_x000D_
  top: 50%;_x000D_
  z-index: 10;_x000D_
  width: 60%;_x000D_
#message .container .text {_x000D_
  background: #fff;_x000D_
  height: 100%;_x000D_
  left: -50%;_x000D_
  position: absolute;_x000D_
  top: -50%;_x000D_
  width: 100%;_x000D_
#message .bg {_x000D_
  background: rgba(0, 0, 0, 0.5);_x000D_
  height: 100%;_x000D_
  left: 0;_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  width: 100%;_x000D_
  z-index: 9;_x000D_
<script src=""></script>_x000D_
<div id="message">_x000D_
  <div class="container">_x000D_
    <div class="text">_x000D_
      <p>The message</p>_x000D_
      <p class="close"><a href="#">Close Window</a></p>_x000D_
  <div class="bg"></div>_x000D_

Angular 2 - NgFor using numbers instead collections

You can use lodash:

  selector: 'board',
  template: `
<div *ngFor="let i of range">
  styleUrls: ['./board.component.css']
export class AppComponent implements OnInit {
  range = _.range(8);

I didn't test code but it should work.

PDOException “could not find driver”

Everywhere I go I read that the path of extension_dir should be changed from ext to an absolute path. It worked for me. However, when trying to build a server of my colleague's PC, I had to let the value to ext instead of putting an absolute path.

If you did put an absolute path and it does the extension is still not found, considerer trying both with the absolute path and ext.

How to empty a char array?

members[0] = 0;

is enough, given your requirements.

Notice however this is not "emptying" the buffer. The memory is still allocated, valid character values may still exist in it, and so forth..

Recursive directory listing in DOS

You can use:

dir /s

If you need the list without all the header/footer information try this:

dir /s /b

(For sure this will work for DOS 6 and later; might have worked prior to that, but I can't recall.)

How can I split a shell command over multiple lines when using an IF statement?

For Windows/WSL/Cygwin etc users:

Make sure that your line endings are standard Unix line feeds, i.e. \n (LF) only.

Using Windows line endings \r\n (CRLF) line endings will break the command line break.

This is because having \ at the end of a line with Windows line ending translates to \ \r \n.
As Mark correctly explains above:

The line-continuation will fail if you have whitespace after the backslash and before the newline.

This includes not just space () or tabs (\t) but also the carriage return (\r).

What's a clean way to stop mongod on Mac OS X?

Check out these docs:

If you started it in a terminal you should be ok with a ctrl + 'c' -- this will do a clean shutdown.

However, if you are using launchctl there are specific instructions for that which will vary depending on how it was installed.

If you are using Homebrew it would be launchctl stop homebrew.mxcl.mongodb

How to access List elements

It's simple

y = [['vegas','London'],['US','UK']]

for x in y:
    for a in x:

Write lines of text to a file in R

tidyverse edition with pipe and write_lines() from readr

c('Hello', 'World') %>% write_lines( "output.txt")

How can I recover the return value of a function passed to multiprocessing.Process?

You can use the exit built-in to set the exit code of a process. It can be obtained from the exitcode attribute of the process:

import multiprocessing

def worker(procnum):
    print str(procnum) + ' represent!'

if __name__ == '__main__':
    jobs = []
    for i in range(5):
        p = multiprocessing.Process(target=worker, args=(i,))

    result = []
    for proc in jobs:
    print result


0 represent!
1 represent!
2 represent!
3 represent!
4 represent!
[0, 1, 2, 3, 4]

What's the best way to loop through a set of elements in JavaScript?

Note that in some cases, you need to loop in reverse order (but then you can use i-- too).

For example somebody wanted to use the new getElementsByClassName function to loop on elements of a given class and change this class. He found that only one out of two elements was changed (in FF3).
That's because the function returns a live NodeList, which thus reflects the changes in the Dom tree. Walking the list in reverse order avoided this issue.

var menus = document.getElementsByClassName("style2");
for (var i = menus.length - 1; i >= 0; i--)
  menus[i].className = "style1";

In increasing index progression, when we ask the index 1, FF inspects the Dom and skips the first item with style2, which is the 2nd of the original Dom, thus it returns the 3rd initial item!

How to use RecyclerView inside NestedScrollView?

I have used this awesome extension (written in kotlin but can be also used in Java)

Basically you get the NestedRecyclerView inside any package lets say utils in your project, then just create your recyclerview like

      android:layout_height="match_parent" />

Check this awesome article by Marc Knaup

Tooltips for cells in HTML table (no Javascript)

An evolution of what BioData41 added...

Place what follows in CSS style



            visibility: hidden;
            width: auto;
            text-align: Left;
            opacity: 0.4;
            transition: opacity 2s;
            border-radius: 6px;
            background-color: #555;
        .CellWithComment:hover span.CellComment {visibility: visible;opacity: 1;}

Then, use it like this:

                <th class="CellWithComment">Category<span class="CellComment">"Ciaooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo"</span></th>
                <th class="CellWithComment">Code<span class="CellComment">"Ciaooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo"</span></th>
                <th>Component Name</th>
                <td>Table cell</td>
                <td>Table cell</td>
                <td>Table cell</td>
                <td>Table cell</td>
                <td>Table cell</td>
                <td>Table cell</td>
                <td>Table cell</td>
                <td>Table cell</td>
                <td>Table cell</td>
                <td>Table cell</td>
                <td>Table cell</td>
                <td>Table cell</td>
                <td>Table cell</td>
                <td>Table cell</td>

Docker-Compose can't connect to Docker Daemon

You should adding your user to the "docker" group with something like:

sudo usermod -aG docker ${USER}

Creating a new empty branch for a new project

You can create a branch as an orphan:

git checkout --orphan <branchname>

This will create a new branch with no parents. Then, you can clear the working directory with:

git rm --cached -r .

and add the documentation files, commit them and push them up to github.

A pull or fetch will always update the local information about all the remote branches. If you only want to pull/fetch the information for a single remote branch, you need to specify it.

How to set an environment variable from a Gradle build?

You can also "prepend" the environment variable setting by using 'environment' command:

run.doFirst { environment 'SPARK_LOCAL_IP', 'localhost' }

Finding diff between current and last version

As pointed out on a comment by amalloy, if by "current and last versions" you mean the last commit and the commit before that, you could simply use

git show

Initializing IEnumerable<string> In C#

IEnumerable is an interface, instead of looking for how to create an interface instance, create an implementation that matches the interface: create a list or an array.

IEnumerable<string> myStrings = new [] { "first item", "second item" };
IEnumerable<string> myStrings = new List<string> { "first item", "second item" };

Calling a stored procedure in Oracle with IN and OUT parameters

Go to Menu Tool -> SQL Output, Run the PL/SQL statement, the output will show on SQL Output panel.

How to get ID of clicked element with jQuery

Your id will be passed through as #1, #2 etc. However, # is not valid as an ID (CSS selectors prefix IDs with #).

How to get next/previous record in MySQL?

If you have an index column, say id, you can return previous and next id in one sql request. Replace :id with your value

 IFNULL((SELECT id FROM table WHERE id < :id ORDER BY id DESC LIMIT 1),0) as previous,
 IFNULL((SELECT id FROM table WHERE id > :id ORDER BY id ASC LIMIT 1),0) as next

How to assign multiple classes to an HTML container?

Just remove the comma like this:

<article class="column wrapper"> 

SQL command to display history of queries

Look at ~/.myslgui/query-browser/history.xml here you can find the last queries made with mysql_query_browser (some days old)

Visual C++: How to disable specific linker warnings?

For the benefit of others, I though I'd include what I did.

Since you cannot get Visual Studio (2010 in my case) to ignore the LNK4204 warnings, my approach was to give it what it wanted: the pdb files. As I was using open source libraries in my case, I have the code building the pdb files already.

BUT, the default is to name all of the PDF files the same thing: vc100.pdb in my case. As you need a .pdb for each and every .lib, this creates a problem, especially if you are using something like ImageMagik, which creates about 20 static .lib files. You cannot have 20 lib files in one directory (which your application's linker references to link in the libraries from) and have all the 20 .pdb files called the same thing.

My solution was to go and rebuild my static library files, and configure VS2010 to name the .pdb file with respect to the PROJECT. This way, each .lib gets a similarly named .pdb, and you can put all of the LIBs and PDBs in one directory for your project to use.

So for the "Debug" configuraton, I edited:

Properties->Configuration Properties -> C/C++ -> Output Files -> Program Database File Name from


to be the following value:


Now rather than somewhere in the intermediate directory, the .pdb files are written to the output directory, where the .lib files are also being written, AND most importantly, they are named with a suffix of D+project name. This means each library project produduces a project .lib and a project specific .pdb.

I'm now able to copy all of my release .lib files, my debug .lib files and the debug .pdb files into one place on my development system, and the project that uses that 3rd party library in debug mode, has the pdb files it needs in debug mode.

Apache shows PHP code instead of executing it

Run Xampp (apache) as administrator. In google chrome type:

localhost/<insert folder name here>/<insert file name>

i.e. if folder you created is "LearnPhp", file is "chapter1.php" then type


I created this folder in the xampp folder in the htdocs folder which gets created when you download xampp.

Sqlite or MySql? How to decide?

SQLite out-of-the-box is not really feature-full regarding concurrency. You will get into trouble if you have hundreds of web requests hitting the same SQLite database.

You should definitely go with MySQL or PostgreSQL.

If it is for a single-person project, SQLite will be easier to setup though.

How do I redirect to another webpage?

So, the question is how to make a redirect page, and not how to redirect to a website?

You only need to use JavaScript for this. Here is some tiny code that will create a dynamic redirect page.

    var url ='url=')[1]; // Get the URL after ?url=
    if( url ) window.location.replace(url);

So say you just put this snippet into a redirect/index.html file on your website you can use it like so.

And if you go to that link it will automatically redirect you to

Link to Documentation

And that's how you make a Simple redirect page with JavaScript


There is also one thing to note. I have added window.location.replace in my code because I think it suits a redirect page, but, you must know that when using window.location.replace and you get redirected, when you press the back button in your browser it will not got back to the redirect page, and it will go back to the page before it, take a look at this little demo thing.


The process: store home => redirect page to google => google

When at google: google => back button in browser => store home

So, if this suits your needs then everything should be fine. If you want to include the redirect page in the browser history replace this

if( url ) window.location.replace(url);


if( url ) window.location.href = url;

Get the current date in java.sql.Date format

Since the java.sql.Date has a constructor that takes 'long time' and java.util.Date has a method that returns 'long time', I just pass the returned 'long time' to the java.sql.Date to create the date.

java.util.Date date = new java.util.Date();
java.sql.Date sqlDate = new Date(date.getTime());

SQL select statements with multiple tables

select P.*,
from Preson P
inner join Address A on
where A.Zip=97229
Order by A.Street,A.City,A.State

changing visibility using javascript

function loadpage (page_request, containerid)
  var loading = document.getElementById ( "loading" ) ;

  // when connecting to server
  if ( page_request.readyState == 1 ) = "visible" ;

  // when loaded successfully
  if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1))
      document.getElementById(containerid).innerHTML=page_request.responseText ; = "hidden" ;

How to open URL in Microsoft Edge from the command line?

Personally, I use this function which I created and put in my profile script ...\Documents\WindowsPowerShell\….profile, feel free to use it. As I am from the UK, I prefer to go to where possible, if you are from another area, you can add your own country code.

# Function taking parameter add (address) and opens in edge.
Function edge {
    if (-not ($add -contains "https://www." -or $add -contains "http://www.")) {
        if ($add[0] -eq "w" -and $add[1] -eq "w" -and $add[2] -eq "w") {
            $add = "https://" + $add
        } else {
            $add = "https://www." + $add

    # If no domain, tries to add, if fails uses .com
    if (-not ($add -match ".co" -or $add -match ".uk" -or $add -match ".com")) {
        try {
            $test = $add + ""
            $HTTP_Request  = [System.Net.WebRequest]::Create($test)
            $HTTP_Response = $HTTP_Request.GetResponse()
            $add = $add + ""
        } catch{
            $add = $add + ".com"
    Write-Host "Taking you to $add"
    start microsoft-edge:$add

Then you just have to call: edge google in powershell to go to

C#: Waiting for all threads to complete

I read the book C# 4.0: The Complete Reference of Herbert Schildt. The author use join to give a solution :

class MyThread
        public int Count;
        public Thread Thrd;
        public MyThread(string name)
            Count = 0;
            Thrd = new Thread(this.Run);
            Thrd.Name = name;
        // Entry point of thread.
        void Run()
            Console.WriteLine(Thrd.Name + " starting.");
                Console.WriteLine("In " + Thrd.Name +
                ", Count is " + Count);
            } while (Count < 10);
            Console.WriteLine(Thrd.Name + " terminating.");
    // Use Join() to wait for threads to end.
    class JoinThreads
        static void Main()
            Console.WriteLine("Main thread starting.");
            // Construct three threads.
            MyThread mt1 = new MyThread("Child #1");
            MyThread mt2 = new MyThread("Child #2");
            MyThread mt3 = new MyThread("Child #3");
            Console.WriteLine("Child #1 joined.");
            Console.WriteLine("Child #2 joined.");
            Console.WriteLine("Child #3 joined.");
            Console.WriteLine("Main thread ending.");

Check if pull needed in Git

I would do the way suggested by brool. The following one-line script takes the SHA1 of your last commited version and compares it to the one of the remote origin, and pull changes only if they differ. And it's even more light-weight of the solutions based on git pull or git fetch.

[ `git log --pretty=%H ...refs/heads/master^` != `git ls-remote origin
-h refs/heads/master |cut -f1` ] && git pull

Convert string in base64 to image and save on filesystem in Python

You can also save it to a string buffer and then do as you wish with it,

import cStringIO
data = json.loads(request.POST['imgData'])  # Getting the object from the post request
image_output = cStringIO.StringIO()
image_output.write(data.decode('base64'))   # Write decoded image to buffer  # seek beginning of the image string
#  # Do as you wish with it!

In django, you can save it as an uploaded file to save to a model:

from django.core.files.uploadedfile import SimpleUploadedFile
suf = SimpleUploadedFile('uploaded_file.png',, content_type='image/png')

Or send it as an email:

email = EmailMessage('Hello', 'Body goes here', '[email protected]',
                                     ['[email protected]', ])
                email.attach('design.png',, 'image/png')

open failed: EACCES (Permission denied)

I got the same issue but Sometimes, the most dificult issue get simple answer.

I recheck the manifest permisions and there WAS_NOT write permision shame of me!!!

How to update fields in a model without creating a new record in django?

Django has some documentation about that on their website, see: Saving changes to objects. To summarize:

.. to save changes to an object that's already in the database, use save().

How to implement a binary search tree in Python?

The Op's Tree.insert method qualifies for the "Gross Misnomer of the Week" award -- it doesn't insert anything. It creates a node which is not attached to any other node (not that there are any nodes to attach it to) and then the created node is trashed when the method returns.

For the edification of @Hugh Bothwell:

>>> class Foo(object):
...    bar = None
>>> a = Foo()
>>> b = Foo()
>>> = 42
>>> = 666

How to square or raise to a power (elementwise) a 2D numpy array?

>>> import numpy
>>> print numpy.power.__doc__

power(x1, x2[, out])

First array elements raised to powers from second array, element-wise.

Raise each base in `x1` to the positionally-corresponding power in
`x2`.  `x1` and `x2` must be broadcastable to the same shape.

x1 : array_like
    The bases.
x2 : array_like
    The exponents.

y : ndarray
    The bases in `x1` raised to the exponents in `x2`.

Cube each element in a list.

>>> x1 = range(6)
>>> x1
[0, 1, 2, 3, 4, 5]
>>> np.power(x1, 3)
array([  0,   1,   8,  27,  64, 125])

Raise the bases to different exponents.

>>> x2 = [1.0, 2.0, 3.0, 3.0, 2.0, 1.0]
>>> np.power(x1, x2)
array([  0.,   1.,   8.,  27.,  16.,   5.])

The effect of broadcasting.

>>> x2 = np.array([[1, 2, 3, 3, 2, 1], [1, 2, 3, 3, 2, 1]])
>>> x2
array([[1, 2, 3, 3, 2, 1],
       [1, 2, 3, 3, 2, 1]])
>>> np.power(x1, x2)
array([[ 0,  1,  8, 27, 16,  5],
       [ 0,  1,  8, 27, 16,  5]])


As per the discussed observation on numerical precision as per @GarethRees objection in comments:

>>> a = numpy.ones( (3,3), dtype = numpy.float96 ) # yields exact output
>>> a[0,0] = 0.46002700024131926
>>> a
array([[ 0.460027,  1.0,  1.0],
       [ 1.0,  1.0,  1.0],
       [ 1.0,  1.0,  1.0]], dtype=float96)
>>> b = numpy.power( a, 2 )
>>> b
array([[ 0.21162484,  1.0,  1.0],
       [ 1.0,  1.0,  1.0],
       [ 1.0,  1.0,  1.0]], dtype=float96)

>>> a.dtype
>>> a[0,0]
>>> b[0,0]

>>> print b[0,0]
>>> print a[0,0]


>>> c    = numpy.random.random( ( 1000, 1000 ) ).astype( numpy.float96 )

>>> import zmq
>>> aClk = zmq.Stopwatch()

>>> aClk.start(), c**2, aClk.stop()
(None, array([[ ...]], dtype=float96), 5663L)                #   5 663 [usec]

>>> aClk.start(), c*c, aClk.stop()
(None, array([[ ...]], dtype=float96), 6395L)                #   6 395 [usec]

>>> aClk.start(), c[:,:]*c[:,:], aClk.stop()
(None, array([[ ...]], dtype=float96), 6930L)                #   6 930 [usec]

>>> aClk.start(), c[:,:]**2, aClk.stop()
(None, array([[ ...]], dtype=float96), 6285L)                #   6 285 [usec]

>>> aClk.start(), numpy.power( c, 2 ), aClk.stop()
(None, array([[ ... ]], dtype=float96), 384515L)             # 384 515 [usec]

How to position a div in the middle of the screen when the page is bigger than the screen

just add position:fixed and it will keep it in view even if you scroll down. see it at

#mydiv {
    top: 50%;
    left: 50%;
    margin-top: -9em; /*set to a negative number 1/2 of your height*/
    margin-left: -15em; /*set to a negative number 1/2 of your width*/
    border: 1px solid #ccc;
    background-color: #f3f3f3;

How to find Google's IP address?

With Python 3, you could do:

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server = ""
port = 80
server_ip = socket.gethostbyname(server)

Javascript Uncaught TypeError: Cannot read property '0' of undefined

There is no error when I use your code,

but I am calling the hasLetter method like this:


Get key from a HashMap using the value

  • If you need only that, simply use put(100, "one"). Note that the key is the first argument, and the value is the 2nd.
  • If you need to be able to get by both the key and the value, use BiMap (from guava)

How to delete shared preferences data from App in Android

Removing all preferences:

SharedPreferences settings = context.getSharedPreferences("PreferencesName", Context.MODE_PRIVATE);

Removing single preference:

SharedPreferences settings = context.getSharedPreferences("PreferencesName", Context.MODE_PRIVATE);

How can I read the client's machine/computer name from the browser?

An updated version from Kelsey :

$(function GetInfo() {
    var network = new ActiveXObject('WScript.Network');
        alert('User ID : ' + network.UserName + '\nComputer Name : ' + network.ComputerName + '\nDomain Name : ' + network.UserDomain);
        document.getElementById('<%= currUserID.ClientID %>').value = network.UserName;
        document.getElementById('<%= currMachineName.ClientID %>').value = network.ComputerName;
        document.getElementById('<%= currMachineDOmain.ClientID %>').value = network.UserDomain;

To store the value, add these control :

<asp:HiddenField ID="currUserID" runat="server" /> <asp:HiddenField ID="currMachineName" runat="server" /> <asp:HiddenField ID="currMachineDOmain" runat="server" />

Where you also can calling it from behind like this :

Page.ClientScript.RegisterStartupScript(this.GetType(), "MachineInfo", "GetInfo();", true);

CSS: auto height on containing div, 100% height on background div inside containing div

Okay so someone is probably going to slap me for this answer, but I use jQuery to solve all my irritating problems and it turns out that I just used something today to fix a similar issue. Assuming you use jquery:


this is untested but I think you can see the concept here. Basically after it is loaded, you can get the height (outerHeight includes padding + borders, innerHeight for the content only). Hope that helps.

Here is how you bind it to the window resize event:

$(window).resize(function() {

Division of integers in Java

Convert both completed and total to double or at least cast them to double when doing the devision. I.e. cast the varaibles to double not just the result.

Fair warning, there is a floating point precision problem when working with float and double.

How to convert from int to string in objective c: example code

int val1 = [textBox1.text integerValue];
int val2 = [textBox2.text integerValue];

int resultValue = val1 * val2;

textBox3.text = [NSString stringWithFormat: @"%d", resultValue];

Add content to a new open window

Here is what you can try

  • Write a function say init() inside mypage.html that do the html thing ( append or what ever)
  • instead of OpenWindow.document.write(output); call OpenWindow.init() when the dom is ready

So the parent window will have

    OpenWindow.onload = function(){

and in the child

    function init(txt){

"Unorderable types: int() < str()"

The issue here is that input() returns a string in Python 3.x, so when you do your comparison, you are comparing a string and an integer, which isn't well defined (what if the string is a word, how does one compare a string and a number?) - in this case Python doesn't guess, it throws an error.

To fix this, simply call int() to convert your string to an integer:


As a note, if you want to deal with decimal numbers, you will want to use one of float() or decimal.Decimal() (depending on your accuracy and speed needs).

Note that the more pythonic way of looping over a series of numbers (as opposed to a while loop and counting) is to use range(). For example:

def main():
    print("Let me Retire Financial Calculator")
    deposit = float(input("Please input annual deposit in dollars: $"))
    rate = int(input ("Please input annual rate in percentage: %")) / 100
    time = int(input("How many years until retirement?"))
    value = 0
    for x in range(1, time+1):
        value = (value * rate) + deposit
        print("The value of your account after" + str(x) + "years will be $" + str(value))

Disable Input fields in reactive form

A more general approach would be.

// Variable/Flag declare
public formDisabled = false;

// Form init
this.form = new FormGroup({
  name: new FormControl({value: '', disabled: this.formDisabled}, 

// Enable/disable form control
public toggleFormState() {
    this.formDisabled = !this.formDisabled;
    const state = this.formDisabled ? 'disable' : 'enable';

    Object.keys(this.form.controls).forEach((controlName) => {
        this.form.controls[controlName][state](); // disables/enables each form control based on 'this.formDisabled'

wordpress contactform7 textarea cols and rows change in smaller screens

I was able to get this work. I added the following to my custom CSS:

.wpcf7-form textarea{ 
    width: 100% !important;

Best practices for API versioning?

We found it practical and useful to put the version in the URL. It makes it easy to tell what you're using at a glance. We do alias /foo to /foo/(latest versions) for ease of use, shorter / cleaner URLs, etc, as the accepted answer suggests.

Keeping backwards compatibility forever is often cost-prohibitive and/or very difficult. We prefer to give advanced notice of deprecation, redirects like suggested here, docs, and other mechanisms.

How to get a Static property with Reflection

myType.GetProperties(BindingFlags.Public | BindingFlags.Static |  BindingFlags.FlattenHierarchy);

This will return all static properties in static base class or a particular type and probably the child as well.

How can I switch word wrap on and off in Visual Studio Code?

Go to the Preferences tab (menu FileSettings), and then search as “word wrap”. The following animated image is helpful too.

Enter image description here

Python: URLError: <urlopen error [Errno 10060]

Answer (Basic is advance!):

Error: 10060 Adding a timeout parameter to request solved the issue for me.

Example 1

import urllib
import urllib2
g = ""
read = urllib2.urlopen(g, timeout=20)

Example 2

A similar error also occurred while I was making a GET request. Again, passing a timeout parameter solved the 10060 Error.

response = requests.get(param_url, timeout=20)

Switch with if, else if, else, and loops inside case

Seems like kind of a homely way of doing things, but if you must... you could restructure it as such to fit your needs:

boolean found = false;

case 1:

for (Element arrayItem : array) {
    if (arrayItem == whateverValue) {
        found = true;    
    } // else if ...
if (found) {
case 2:

How to show empty data message in Datatables

I was finding same but lastly i found an answer. I hope this answer help you so much.

when your array is empty then you can send empty array just like

            echo json_encode($result);
            echo json_encode(array('data'=>''));

Thank you

angular-cli server - how to specify default port

There might be a situation when you want to use NodeJS environment variable to specify Angular CLI dev server port. One of the possible solution is to move CLI dev server running into a separate NodeJS script, which will read port value (e.g from .env file) and use it executing ng serve with port parameter:

// run-env.js
const dotenv = require('dotenv');
const child_process = require('child_process');

const config = dotenv.config()
const DEV_SERVER_PORT = process.env.DEV_SERVER_PORT || 4200;

const child = child_process.exec(`ng serve --port=${DEV_SERVER_PORT}`);
child.stdout.on('data', data => console.log(data.toString()));

Then you may a) run this script directly via node run-env, b) run it via npm by updating package.json, for example

"scripts": {
  "start": "node run-env"

run-env.js should be committed to the repo, .env should not. More details on the approach can be found in this post: How to change Angular CLI Development Server Port via .env.

How do I enable TODO/FIXME/XXX task tags in Eclipse?

There are apparently distributions or custom builds in which the ability to set Task Tags for non-Java files is not present. This post mentions that ColdFusion Builder (built on Eclipse) does not let you set non-Java Task Tags, but the beta version of CF Builder 2 does. (I know the OP wasn't using CF Builder, but I am, and I was wondering about this question myself ... because he didn't see the ability to set non-Java tags, I thought others might be in the same position.)

Run on server option not appearing in Eclipse

I had a similar issue. The Maven projects have different structure than "Dynamic Web Projects". Eclipse knows only how to deploy the Dynamic Web Projects (project structure used by Web Tools Platform).

In order to solve this and tell Eclipse how to deploy a "maven style" projects, you have to install the M2E Eclipse WTP plugin (I suppose you are already using the m2e plugin).

To install: Preferences->Maven->Discovery->Open Catalog and choose the WTP plugin.

After reinstalling, you will be able to "run on server" those projects which are maven web projects.

Hope that helps,

Matplotlib make tick labels font size smaller

Please note that newer versions of MPL have a shortcut for this task. An example is shown in the other answer to this question:

The code below is for illustrative purposes and may not necessarily be optimized.

import matplotlib.pyplot as plt
import numpy as np

def xticklabels_example():
    fig = plt.figure() 

    x = np.arange(20)
    y1 = np.cos(x)
    y2 = (x**2)
    y3 = (x**3)
    yn = (y1,y2,y3)
    COLORS = ('b','g','k')

    for i,y in enumerate(yn):
        ax = fig.add_subplot(len(yn),1,i+1)

        ax.plot(x, y, ls='solid', color=COLORS[i]) 

        if i != len(yn) - 1:
            # all but last 
            ax.set_xticklabels( () )
            for tick in ax.xaxis.get_major_ticks():
                # specify integer or one of preset strings, e.g.

    fig.suptitle('Matplotlib xticklabels Example')

if __name__ == '__main__':

enter image description here

Change URL without refresh the page

When you use a function ...

<p onclick="update_url('/en/step2');">Link</p>

function update_url(url) {
    history.pushState(null, null, url);

"use database_name" command in PostgreSQL

When you get a connection to PostgreSQL it is always to a particular database. To access a different database, you must get a new connection.

Using \c in psql closes the old connection and acquires a new one, using the specified database and/or credentials. You get a whole new back-end process and everything.

disabling spring security in spring boot app

You could just comment the maven dependency for a while:

<!--        <dependency>

It worked fine for me

Disabling it from is deprecated for Spring Boot 2.0

SQL: How To Select Earliest Row

In this case a relatively simple GROUP BY can work, but in general, when there are additional columns where you can't order by but you want them from the particular row which they are associated with, you can either join back to the detail using all the parts of the key or use OVER():

Runnable example (Wofkflow20 error in original data corrected)

;WITH partitioned AS (
    SELECT company
        ,ROW_NUMBER() OVER(PARTITION BY company, workflow
                            ORDER BY date) AS seq
    FROM workflowTable
FROM partitioned WHERE seq = 1

How to initialize weights in PyTorch?

If you see a deprecation warning (@Fábio Perez)...

def init_weights(m):
    if type(m) == nn.Linear:

net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2))


For me this happened within a class function.

In PHP 5.3 and above $this::$defaults worked fine; when I swapped the code into a server that for whatever reason had a lower version number it threw this error.

The solution, in my case, was to use the keyword self instead of $this:

self::$defaults works just fine.

MySQL - how to front pad zip code with "0"?

LPAD works with VARCHAR2 as it does not put spaces for left over bytes. LPAD changes leftover/null bytes to zeros on LHS SO datatype should be VARCHAR2

fast way to copy formatting in excel

Just use the NumberFormat property after the Value property: In this example the Ranges are defined using variables called ColLetter and SheetRow and this comes from a for-next loop using the integer i, but they might be ordinary defined ranges of course.

TransferSheet.Range(ColLetter & SheetRow).Value = Range(ColLetter & i).Value TransferSheet.Range(ColLetter & SheetRow).NumberFormat = Range(ColLetter & i).NumberFormat

How to get the CUDA version?

Found mine after:

whereis cuda


cuda: /usr/lib/cuda /usr/include/cuda.h


nvcc --version

CUDA Version 9.1.85

error: member access into incomplete type : forward declaration of

You must have the definition of class B before you use the class. How else would the compiler otherwise know that there exists such a function as B::add?

Either define class B before class A, or move the body of A::doSomething to after class B have been defined, like

class B;

class A
    B* b;

    void doSomething();

class B
    A* a;

    void add() {}

void A::doSomething()

How to use global variables in React Native?

Try to use = bar in or index.ios.js, then you can call in other file js.

Substitute a comma with a line break in a cell

You can also do this without VBA from the find/replace dialogue box. My answer was at .

nodejs send html file to client

After years, I want to add another approach by using a view engine in Express.js

var fs = require('fs');

app.get('/test', function(req, res, next) {
    var html = fs.readFileSync('./html/test.html', 'utf8')
    res.render('test', { html: html })
    // or res.send(html)

Then, do that in your views/test if you choose res.render method at the above code (I'm writing in EJS format):

<%- locals.html %>

That's all.

In this way, you don't need to break your View Engine arrangements.

iterrows pandas get next rows value

I would use shift() function as follows:

df['value_1'] = df.value.shift(-1)
[print(x) for x in df.T.unstack().dropna(how = 'any').values];

which produces


This is how the code above works:

Step 1) Use shift function

df['value_1'] = df.value.shift(-1)


value value_1
0    AA      BB
1    BB      CC
2    CC     NaN

step 2) Transpose:

df = df.T


          0   1    2
value    AA  BB   CC
value_1  BB  CC  NaN

Step 3) Unstack:

df = df.unstack()


0  value       AA
   value_1     BB
1  value       BB
   value_1     CC
2  value       CC
   value_1    NaN
dtype: object

Step 4) Drop NaN values

df = df.dropna(how = 'any')


0  value      AA
   value_1    BB
1  value      BB
   value_1    CC
2  value      CC
dtype: object

Step 5) Return a Numpy representation of the DataFrame, and print value by value:

df = df.values
[print(x) for x in df];



How can I view the source code for a function?

You can also try to use print.function(), which is S3 generic, to get the function write in the console.

Rmi connection refused with localhost

It seems to work when I replace the

Runtime.getRuntime().exec("rmiregistry 2020");



anyone an idea why? What's the difference?

Get all dates between two dates in SQL Server

This is the method that I would use.

    @DateFrom DATETIME = GETDATE(),
    @DateTo DATETIME = DATEADD(HOUR, -1, GETDATE() + 2); -- Add 2 days and minus one hour

-- Dates spaced a day apart 

WITH MyDates (MyDate)
AS (
    SELECT @DateFrom
    FROM MyDates
    WHERE MyDate < @DateTo

    , CONVERT(DATE, MyDates.MyDate) AS [MyDate in DATE format]

Here is a similar example, but this time the dates are spaced one hour apart to further aid understanding of how the query works:

-- Alternative example with dates spaced an hour apart

WITH MyDates (MyDate)
AS (SELECT @DateFrom
    FROM MyDates
    WHERE MyDate < @DateTo


As you can see, the query is fast, accurate and versatile.

How to printf "unsigned long" in C?

int main()
    unsigned long long d;

This will be helpful . . .

Print current call stack from a method in Python code

If you use python debugger, not only interactive probing of variables but you can get the call stack with the "where" command or "w".

So at the top of your program

import pdb

Then in the code where you want to see what is happening


and you get dropped into a prompt

Check if an object exists

You can use:

   # get your models
except ObjectDoesNotExist:
   # do something

Warning: mysql_connect(): [2002] No such file or directory (trying to connect via unix:///tmp/mysql.sock) in

I am on XAMPP on Mac OS X, and Brian Lowe's solution above worked with a slight modification.

The mysql.sock file is actually in "/Applications/xampp/xamppfiles/var/mysql/" folder. So had to link it up both in /tmp and /var/mysql. I haven't checked which one is used by PHP command line, but this did the fix, so I am happy :-)

sudo su
ln -s /Applications/xampp/xamppfiles/var/mysql/mysql.sock /tmp/mysql.sock
mkdir /var/mysql
ln -s /Applications/xampp/xamppfiles/var/mysql/mysql.sock /var/mysql/mysql.sock

Counter inside xsl:for-each loop


<xsl:value-of select="count(preceding-sibling::*) + 1" />

Edit - had a brain freeze there, position() is more straightforward!

Composer could not find a composer.json

If you forget to run:

php artisan key:generate

You would be face this error : Composer could not find a composer.json

What is Persistence Context?

A persistent context represents the entities which hold data and are qualified to be persisted in some persistent storage like a database. Once we commit a transaction under a session which has these entities attached with, Hibernate flushes the persistent context and changes(insert/save, update or delete) on them are persisted in the persistent storage.

gdb fails with "Unable to find Mach task port for process-id" error

You need to create a certificate and sign gdb:

  • Open application “Keychain Access” (/Applications/Utilities/Keychain
  • Open menu /Keychain Access/Certificate Assistant/Create a Certificate...
  • Choose a name (gdb-cert in the example), set “Identity Type” to “Self Signed Root”, set “Certificate Type” to “Code Signing” and select the “Let me override defaults”. Click “Continue”. You might want to extend the predefined 365 days period to 3650 days.
  • Click several times on “Continue” until you get to the “Specify a Location For The Certificate” screen, then set “Keychain to System”.
  • If you can't store the certificate in the “System” keychain, create it in the “login” keychain, then export it. You can then import it into the “System” keychain.
  • In keychains select “System”, and you should find your new certificate. Use the context menu for the certificate, select “Get Info”, open the “Trust” item, and set “Code Signing” to “Always Trust”.
  • You must quit “Keychain Access” application in order to use the certificate and restart “taskgated” service by killing the current running “taskgated” process. Alternatively you can restart your computer.
  • Finally you can sign gdb:

    sudo codesign -s gdb-cert /usr/local/bin/ggdb

    sudo ggdb ./myprog

Change Background color (css property) using Jquery

$("#bchange").click(function() {
    $("body, this").css("background-color","yellow");

How do I write a RGB color value in JavaScript?

I am showing with an example of adding random color. You can write this way

var r = Math.floor(Math.random() * 255);
var g = Math.floor(Math.random() * 255);
var b = Math.floor(Math.random() * 255);
var col = "rgb(" + r + "," + g + "," + b + ")";
parent.childNodes[1].style.color = col;

The property is expected as a string

NGinx Default public www location?

Dump the configuration:

$ nginx -T
server {
    location / {
        root   /usr/share/nginx/html;

What you get might be different since it depends on how your nginx was configured/installed.


Update: There's some confusion on the issue of if/when the -T option was added to nginx. It was documented in the man page by vl-homutov on 2015 June 16, which became part of the v1.9.2 release. It's even mentioned in the release notes. The -T option has been present in every nginx release since, including the one available on Ubuntu 16.04.1 LTS:

root@23cc8e58640e:/# nginx -h    
nginx version: nginx/1.10.0 (Ubuntu)
Usage: nginx [-?hvVtTq] [-s signal] [-c filename] [-p prefix] [-g directives]

  -?,-h         : this help
  -v            : show version and exit
  -V            : show version and configure options then exit
  -t            : test configuration and exit
  -T            : test configuration, dump it and exit
  -q            : suppress non-error messages during configuration testing
  -s signal     : send signal to a master process: stop, quit, reopen, reload
  -p prefix     : set prefix path (default: /usr/share/nginx/)
  -c filename   : set configuration file (default: /etc/nginx/nginx.conf)
  -g directives : set global directives out of configuration file

How do I concatenate two lists in Python?

import itertools

A = list(zip([1,3,5,7,9],[2,4,6,8,10]))
B = [1,3,5,7,9]+[2,4,6,8,10]
C = list(set([1,3,5,7,9] + [2,4,6,8,10]))

D = [1,3,5,7,9]

E = [1,3,5,7,9]

F = []
for a in itertools.chain([1,3,5,7,9], [2,4,6,8,10]):

print ("A: " + str(A))
print ("B: " + str(B))
print ("C: " + str(C))
print ("D: " + str(D))
print ("E: " + str(E))
print ("F: " + str(F))


A: [(1, 2), (3, 4), (5, 6), (7, 8), (9, 10)]
B: [1, 3, 5, 7, 9, 2, 4, 6, 8, 10]
C: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
D: [1, 3, 5, 7, 9, [2, 4, 6, 8, 10]]
E: [1, 3, 5, 7, 9, 2, 4, 6, 8, 10]
F: [1, 3, 5, 7, 9, 2, 4, 6, 8, 10]

What is the proper way to check if a string is empty in Perl?

To check for an empty string you could also do something as follows

if (!defined $val || $val eq '')
    # empty

How to install xgboost in Anaconda Python (Windows platform)?

if you found an issue when you try to import xgboost (my case it is Windows 10 and anaconda spyder) do the following:

  1. Click on the windows icon (start button!)
  2. Select and expand the anaconda folder
  3. Run the Anaconda Prompt (as Administrator)
  4. Type the following command as it is mentioned in

conda install -c anaconda py-xgboost

enter image description here

That's all...Good luck.

How to use Chrome's network debugger with redirects

Just update of @bfncs answer

I think around Chrome 43 the behavior was changed a little. You still need to enable Preserve log to see, but now redirect shown under Other tab, when loaded document is shown under Doc.

This always confuse me, because I have a lot of networks requests and filter it by type XHR, Doc, JS etc. But in case of redirect the Doc tab is empty, so I have to guess.

Sleep function in Windows, using C


#include <windows.h>

Sleep(sometime_in_millisecs); // Note uppercase S

And here's a small example that compiles with MinGW and does what it says on the tin:

#include <windows.h>
#include <stdio.h>

int main() {
    printf( "starting to sleep...\n" );
    Sleep(3000); // Sleep three seconds
    printf("sleep ended\n");

How can I add a hint or tooltip to a label in C# Winforms?

just another way to do it.

Label lbl = new Label();
new ToolTip().SetToolTip(lbl, "tooltip text here");

Internal vs. Private Access Modifiers

private - encapsulations in class/scope/struct ect'.

internal - encapsulation in assemblies.

Css Move element from left to right animated

It's because you aren't giving the un-hovered state a right attribute.

right isn't set so it's trying to go from nothing to 0px. Obviously because it has nothing to go to, it just 'warps' over.

If you give the unhovered state a right:90%;, it will transition how you like.

Just as a side note, if you still want it to be on the very left of the page, you can use the calc css function.


right: calc(100% - 100px)
                     ^ width of div

You don't have to use left then.

Also, you can't transition using left or right auto and will give the same 'warp' effect.

div {_x000D_
    right:calc(100% - 100px);_x000D_
div:hover {_x000D_
  <b>Note:</b> This example does not work in Internet Explorer 9 and earlier versions._x000D_
<p>Hover over the red square to see the transition effect.</p>

CanIUse says that the calc() function only works on IE10+

Conda version pip install -r requirements.txt --target ./lib

A quick search on the conda official docs will help you to find what each flag does.

So far:

  • -y: Do not ask for confirmation.
  • -f: I think it should be --file, so it read package versions from the given file.
  • -q: Do not display progress bar.
  • -c: Additional channel to search for packages. These are URLs searched in the order

ps1 cannot be loaded because running scripts is disabled on this system

Open terminal

Run the command: Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Unrestricted

in terminal: yarn --version

What's is the difference between include and extend in use case diagram?

I don't recommend the use of this to remember the two:

My use case: I am going to the city.

includes -> drive the car

extends -> fill the petrol

I would rather you use: My use case: I am going to the city.

extends -> driving the car

includes -> fill the petrol

Am taught that extend relationship continues the behaviour of a base class. The base class functionalities have to be there. The include relationship on the other hand, are akin to functions that may be called. May is in bold.

This can be seen from agilemodeling Reuse in Use-Case Models

How to get the first and last date of the current year?

Another way: (Since SQL Server 2012)


Check if property has attribute

You can use a common (generic) method to read attribute over a given MemberInfo

public static bool TryGetAttribute<T>(MemberInfo memberInfo, out T customAttribute) where T: Attribute {
                var attributes = memberInfo.GetCustomAttributes(typeof(T), false).FirstOrDefault();
                if (attributes == null) {
                    customAttribute = null;
                    return false;
                customAttribute = (T)attributes;
                return true;

Generating a PNG with matplotlib when DISPLAY is undefined

To make sure your code is portable across Windows, Linux and OSX and for systems with and without displays, I would suggest following snippet:

import matplotlib
import os
# must be before importing matplotlib.pyplot or pylab!
if == 'posix' and "DISPLAY" not in os.environ:

# now import other things from matplotlib
import matplotlib.pyplot as plt


Generate insert script for selected records?

SELECT 'INSERT SomeOtherDB.dbo.table(column1,column2,etc.)
  SELECT ' + CONVERT(VARCHAR(12), Pk_Id) + ','
       + '''' + REPLACE(ProductName, '''', '''''') + ''','
       + CONVERT(VARCHAR(12), Fk_CompanyId) + ','
       + CONVERT(VARCHAR(12), Price) + ';'
FROM dbo.unspecified_table_name
WHERE Fk_CompanyId = 1;

mvn clean install vs. deploy vs. release

  • mvn install will put your packaged maven project into the local repository, for local application using your project as a dependency.
  • mvn release will basically put your current code in a tag on your SCM, change your version in your projects.
  • mvn deploy will put your packaged maven project into a remote repository for sharing with other developers.

Resources :

Update GCC on OSX

If you install macports you can install gcc select, and then choose your gcc version.

/opt/local/bin/port install gcc_select

To see your versions use

port select --list gcc

To select a version use

sudo port select --set gcc gcc40

Why is 2 * (i * i) faster than 2 * i * i in Java?

While not directly related to the question's environment, just for the curiosity, I did the same test on .NET Core 2.1, x64, release mode.

Here is the interesting result, confirming similar phonomena (other way around) happening over the dark side of the force. Code:

static void Main(string[] args)
    Stopwatch watch = new Stopwatch();

    Console.WriteLine("2 * (i * i)");

    for (int a = 0; a < 10; a++)
        int n = 0;


        for (int i = 0; i < 1000000000; i++)
            n += 2 * (i * i);


        Console.WriteLine($"result:{n}, {watch.ElapsedMilliseconds} ms");

    Console.WriteLine("2 * i * i");

    for (int a = 0; a < 10; a++)
        int n = 0;


        for (int i = 0; i < 1000000000; i++)
            n += 2 * i * i;


        Console.WriteLine($"result:{n}, {watch.ElapsedMilliseconds}ms");


2 * (i * i)

  • result:119860736, 438 ms
  • result:119860736, 433 ms
  • result:119860736, 437 ms
  • result:119860736, 435 ms
  • result:119860736, 436 ms
  • result:119860736, 435 ms
  • result:119860736, 435 ms
  • result:119860736, 439 ms
  • result:119860736, 436 ms
  • result:119860736, 437 ms

2 * i * i

  • result:119860736, 417 ms
  • result:119860736, 417 ms
  • result:119860736, 417 ms
  • result:119860736, 418 ms
  • result:119860736, 418 ms
  • result:119860736, 417 ms
  • result:119860736, 418 ms
  • result:119860736, 416 ms
  • result:119860736, 417 ms
  • result:119860736, 418 ms

Spring data JPA query with parameter properties

You can try something like this:

public interface PersonRepository extends CrudRepository<Person, Long> {
       @Query("select p from Person AS p"
       + " ,Name AS n"  
       + " where p.forename = n.forename "
       + " and p.surname = n.surname"
       + " and n = :name")
       Set<Person>findByName(@Param("name") Name name);

Quoting backslashes in Python string literals

What Harley said, except the last point - it's not actually necessary to change the '/'s into '\'s before calling open. Windows is quite happy to accept paths with forward slashes.

infile = open('c:/folder/subfolder/file.txt')

The only time you're likely to need the string normpathed is if you're passing to to another program via the shell (using os.system or the subprocess module).

How to support UTF-8 encoding in Eclipse

You can set a default encoding-set whenever you run eclipse.exe.

  1. Open eclipse.ini in your eclipse home directory Or STS.ini in case of STS(Spring Tool Suite)
  2. put the line below at the end of the file


How to detect browser using angularjs?

You can easily use the "ng-device-detector" module.

var app = angular.module('myapp', ["ng.deviceDetector"]);
app.controller('DeviceCtrl', ["$scope","deviceDetector",function($scope,deviceDetector) {
      console.log("browser: ", deviceDetector.browser);
      console.log("browser version: ", deviceDetector.browser_version);
      console.log("device: ", deviceDetector.device);

How to remove elements from a generic list while iterating over it?

Select the elements you do want rather than trying to remove the elements you don't want. This is so much easier (and generally more efficient too) than removing elements.

var newSequence = (from el in list
                   where el.Something || el.AnotherThing < 0
                   select el);

I wanted to post this as a comment in response to the comment left by Michael Dillon below, but it's too long and probably useful to have in my answer anyway:

Personally, I'd never remove items one-by-one, if you do need removal, then call RemoveAll which takes a predicate and only rearranges the internal array once, whereas Remove does an Array.Copy operation for every element you remove. RemoveAll is vastly more efficient.

And when you're backwards iterating over a list, you already have the index of the element you want to remove, so it would be far more efficient to call RemoveAt, because Remove first does a traversal of the list to find the index of the element you're trying to remove, but you already know that index.

So all in all, I don't see any reason to ever call Remove in a for-loop. And ideally, if it is at all possible, use the above code to stream elements from the list as needed so no second data structure has to be created at all.

java.lang.NullPointerException: Attempt to invoke virtual method on a null object reference

Your app is crashing at:

welcomePlayer.setText("Welcome Back, " + String.valueOf(mPlayer.getName(this)) + " !");

because mPlayer=null.

You forgot to initialize Player mPlayer in your PlayGame Activity.

mPlayer = new Player(context,"");

Is there a better way to run a command N times in bash?

Using a constant:

for ((n=0;n<10;n++)); do

Using a variable (can include math expressions):

x=10; for ((n=0; n < (x / 2); n++)); do some_command; done

ORA-12514 TNS:listener does not currently know of service requested in connect descriptor

In my circumstances the error was due to the fact the listener did not have the db's service registered. I solved this by registering the services. Example:

My descriptor in tnsnames.ora:

    (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))

So, I proceed to register the service in the listener.ora manually:

    (SID_DESC =
      (ORACLE_HOME = C:\Oracle\product\11.2.0\dbhome_1)

Finally, restart the listener by command:

> lsnrctl stop
> lsnrctl start


How to change letter spacing in a Textview?

As android doesn't support such a thing, you can do it manually with FontCreator. It has good options for font modifying. I used this tool to build a custom font, even if it takes some times but you can always use it in your projects.

Display Adobe pdf inside a div

We use this on our website

Its a very customizable to display PDF's directly in your browser. It basically hosts the PDF in a flash object if you are not opposed to that sort of thing.

Here is a sample from our corporate website.

Gerrit error when Change-Id in commit messages are missing

I got this error message too.

and what makes me think it is useful to give an answer here is that the answer from @Rafal Rawicki is a good solution in some cases but not for all circumstances. example that i met: "git log" we can get the HEAD commit change-id

2.we also can get a 'HEAD' commit change-id on Gerrit website.

3.they are different ,which makes us can not push successfully and get the "missing change-id error"


0.'git add .' your HEAD commit change-id got from 'git log',it will be used later.

2.copy the HEAD commit change-id from Gerrit website.

3.'git reset HEAD'

4.'git commit --amend' and copy the change-id from **Gerrit website** to the commit message in the last paragraph(replace previous change-id)

5.'git push *' you can push successfully now but can not find the HEAD commit from **git log** on Gerrit website too

6.'git reset HEAD'

7.'git commit --amend' and copy the change-id from **git log**(we saved in step 1) to the commit message in the last paragraph(replace previous change-id)

8.'git push *' you can find the HEAD commit from **git log** on Gerrit website,they have the same change-id


PHP DOMDocument loadHTML not encoding UTF-8 correctly

You could prefix a line enforcing utf-8 encoding, like this:

@$doc->loadHTML('<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $profile);

And you can then continue with the code you already have, like:


Loop through JSON in EJS

in my case, datas is an objects of Array for more information please Click Here

<% for(let [index,data] of datas.entries() || []){  %>
 Index : <%=index%>
 Data : <%=data%>
<%} %>

Auto-increment on partial primary key with Entity Framework Core

First of all you should not merge the Fluent Api with the data annotation so I would suggest you to use one of the below:

make sure you have correclty set the keys

            .HasKey(p => new { p.Name, p.Id });
modelBuilder.Entity<Foo>().Property(p => p.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

OR you can achieve it using data annotation as well

public class Foo
    [Key, Column(Order = 0)]
    public int Id { get; set; }

    [Key, Column(Order = 1)]
    public string Name{ get; set; }

Angular 2: How to write a for loop, not a foreach loop

Depending on the length of the wanted loop, maybe even a more "template-driven" solution:

  <li *ngFor="let index of [0,1,2,3,4,5]">
    {{ index }}

FIFO based Queue implementations?

ArrayDeque is probably the fastest object-based queue in the JDK; Trove has the TIntQueue interface, but I don't know where its implementations live.

How can I get the size of an std::vector as an int?

In the first two cases, you simply forgot to actually call the member function (!, it's not a value) std::vector<int>::size like this:

#include <vector>

int main () {
    std::vector<int> v;
    auto size = v.size();

Your third call

int size = v.size();

triggers a warning, as not every return value of that function (usually a 64 bit unsigned int) can be represented as a 32 bit signed int.

int size = static_cast<int>(v.size());

would always compile cleanly and also explicitly states that your conversion from std::vector::size_type to int was intended.

Note that if the size of the vector is greater than the biggest number an int can represent, size will contain an implementation defined (de facto garbage) value.

jQuery ajax success callback function definition

I would write :

var handleData = function (data) {
    //do some stuff

function getData() {
        url : '',
        type: 'GET',
        success : handleData

Parsing ISO 8601 date in Javascript

According to MSDN, the JavaScript Date object does not provide any specific date formatting methods (as you may see with other programming languages). However, you can use a few of the Date methods and formatting to accomplish your goal:

function dateToString (date) {
  // Use an array to format the month numbers
  var months = [

  // Use an object to format the timezone identifiers
  var timeZones = {
    "360": "EST",

  var month = months[date.getMonth()];
  var day = date.getDate();
  var year = date.getFullYear();

  var hours = date.getHours();
  var minutes = date.getMinutes();
  var time = (hours > 11 ? (hours - 11) : (hours + 1)) + ":" + minutes + (hours > 11 ? "PM" : "AM");
  var timezone = timeZones[date.getTimezoneOffset()];

  // Returns formatted date as string (e.g. January 28, 2011 - 7:30PM EST)
  return month + " " + day + ", " + year + " - " + time + " " + timezone;

var date = new Date("2011-01-28T19:30:00-05:00");


You could even take it one step further and override the Date.toString() method:

function dateToString () { // No date argument this time
  // Use an array to format the month numbers
  var months = [

  // Use an object to format the timezone identifiers
  var timeZones = {
    "360": "EST",

  var month = months[*this*.getMonth()];
  var day = *this*.getDate();
  var year = *this*.getFullYear();

  var hours = *this*.getHours();
  var minutes = *this*.getMinutes();
  var time = (hours > 11 ? (hours - 11) : (hours + 1)) + ":" + minutes + (hours > 11 ? "PM" : "AM");
  var timezone = timeZones[*this*.getTimezoneOffset()];

  // Returns formatted date as string (e.g. January 28, 2011 - 7:30PM EST)
  return month + " " + day + ", " + year + " - " + time + " " + timezone;

var date = new Date("2011-01-28T19:30:00-05:00");
Date.prototype.toString = dateToString;


Create a hidden field in JavaScript

I've found this to work:

var element1 = document.createElement("input");
element1.type = "hidden";
element1.value = "10"; = "a";

Use of min and max functions in C++

As you noted yourself, fmin and fmax were introduced in C99. Standard C++ library doesn't have fmin and fmax functions. Until C99 standard library gets incorporated into C++ (if ever), the application areas of these functions are cleanly separated. There's no situation where you might have to "prefer" one over the other.

You just use templated std::min/std::max in C++, and use whatever is available in C.

Programmatic equivalent of default(Type)

Can't find anything simple and elegant just yet, but I have one idea: If you know the type of the property you wish to set, you can write your own default(T). There are two cases - T is a value type, and T is a reference type. You can see this by checking T.IsValueType. If T is a reference type, then you can simply set it to null. If T is a value type, then it will have a default parameterless constructor that you can call to get a "blank" value.

Search for a particular string in Oracle clob column

select *  
where dbms_lob.instr(COLUMNNAME,'searchtext') > 0;

IIS7 - The request filtering module is configured to deny a request that exceeds the request content length

I had similar issue, I resolved by changing the requestlimits maxAllowedContentLength ="40000000" section of applicationhost.config file, located in "C:\Windows\System32\inetsrv\config" directory

Look for security Section and add the sectionGroup.

<sectionGroup name="requestfiltering">
    <section name="requestlimits" maxAllowedContentLength ="40000000" />

*NOTE delete;

<section name="requestfiltering" overrideModeDefault="Deny" />

"detached entity passed to persist error" with JPA/EJB code

If you set id in your database to be primary key and autoincrement, then this line of code is wrong:


Try with this:

public static void main(String[] args){
         UserBean user = new UserBean();

JavaScript hard refresh of current page

Try to use:


When this method receives a true value as argument, it will cause the page to always be reloaded from the server. If it is false or not specified, the browser may reload the page from its cache.

More info: