Programs & Examples On #Datefield

Laravel Eloquent where field is X or null

You could merge two queries together:

$merged = $query_one->merge($query_two);

How to add plus one (+1) to a SQL Server column in a SQL Query

"UPDATE TableName SET TableField = TableField + 1 WHERE SomeFilterField = @ParameterID"

Foreign Key Django Model

You create the relationships the other way around; add foreign keys to the Person type to create a Many-to-One relationship:

class Person(models.Model):
    name = models.CharField(max_length=50)
    birthday = models.DateField()
    anniversary = models.ForeignKey(
        Anniversary, on_delete=models.CASCADE)
    address = models.ForeignKey(
        Address, on_delete=models.CASCADE)

class Address(models.Model):
    line1 = models.CharField(max_length=150)
    line2 = models.CharField(max_length=150)
    postalcode = models.CharField(max_length=10)
    city = models.CharField(max_length=150)
    country = models.CharField(max_length=150)

class Anniversary(models.Model):
    date = models.DateField()

Any one person can only be connected to one address and one anniversary, but addresses and anniversaries can be referenced from multiple Person entries.

Anniversary and Address objects will be given a reverse, backwards relationship too; by default it'll be called person_set but you can configure a different name if you need to. See Following relationships "backward" in the queries documentation.

django no such table:

sqlall just prints the SQL, it doesn't execute it. syncdb will create tables that aren't already created, but it won't modify existing tables.

How do I get the current date and current time only respectively in Django?

Another way to get datetime UTC with milliseconds.

from datetime import datetime

datetime.utcnow().isoformat(sep='T', timespec='milliseconds') + 'Z'


How do I filter query objects by date range in Django?

Is simple,


Works for me

Age from birthdate in python

from datetime import date

def calculate_age(born):
    today =
        birthday = born.replace(year=today.year)
    except ValueError: # raised when birth date is February 29 and the current year is not a leap year
        birthday = born.replace(year=today.year, month=born.month+1, day=1)
    if birthday > today:
        return today.year - born.year - 1
        return today.year - born.year

Update: Use Danny's solution, it's better

Django DateField default options

This is why you should always import the base datetime module: import datetime, rather than the datetime class within that module: from datetime import datetime.

The other mistake you have made is to actually call the function in the default, with the (). This means that all models will get the date at the time the class is first defined - so if your server stays up for days or weeks without restarting Apache, all elements will get same the initial date.

So the field should be:

import datetime
date = models.DateField(_("Date"),

How to convert / cast long to String?

See the reference documentation for the String class: String s = String.valueOf(date);

If your Long might be null and you don't want to get a 4-letter "null" string, you might use Objects.toString, like: String s = Objects.toString(date, null);


You reverse it using Long l = Long.valueOf(s); but in this direction you need to catch NumberFormatException

How to select element using XPATH syntax on Selenium for Python?

Check this blog by Martin Thoma. I tested the below code on MacOS Mojave and it worked as specified.

> def get_browser():
>     """Get the browser (a "driver")."""
>     # find the path with 'which chromedriver'
>     path_to_chromedriver = ('/home/moose/GitHub/algorithms/scraping/'
>                             'venv/bin/chromedriver')
>     download_dir = "/home/moose/selenium-download/"
>     print("Is directory: {}".format(os.path.isdir(download_dir)))
>     from import Options
>     chrome_options = Options()
>     chrome_options.add_experimental_option('prefs', {
>         "plugins.plugins_list": [{"enabled": False,
>                                   "name": "Chrome PDF Viewer"}],
>         "download": {
>             "prompt_for_download": False,
>             "default_directory": download_dir
>         }
>     })
>     browser = webdriver.Chrome(path_to_chromedriver,
>                                chrome_options=chrome_options)
>     return browser

Convert np.array of type float64 to type uint8 scaling values

Considering that you are using OpenCV, the best way to convert between data types is to use normalize function.

img_n = cv2.normalize(src=img, dst=None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_8U)

However, if you don't want to use OpenCV, you can do this in numpy

def convert(img, target_type_min, target_type_max, target_type):
    imin = img.min()
    imax = img.max()

    a = (target_type_max - target_type_min) / (imax - imin)
    b = target_type_max - a * imax
    new_img = (a * img + b).astype(target_type)
    return new_img

And then use it like this

imgu8 = convert(img16u, 0, 255, np.uint8)

This is based on the answer that I found on crossvalidated board in comments under this solution

Changing the position of Bootstrap popovers based on the popover's X position in relation to window edge?

You can use auto in data placement like data-placement="auto left". It will automatic adjust according to your screen size and default placement will be left.

Center HTML Input Text Field Placeholder

You can try like this :

input[placeholder] {
   text-align: center;

Stock ticker symbol lookup API

Use YQL and you don't need to worry. It's a query language by Yahoo and you can get all the stock data including the name of the company for the ticker. It's a REST API and it returns the results via XML or JSON. I have a full tutorial and source code on my site take a look:

How get permission for camera in android.(Specifically Marshmallow)

check using this
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA)
            == PackageManager.PERMISSION_DENIED)


Can you style html form buttons with css?

Yes you can target those specificaly using input[type=submit] e.g.

.myFormClass input[type=submit] {
  margin: 10px;
  color: white;
  background-color: blue;

SQL select join: is it possible to prefix all columns as 'prefix.*'?

PHP 7.2 + MySQL/Mariadb

MySQL will send you multiple fields with the same name. Even in the terminal client. But if you want an associative array, you'll have to make the keys yourself.

Thanks to @axelbrz for the original. I've ported it to newer php and cleaned it up a little:

function mysqli_rows_with_columns($link, $query) {
    $result = mysqli_query($link, $query);
    if (!$result) {
        return mysqli_error($link);
    $field_count = mysqli_num_fields($result);
    $fields = array();
    for ($i = 0; $i < $field_count; $i++) {
        $field = mysqli_fetch_field_direct($result, $i);
        $fields[] = $field->table . '.' . $field->name; # changed by AS
        #$fields[] = $field->orgtable . '.' . $field->orgname; # actual table/field names
    $rows = array();
    while ($row = mysqli_fetch_row($result)) {
        $new_row = array();
        for ($i = 0; $i < $field_count; $i++) {
            $new_row[$fields[$i]] = $row[$i];
        $rows[] = $new_row;
    return $rows;

$link = mysqli_connect('localhost', 'fixme', 'fixme', 'fixme');
print_r(mysqli_rows_with_columns($link, 'select foo.*, bar.* from foo, bar'));

Import Certificate to Trusted Root but not to Personal [Command Line]

Look at the documentation of certutil.exe and -addstore option.

I tried

certutil -addstore "Root" "c:\cacert.cer"

and it worked well (meaning The certificate landed in Trusted Root of LocalMachine store).


If there are multiple certificates in a pfx file (key + corresponding certificate and a CA certificate) then this command worked well for me:

certutil -importpfx c:\somepfx.pfx


To import CA certificate to Intermediate Certification Authorities store run following command

certutil -addstore "CA" "c:\intermediate_cacert.cer"

CSS3 background image transition

You can transition background-image. Use the CSS below on the img element:

-webkit-transition: background-image 0.2s ease-in-out;
transition: background-image 0.2s ease-in-out;

This is supported natively by Chrome, Opera and Safari. Firefox hasn't implemented it yet ( Not sure about IE.

Sass calculate percent minus px

Sass cannot perform arithmetic on values that cannot be converted from one unit to the next. Sass has no way of knowing exactly how wide "100%" is in terms of pixels or any other unit. That's something only the browser knows.

You need to use calc() instead. Check browser compatibility on Can I use...

.foo {
    height: calc(25% - 5px);

If your values are in variables, you may need to use interpolation turn them into strings (otherwise Sass just tries to perform arithmetic):

$a: 25%;
$b: 5px;

.foo {
  width: calc(#{$a} - #{$b});

How is Java platform-independent when it needs a JVM to run?

when we compile java file the .class file of that program is generated that .class file contain the byte code.That byte code is platform independent,byte code can run on any operating system using java virtual machine. platform independence not about only operating system it also about the hardware. When you run you java application on a 16-bit machine that you made on 32-bit, you do not have to worry about converting the data types according to the target system. You can run your app on any architecture and you will get the same result in each.

What are the differences between normal and slim package of jquery?

At this time, the most authoritative answer appears to be in this issue, which states "it is a custom build of jQuery that excludes effects, ajax, and deprecated code." Details will be announced with jQuery 3.0.

I suspect that the rationale for excluding these components of the jQuery library is in recognition of the increasingly common scenario of jQuery being used in conjunction with another JS framework like Angular or React. In these cases, the usage of jQuery is primarily for DOM traversal and manipulation, so leaving out those components that are either obsolete or are provided by the framework gains about a 20% reduction in file size.

Remove part of a string

If you're a Tidyverse kind of person, here's the stringr solution:

R> library(stringr)
R> strings = c("TGAS_1121", "MGAS_1432", "ATGAS_1121") 
R> strings %>% str_replace(".*_", "_")
[1] "_1121" "_1432" "_1121"
# Or:
R> strings %>% str_replace("^[A-Z]*", "")
[1] "_1121" "_1432" "_1121"

How to get multiple select box values using jQuery?

Just by one line-

var select_button_text = $('#SelectQButton option:selected')
                .toArray().map(item => item.text);

Output: ["text1", "text2"]

var select_button_text = $('#SelectQButton option:selected')
                .toArray().map(item => item.value);

Output: ["value1", "value2"]

If you use .join()

var select_button_text = $('#SelectQButton option:selected')
                .toArray().map(item => item.text).join();

Output: text1,text2,text3

Bloomberg BDH function with ISIN

I had the same problem. Here's what I figured out:

=BDP(A1&"@BGN Corp", "Issuer_parent_eqy_ticker")

A1 being the ISINs. This will return the ticker number. Then just use the ticker number to get the price.

Show loading image while $.ajax is performed

I think this might be better if you have tons of $.ajax calls



If you use CSS. The element you want to shown while ajax is fetching data from your back-end code must be like this.

AnyElementYouWantToShowOnAjaxSend {
    position: fixed;
    top: 0;
    left: 0;
    height: 100vh; /* to make it responsive */
    width: 100vw; /* to make it responsive */
    overflow: hidden; /*to remove scrollbars */
    z-index: 99999; /*to make it appear on topmost part of the page */
    display: none; /*to make it visible only on fadeIn() function */

How to add pandas data to an existing csv file?

You can append to a csv by opening the file in append mode:

with open('my_csv.csv', 'a') as f:
    df.to_csv(f, header=False)

If this was your csv, foo.csv:


If you read that and then append, for example, df + 6:

In [1]: df = pd.read_csv('foo.csv', index_col=0)

In [2]: df
   A  B  C
0  1  2  3
1  4  5  6

In [3]: df + 6
    A   B   C
0   7   8   9
1  10  11  12

In [4]: with open('foo.csv', 'a') as f:
             (df + 6).to_csv(f, header=False)

foo.csv becomes:



This class was compiled with a JDK more recent than the one used for execution.

The easiest is to install a more recent JRE on the computer where you execute the program. If you think you installed a recent one, check the JAVA_HOME and PATH environment variables.

Version 49 is java 1.5. That means the class was compiled with (or for) a JDK which is yet old. You probably tried to execute the class with JDK 1.4. You really should use one more recent (1.6 or 1.7, see java version history).

jQuery - trapping tab select event

From what I can tell, per the documentation here:, it seems as though you're not quite initializing it right. The demos state that you need a main wrapped <div> element, with a <ul> or possibly <ol> element representing the tabs, and then an element for each tab page (presumable a <div> or <p>, possibly a <section> if we're using HTML5). Then you call $().tabs() on the main <div>, not the <ul> element.

After that, you can bind to the tabsselect event no problem. Check out this fiddle for basic, basic example:

Execution failed for task ':app:compileDebugAidl': aidl is missing

Quick fix that worked for me:

Right click on project->"Open Module Settings"->Build Tools Version change to: 22.0.1

enter image description here

Is there a real solution to debug cordova apps

Here's the solution using Phonegap Build. Add the following to your config.xml to be able to inspect with Chrome Remote Webview Debugging.

First, make sure your widget tag contains xmlns:android=""


Then add the following

<gap:config-file platform="android" parent="/manifest">
     <application android:debuggable="true" />

It works for me on Nexus 5, Phonegap 3.7.0.

<preference name="phonegap-version" value="3.7.0" />

Build the app in Phonegap Build, install the APK, connect the phone to the USB, enable USB debugging on you phone then visit chrome://inspect.


Mobile Redirect using htaccess

First, go to the following URL and download the mobile_detect.php file:

Insert the following code on your index or home page:

$detect = new Mobile_Detect();
if ($detect->isMobile() && isset($_COOKIE['mobile']))
$detect = "false";
elseif ($detect->isMobile())

cannot download, $GOPATH not set

This one worked

Setting up Go development environment on Ubuntu, and how to fix $GOPATH / $GOROOT


mkdir ~/go

Set $GOPATH in .bashrc,

export GOPATH=~/go
export PATH=$PATH:$GOPATH/bin

How to scroll page in flutter

You can try CustomScrollView. Put your CustomScrollView inside Column Widget.

Just for example -

class App extends StatelessWidget {

 App({Key key}): super(key: key);

  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: AppBar(
          title: const Text('AppBar'),
      body: new Container(
          constraints: BoxConstraints.expand(),
          decoration: new BoxDecoration(
            image: new DecorationImage(
              alignment: Alignment.topLeft,
              image: new AssetImage('images/main-bg.png'),
              fit: BoxFit.cover,
          child: new Column(
            children: <Widget>[               
                child: new CustomScrollView(
                  scrollDirection: Axis.vertical,
                  shrinkWrap: false,
                  slivers: <Widget>[
                    new SliverPadding(
                      padding: const EdgeInsets.symmetric(vertical: 0.0),
                      sliver: new SliverList(
                        delegate: new SliverChildBuilderDelegate(
                          (context, index) => new YourRowWidget(),
                          childCount: 5,

In above code I am displaying a list of items ( total 5) in CustomScrollView. YourRowWidget widget gets rendered 5 times as list item. Generally you should render each row based on some data.

You can remove decoration property of Container widget, it is just for providing background image.

How to disable <br> tags inside <div> by css?

I used it like this:

@media (max-width: 450px) {
  br {
    display: none;

nb: media query via Foundation nb2: this is useful if one of the editor intend to use
tags in his/her copy and you need to deal with it specifically under some conditions—on mobile for example.

Finding rows containing a value (or values) in any column

If you want to find the rows that have any of the values in a vector, one option is to loop the vector (lapply(v1,..)), create a logical index of (TRUE/FALSE) with (==). Use Reduce and OR (|) to reduce the list to a single logical matrix by checking the corresponding elements. Sum the rows (rowSums), double negate (!!) to get the rows with any matches.

indx1 <- !!rowSums(Reduce(`|`, lapply(v1, `==`, df)), na.rm=TRUE)

Or vectorise and get the row indices with which with arr.ind=TRUE

indx2 <- unique(which(Vectorize(function(x) x %in% v1)(df),


I didn't use @kristang's solution as it is giving me errors. Based on a 1000x500 matrix, @konvas's solution is the most efficient (so far). But, this may vary if the number of rows are increased

val <- paste0('M0', 1:1000)
df1 <-, NA), 1000*500, 
  replace=TRUE), ncol=500), stringsAsFactors=FALSE) 
v1 <- sample(val, 200, replace=FALSE)

 konvas <- function() {apply(df1, 1, function(r) any(r %in% v1))}
 akrun1 <- function() {!!rowSums(Reduce(`|`, lapply(v1, `==`, df1)),
 akrun2 <- function() {unique(which(Vectorize(function(x) x %in% 

 microbenchmark(konvas(), akrun1(), akrun2(), unit='relative', times=20L)
 #Unit: relative
 #   expr       min         lq       mean     median         uq      max   neval
 # konvas()   1.00000   1.000000   1.000000   1.000000   1.000000  1.00000    20
 # akrun1() 160.08749 147.642721 125.085200 134.491722 151.454441 52.22737    20
 # akrun2()   5.85611   5.641451   4.676836   5.330067   5.269937  2.22255    20
 # cld
 #  a 
 #  b
 #  a 

For ncol = 10, the results are slighjtly different:

expr       min        lq     mean    median        uq       max    neval
 konvas()  3.116722  3.081584  2.90660  2.983618  2.998343  2.394908    20
 akrun1() 27.587827 26.554422 22.91664 23.628950 21.892466 18.305376    20
 akrun2()  1.000000  1.000000  1.00000  1.000000  1.000000  1.000000    20


 v1 <- c('M017', 'M018')
 df <- structure(list(datetime = c("04.10.2009 01:24:51",
"04.10.2009 01:24:53", 
"04.10.2009 01:24:54", "04.10.2009 01:25:06", "04.10.2009 01:25:07", 
"04.10.2009 01:26:07", "04.10.2009 01:26:27", "04.10.2009 01:27:23", 
"04.10.2009 01:27:30", "04.10.2009 01:27:32", "04.10.2009 01:27:34"
), col1 = c("M017", "M018", "M051", "<NA>", "<NA>", "<NA>", "<NA>", 
"<NA>", "<NA>", "M017", "M051"), col2 = c("<NA>", "<NA>", "<NA>", 
"M016", "M015", "M017", "M017", "M017", "M017", "<NA>", "<NA>"
), col3 = c("<NA>", "<NA>", "<NA>", "<NA>", "<NA>", "<NA>", "<NA>", 
"<NA>", "<NA>", "<NA>", "<NA>"), col4 = c(NA, NA, NA, NA, NA, 
NA, NA, NA, NA, NA, NA)), .Names = c("datetime", "col1", "col2", 
"col3", "col4"), class = "data.frame", row.names = c("1", "2", 
"3", "4", "5", "6", "7", "8", "9", "10", "11"))

Construct pandas DataFrame from list of tuples of (row,col,values)

You can pivot your DataFrame after creating:

>>> df = pd.DataFrame(data)
>>> df.pivot(index=0, columns=1, values=2)
# avg DataFrame
1      c1     c2
r1  avg11  avg12
r2  avg21  avg22
>>> df.pivot(index=0, columns=1, values=3)
# stdev DataFrame
1        c1       c2
r1  stdev11  stdev12
r2  stdev21  stdev22

Python: Remove division decimal

When a number as a decimal it is usually a float in Python.

If you want to remove the decimal and keep it an integer (int). You can call the int() method on it like so...

>>> int(2.0)

However, int rounds down so...

>>> int(2.9)

If you want to round to the nearest integer you can use round:

>>> round(2.9)
>>> round(2.4)

And then call int() on that:

>>> int(round(2.9))
>>> int(round(2.4))

How to avoid mysql 'Deadlock found when trying to get lock; try restarting transaction'

cron is dangerous. If one instance of cron fails to finish before the next is due, they are likely to fight each other.

It would be better to have a continuously running job that would delete some rows, sleep some, then repeat.

Also, INDEX(datetime) is very important for avoiding deadlocks.

But, if the datetime test includes more than, say, 20% of the table, the DELETE will do a table scan. Smaller chunks deleted more often is a workaround.

Another reason for going with smaller chunks is to lock fewer rows.

Bottom line:

  • INDEX(datetime)
  • Continually running task -- delete, sleep a minute, repeat.
  • To make sure that the above task has not died, have a cron job whose sole purpose is to restart it upon failure.

Other deletion techniques:

Best way to center a <div> on a page vertically and horizontally?

2018 way using CSS Grid:

    display: grid;
    place-items: center center;

Check for browser support, Caniuse suggests it works from Chrome 57, FF 52, Opera 44, Safari 10.1, Edge 16. I didn't check myself.

See snippet below:

    display: grid;
    place-items: center center;
    /*place-items is a shorthand for align-items and justify-items*/
    height: 200px;
    border: 1px solid black;
    background: gainsboro;

    background: white;
<div class="parent">
    <div class="child">Centered!</div>

Android lollipop change navigation bar color

It can be done inside styles.xml using

<item name="android:navigationBarColor">@color/theme_color</item>


window.setNavigationBarColor(@ColorInt int color)

Note that the method was introduced in Android Lollipop and won't work on API version < 21.

The second method (works on KitKat) is to set windowTranslucentNavigation to true in the manifest and place a colored view beneath the navigation bar.

What is the Record type in typescript?

  1. Can someone give a simple definition of what Record is?

A Record<K, T> is an object type whose property keys are K and whose property values are T. That is, keyof Record<K, T> is equivalent to K, and Record<K, T>[K] is (basically) equivalent to T.

  1. Is Record<K,T> merely a way of saying "all properties on this object will have type T"? Probably not all objects, since K has some purpose...

As you note, K has a purpose... to limit the property keys to particular values. If you want to accept all possible string-valued keys, you could do something like Record<string, T>, but the idiomatic way of doing that is to use an index signature like { [k: string]: T }.

  1. Does the K generic forbid additional keys on the object that are not K, or does it allow them and just indicate that their properties are not transformed to T?

It doesn't exactly "forbid" additional keys: after all, a value is generally allowed to have properties not explicitly mentioned in its type... but it wouldn't recognize that such properties exist:

declare const x: Record<"a", string>;
x.b; // error, Property 'b' does not exist on type 'Record<"a", string>'

and it would treat them as excess properties which are sometimes rejected:

declare function acceptR(x: Record<"a", string>): void;
acceptR({a: "hey", b: "you"}); // error, Object literal may only specify known properties

and sometimes accepted:

const y = {a: "hey", b: "you"};
acceptR(y); // okay
  1. With the given example:

    type ThreeStringProps = Record<'prop1' | 'prop2' | 'prop3', string>

    Is it exactly the same as this?:

    type ThreeStringProps = {prop1: string, prop2: string, prop3: string}


Hope that helps. Good luck!

how to create 100% vertical line in css

When I tested this, I tried using the position property and it worked perfectly.


<div class="main">
 <div class="body">
 //add content here


 position: relative;

 position: absolute;
 height: 100%;

Manually highlight selected text in Notepad++

To highlight a block of code in Notepad++, please do the following steps

  1. Select the required text.
  2. Right click to display the context menu
  3. Choose Style token and select any of the five choices available ( styles from Using 1st style to using 5th style). Each is of different colors.If you want yellow color choose using 3rd style.

If you want to create your own style you can use Style Configurator under Settings menu.

Component is not part of any NgModule or the module has not been imported into your module

I ran into this same issue and none of what I was seeing here was working. If you are listing your Component in the app-routing.module issue you may have run into the same problem I was having.


import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';
import { NavbarComponent } from './navbar/navbar.component';
import { TopbarComponent } from './topbar/topbar.component';
import { FooterbarComponent } from './footerbar/footerbar.component';
import { MRDBGlobalConstants } from './shared/';
import {AppRoutingModule} from './app.routing';
import {HomeModule} from './Home/home.module';
// import HomeComponent here

  declarations: [
    // add HomeComponent here
  imports: [
    HomeModule  // remove this

  providers: [MRDBGlobalConstants],
  bootstrap: [AppComponent]
export class AppModule { }


export * from './';


import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './components';

const routes: Routes = [
    { path: 'app/home', component: HomeComponent },
    { path: '', redirectTo: 'app/home', pathMatch: 'full' },
    { path: '**', redirectTo: 'app/home' }

    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
export class AppRoutingModule { }


import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
// import { HomeComponent } from './home.component'; This would cause app to break
import { HomeComponent } from './';
  imports: [
  exports: [HomeComponent],
  declarations: [HomeComponent]
export class HomeModule { }

I won't claim to understand exactly why this is the case, but when using indexing to export components (and I would assume the same for services, etc.), when referencing the same component in separate modules you need to import them from the same file, in this case the index, in order to avoid this issue.

How can I change column types in Spark SQL's DataFrame?

You can use below code.

df.withColumn("year", df("year").cast(IntegerType))

Which will convert year column to IntegerType column.

td widths, not working?

This problem is quite easily solved using min-width and max-width within a css rule.


    <td class="name">Peter</td>
    <td class="hobby">Photography</td>
    <td class="comment">A long comment about something...</td>


.name {
  max-width: 80px;
  min-width: 80px;

This will force the first column to be 80px wide. Usually I only use max-width without min-width to reign in text that is very occasionally too long from creating a table that has a super wide column that is mostly empty. The OP's question was about setting to a fixed width though, hence both rules together. On many browsers width:80px; in CSS is ignored for table columns. Setting the width within the HTML does work, but is not the way you should do things.

I would recommend using min and max width rules, and not set them the same but rather set a range. This way the table can do it's thing, but you can give it some hints on what to do with overly long content.

If I want to keep the text from wrapping and increasing the height of a row - but still make it possible for a user to see the full text, I use white-space: nowrap; on the main rule, then apply a hover rule that removes the width and nowrap rules so that the user can see the full content when they over their mouse over it. Something like this:


.name {
  max-width: 80px;
  white-space: nowrap;
  overflow: hidden;
.name:hover {
  max-width: none;
  white-space: normal;

It just depends on exactly what you are trying to achieve. I hope this helps someone. PS As an aside, for iOS there is a fix for hover not working - see CSS Hover Not Working on iOS Safari and Chrome

How does Java import work?

javac (or java during runtime) looks for the classes being imported in the classpath. If they are not there in the classpath then classnotfound exceptions are thrown.

classpath is just like the path variable in a shell, which is used by the shell to find a command or executable.

Entire directories or individual jar files can be put in the classpath. Also, yes a classpath can perhaps include a path which is not local but is somewhere on the internet. Please read more about classpath to resolve your doubts.

Hexadecimal To Decimal in Shell Script

I have this handy script on my $PATH to filter 0x1337-like; 1337; or "0x1337" lines of input into decimal strings (expanded for clarity):

#!/usr/bin/env bash

while read data; do
  withoutQuotes=`echo ${data} | sed s/\"//g`
  without0x=`echo ${withoutQuotes} | sed s/0x//g`
  echo $((16#${clean}))

remove inner shadow of text input

None of the solution are working currently. Here is my solution. You can add prefixes.

box-shadow: inset 0px 0px 0px 0px red;

Is a LINQ statement faster than a 'foreach' loop?

I was interested in this question, so I did a test just now. Using .NET Framework 4.5.2 on an Intel(R) Core(TM) i3-2328M CPU @ 2.20GHz, 2200 Mhz, 2 Core(s) with 8GB ram running Microsoft Windows 7 Ultimate.

It looks like LINQ might be faster than for each loop. Here are the results I got:

Exists = True
Time   = 174
Exists = True
Time   = 149

It would be interesting if some of you could copy & paste this code in a console app and test as well. Before testing with an object (Employee) I tried the same test with integers. LINQ was faster there as well.

public class Program
    public class Employee
        public int id;
        public string name;
        public string lastname;
        public DateTime dateOfBirth;

        public Employee(int id,string name,string lastname,DateTime dateOfBirth)
   = id;
   = name;
            this.lastname = lastname;
            this.dateOfBirth = dateOfBirth;


    public static void Main() => StartObjTest();

    #region object test

    public static void StartObjTest()
        List<Employee> items = new List<Employee>();

        for (int i = 0; i < 10000000; i++)
            items.Add(new Employee(i,"name" + i,"lastname" + i,DateTime.Today));

        Test3(items, items.Count-100);
        Test4(items, items.Count - 100);


    public static void Test3(List<Employee> items, int idToCheck)

        Stopwatch s = new Stopwatch();

        bool exists = false;
        foreach (var item in items)
            if ( == idToCheck)
                exists = true;

        Console.WriteLine("Exists=" + exists);
        Console.WriteLine("Time=" + s.ElapsedMilliseconds);


    public static void Test4(List<Employee> items, int idToCheck)

        Stopwatch s = new Stopwatch();

        bool exists = items.Exists(e => == idToCheck);

        Console.WriteLine("Exists=" + exists);
        Console.WriteLine("Time=" + s.ElapsedMilliseconds);



    #region int test
    public static void StartIntTest()
        List<int> items = new List<int>();

        for (int i = 0; i < 10000000; i++)

        Test1(items, -100);
        Test2(items, -100);


    public static void Test1(List<int> items,int itemToCheck)

        Stopwatch s = new Stopwatch();

        bool exists = false;
        foreach (var item in items)
            if (item == itemToCheck)
                exists = true;

        Console.WriteLine("Exists=" + exists);
        Console.WriteLine("Time=" + s.ElapsedMilliseconds);


    public static void Test2(List<int> items, int itemToCheck)

        Stopwatch s = new Stopwatch();

        bool exists = items.Contains(itemToCheck);

        Console.WriteLine("Exists=" + exists);
        Console.WriteLine("Time=" + s.ElapsedMilliseconds);




How to parse XML and count instances of a particular node attribute?

#If the xml is in the form of a string as shown below then
from lxml  import etree, objectify
'''sample xml as a string with a name space {}'''
message =b'<?xml version="1.0" encoding="UTF-8"?>\r\n<pa:Process xmlns:pa="">\r\n\t<pa:firsttag>SAMPLE</pa:firsttag></pa:Process>\r\n'  # this is a sample xml which is a string

print('************message coversion and parsing starts*************')

message=message.replace('<?xml version="1.0" encoding="UTF-8"?>\r\n','') #replace is used to remove unwanted strings from the 'message'
print (message)

print ('******Parsing starts*************')
parser = etree.XMLParser(remove_blank_text=True) #the name space is removed here
root = etree.fromstring(message, parser) #parsing of xml happens here
print ('******Parsing completed************')

for child in root: # parsed xml is iterated using a for loop and values are stored in a dictionary
    print('****Derving from xml tree*****')
    if child.tag =="{}firsttag":

### output
'''************message coversion and parsing starts*************
<pa:Process xmlns:pa="">

******Parsing starts*************
******Parsing completed************
{}firsttag SAMPLE
****Derving from xml tree*****

Drop all tables command

I had the same problem with SQLite and Android. Here is my Solution:

List<String> tables = new ArrayList<String>();
Cursor cursor = db.rawQuery("SELECT * FROM sqlite_master WHERE type='table';", null);
while (!cursor.isAfterLast()) {
    String tableName = cursor.getString(1);
    if (!tableName.equals("android_metadata") &&

for(String tableName:tables) {
    db.execSQL("DROP TABLE IF EXISTS " + tableName);

How to create a trie in Python

from collections import defaultdict

Define Trie:

_trie = lambda: defaultdict(_trie)

Create Trie:

trie = _trie()
for s in ["cat", "bat", "rat", "cam"]:
    curr = trie
    for c in s:
        curr = curr[c]


def word_exist(trie, word):
    curr = trie
    for w in word:
        if w not in curr:
            return False
        curr = curr[w]
    return '_end' in curr


print(word_exist(trie, 'cam'))

How to fix a Div to top of page with CSS only

You can do something like this:

<head><title>My Glossary</title></head>
<body style="margin:0px;">
        <div id="top" style="position:fixed;background:white;width:100%;">
            <a href="#A">A</a> |
             <a href="#B">B</a> |
            <a href="#Z">Z</a>

        <div id="term-defs" style="padding-top:1em;">
               <span id="A"></span>
               <dd>This is the sound made by a fool</dd>
               <!-- and so on ... ->

It's the position:fixed that's most important, because it takes the top div from the normal page flow and fixes it at it's pre-determined position. It's also important to use the padding-top:1em because otherwise the term-defs div would start right under the top div. The background and width are there to cover the contents of the term-defs div as they scroll under the top div.

Hope this helps.

Saving an image in OpenCV

hopefully this will save images form your webcam

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>

using namespace std;
using namespace cv;

int main()
   VideoCapture cap(0);

   Mat save_img;

   cap >> save_img;

   char Esc = 0;

   while (Esc != 27 && cap.isOpened()) {        
    bool Frame =;        
    if (!Frame || save_img.empty()) {       
        cout << "error: frame not read from webcam\n";      
    namedWindow("save_img", CV_WINDOW_NORMAL);  
    imshow("imgOriginal", save_img);            
    Esc = waitKey(1);

CSS transition fade in

OK, first of all I'm not sure how it works when you create a div using (document.createElement('div')), so I might be wrong now, but wouldn't it be possible to use the :target pseudo class selector for this?

If you look at the code below, you can se I've used a link to target the div, but in your case it might be possible to target #new from the script instead and that way make the div fade in without user interaction, or am I thinking wrong?

Here's the code for my example:


<a href="#new">Click</a> 
<div id="new">
    Fade in ... 


#new {
    width: 100px;
    height: 100px;
    border: 1px solid #000000;
    opacity: 0;    

#new:target {
    -webkit-transition: opacity 2.0s ease-in;
       -moz-transition: opacity 2.0s ease-in;
         -o-transition: opacity 2.0s ease-in;
                                  opacity: 1;

... and here's a jsFiddle

How to get everything after last slash in a URL?

Here's a more general, regex way of doing this:

    re.sub(r'^.+/([^/]+)$', r'\1', url)

How to use a decimal range() step value?

Similar to R's seq function, this one returns a sequence in any order given the correct step value. The last value is equal to the stop value.

def seq(start, stop, step=1):
    n = int(round((stop - start)/float(step)))
    if n > 1:
        return([start + step*i for i in range(n+1)])
    elif n == 1:


seq(1, 5, 0.5)

[1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0]

seq(10, 0, -1)

[10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

seq(10, 0, -2)

[10, 8, 6, 4, 2, 0]

seq(1, 1)

[ 1 ]

SQL providerName in web.config

System.Data.SqlClient is the .NET Framework Data Provider for SQL Server. ie .NET library for SQL Server.

I don't know where providerName=SqlServer comes from. Could you be getting this confused with the provider keyword in your connection string? (I know I was :) )

In the web.config you should have the System.Data.SqlClient as the value of the providerName attribute. It is the .NET Framework Data Provider you are using.

      connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" 


OperationalError: database is locked

In my case, I had not saved a database operation I performed within the SQLite Browser. Saving it solved the issue.

How to use Comparator in Java to sort

Use People implements Comparable<People> instead; this defines the natural ordering for People.

A Comparator<People> can also be defined in addition, but People implements Comparator<People> is not the right way of doing things.

The two overloads for Collections.sort are different:

  • <T extends Comparable<? super T>> void sort(List<T> list)
    • Sorts Comparable objects using their natural ordering
  • <T> void sort(List<T> list, Comparator<? super T> c)
    • Sorts whatever using a compatible Comparator

You're confusing the two by trying to sort a Comparator (which is again why it doesn't make sense that Person implements Comparator<Person>). Again, to use Collections.sort, you need one of these to be true:

  • The type must be Comparable (use the 1-arg sort)
  • A Comparator for the type must be provided (use the 2-args sort)

Related questions

Also, do not use raw types in new code. Raw types are unsafe, and it's provided only for compatibility.

That is, instead of this:

ArrayList peps = new ArrayList(); // BAD!!! No generic safety!

you should've used the typesafe generic declaration like this:

List<People> peps = new ArrayList<People>(); // GOOD!!!

You will then find that your code doesn't even compile!! That would be a good thing, because there IS something wrong with the code (Person does not implements Comparable<Person>), but because you used raw type, the compiler didn't check for this, and instead you get a ClassCastException at run-time!!!

This should convince you to always use typesafe generic types in new code. Always.

See also

Make Div overlay ENTIRE page (not just viewport)?

I had quite a bit of trouble as I didn't want to FIX the overlay in place as I wanted the info inside the overlay to be scrollable over the text. I used:

<html style="height=100%">
   <body style="position:relative">
      <div id="my-awesome-overlay" 
                  display: block">
           [epic content here]

Of course the div in the middle needs some content and probably a transparent grey background but I'm sure you get the gist!

Create PDF from a list of images

Install FPDF for Python:

pip install fpdf

Now you can use the same logic:

from fpdf import FPDF
pdf = FPDF()
# imagelist is the list with all image filenames
for image in imagelist:
pdf.output("yourfile.pdf", "F")

You can find more info at the tutorial page or the official documentation.

Check if string contains a value in array

Simple str_replace with count parameter would work here:

$count = 0;
str_replace($owned_urls, '', $string, $count);
// if replace is successful means the array value is present(Match Found).
if ($count > 0) {
  echo "One of Array value is present in the string.";

More Info -

Using variables inside a bash heredoc

Don't use quotes with <<EOF:

sudo tee "/path/to/outfile" > /dev/null <<EOF
Some text that contains my $var

Variable expansion is the default behavior inside of here-docs. You disable that behavior by quoting the label (with single or double quotes).

Formatting dates on X axis in ggplot2

To show months as Jan 2017 Feb 2017 etc:

scale_x_date(date_breaks = "1 month", date_labels =  "%b %Y") 

Angle the dates if they take up too much space:

theme(axis.text.x=element_text(angle=60, hjust=1))

Find rows that have the same value on a column in MySQL

First part of accepted answer does not work for MSSQL.
This worked for me:

select email, COUNT(*) as C from table 
group by email having COUNT(*) >1 order by C desc

How to send HTML email using linux command line

Command Line

Create a file named tmp.html with the following contents:

<b>my bold message</b>

Next, paste the following into the command line (parentheses and all):

  echo To: [email protected]
  echo From: [email protected]
  echo "Content-Type: text/html; "
  echo Subject: a logfile
  cat tmp.html
) | sendmail -t

The mail will be dispatched including a bold message due to the <b> element.

Shell Script

As a script, save the following as

ARG_EMAIL_TO="[email protected]"
ARG_EMAIL_FROM="Your Name <[email protected]>"

  echo "To: ${ARG_EMAIL_TO}"
  echo "From: ${ARG_EMAIL_FROM}"
  echo "Subject: ${ARG_EMAIL_SUBJECT}"
  echo "Mime-Version: 1.0"
  echo "Content-Type: text/html; charset='utf-8'"
  cat contents.html
) | sendmail -t

Create a file named contents.html in the same directory as the script that resembles:

<html><head><title>Subject Line</title></head>
  <p style='color:red'>HTML Content</p>

Run When the email arrives, the HTML Content text will appear red.


Continuous Integration vs. Continuous Delivery vs. Continuous Deployment

lets keep it short :

CI: A software development practice where members of a team integrate their work at least daily. Each integration is verified by automated build (include tests)to detect error as quick as possible. CD: CD Builds on CI, where you build software in such a way that the software can be released to production at any time.

Is there a Google Sheets formula to put the name of the sheet into a cell?

If you reference the sheet from another sheet, you can get the sheet name using the CELL function. You can then use regex to extract out the sheet name.

=REGEXREPLACE(CELL("address",'SHEET NAME'!A1),"'?([^']+)'?!.*","$1")

update: The formula will automatically update 'SHEET NAME' with future changes, but you will need to reference a cell (such as A1) on that sheet when the formula is originally entered.

'node' is not recognized as an internal or external command

I set the NODEJS variable in the system control panel but the only thing that worked to set the path was to do it from command line as administrator.


Another trick is that once you set the path you must close the console and open a new one for the new path to be taken into account.

However for the regular user to be able to use node I had to run set path again not as admin and restart the computer

How to change column datatype in SQL database without losing data

You can easily do this using the following command. Any value of 0 will be turned into a 0 (BIT = false), anything else will be turned into 1 (BIT = true).

ALTER TABLE dbo.YourTable
   ALTER COLUMN YourColumnName BIT

The other option would be to create a new column of type BIT, fill it from the old column, and once you're done, drop the old column and rename the new one to the old name. That way, if something during the conversion goes wrong, you can always go back since you still have all the data..

How to do a less than or equal to filter in Django queryset?

Less than or equal:


Greater than or equal:


Likewise, lt for less than and gt for greater than. You can find them all in the documentation.

Jquery mouseenter() vs mouseover()

This example demonstrates the difference between the mousemove, mouseenter and mouseover events:


<div onmousemove="myMoveFunction()">
    <p>onmousemove: <br> <span id="demo">Mouse over me!</span></p>

<div onmouseenter="myEnterFunction()">
    <p>onmouseenter: <br> <span id="demo2">Mouse over me!</span></p>

<div onmouseover="myOverFunction()">
    <p>onmouseover: <br> <span id="demo3">Mouse over me!</span></p>


div {
    width: 200px;
    height: 100px;
    border: 1px solid black;
    margin: 10px;
    float: left;
    padding: 30px;
    text-align: center;
    background-color: lightgray;

p {
    background-color: white;
    height: 50px;

p span {
    background-color: #86fcd4;
    padding: 0 20px;


var x = 0;
var y = 0;
var z = 0;

function myMoveFunction() {
    document.getElementById("demo").innerHTML = z += 1;

function myEnterFunction() {
    document.getElementById("demo2").innerHTML = x += 1;

function myOverFunction() {
    document.getElementById("demo3").innerHTML = y += 1;
  • onmousemove : occurs every time the mouse pointer is moved over the div element.
  • onmouseenter : only occurs when the mouse pointer enters the div element.
  • onmouseover : occurs when the mouse pointer enters the div element, and its child elements (p and span).

How do I calculate percentiles with python/numpy?

Here's how to do it without numpy, using only python to calculate the percentile.

import math

def percentile(data, percentile):
    size = len(data)
    return sorted(data)[int(math.ceil((size * percentile) / 100)) - 1]

p5 = percentile(mylist, 5)
p25 = percentile(mylist, 25)
p50 = percentile(mylist, 50)
p75 = percentile(mylist, 75)
p95 = percentile(mylist, 95)

Returning http status code from Web Api controller

An update to @Aliostads answer using the more moden IHttpActionResult introduced in Web API 2.

public class TryController : ApiController
    public IHttpActionResult GetUser(int userId, DateTime lastModifiedAtClient)
        var user = new DataEntities().Users.First(p => p.Id == userId);
        if (user.LastModified <= lastModifiedAtClient)
            return StatusCode(HttpStatusCode.NotModified);
            // If you would like to return a Http Status code with any object instead:
            // return Content(HttpStatusCode.InternalServerError, "My Message");
        return Ok(user);

What does it mean to "program to an interface"?

An interface is like a contract, where you want your implementation class to implement methods written in the contract (interface). Since Java does not provide multiple inheritance, "programming to interface" is a good way to achieve multiple inheritance.

If you have a class A that is already extending some other class B, but you want that class A to also follow certain guidelines or implement a certain contract, then you can do so by the "programming to interface" strategy.

Remove all occurrences of a value from a list?

I believe this is probably faster than any other way if you don't care about the lists order, if you do take care about the final order store the indexes from the original and resort by that.

ones_last_index = category_ids.count('1')
del category_ids[0:ones_last_index]

Python's time.clock() vs. time.time() accuracy?

I use this code to compare 2 methods .My OS is windows 8 , processor core i5 , RAM 4GB

import time

def t_time():
    return (time.time()-start)

def t_clock():
    return (time.clock()-start)


for i in range(1,100):
    counter_time += t_time()

    for i in range(1,100):
        counter_clock += t_clock()

print "time() =",counter_time/100
print "clock() =",counter_clock/100


time() = 0.0993799996376

clock() = 0.0993572257367

How to overcome "datetime.datetime not JSON serializable"?

Actually it is quite simple. If you need to often serialize dates, then work with them as strings. You can easily convert them back as datetime objects if needed.

If you need to work mostly as datetime objects, then convert them as strings before serializing.

import json, datetime

date = str(
"2018-12-01 15:44:34.409085"
<class 'str'>

datetime_obj = datetime.datetime.strptime(date, '%Y-%m-%d %H:%M:%S.%f')
2018-12-01 15:44:34.409085
<class 'datetime.datetime'>

As you can see, the output is the same in both cases. Only the type is different.

Forward declaration of a typedef in C++

Because to declare a type, its size needs to be known. You can forward declare a pointer to the type, or typedef a pointer to the type.

If you really want to, you can use the pimpl idiom to keep the includes down. But if you want to use a type, rather than a pointer, the compiler has to know its size.

Edit: j_random_hacker adds an important qualification to this answer, basically that the size needs to be know to use the type, but a forward declaration can be made if we only need to know the type exists, in order to create pointers or references to the type. Since the OP didn't show code, but complained it wouldn't compile, I assumed (probably correctly) that the OP was trying to use the type, not just refer to it.

SELECT from nothing?

In Oracle:

SELECT 'Hello world' FROM dual

Dual equivalent in SQL Server:

SELECT 'Hello world' 

Node.js https pem error: routines:PEM_read_bio:no start line

If you are using windows, you should make sure that the certificate file csr.pem and key.pem don't have unix-style line endings. Openssl will generate the key files with unix style line endings. You can convert these files to dos format using a utility like unix2dos or a text editor like notepad++

Text on image mouseover?

And if you come from even further in the future you can use the title property on div tags now to provide tooltips:

<div title="Tooltip text">Hover over me</div>

Let's just hope you're not using a browser from the past.

<div title="Tooltip text">Hover over me</div>

PHP foreach change original array values

Use foreach($fields as &$field){ - so you will work with the original array.

Here is more about passing by reference.

Blocks and yields in Ruby

Yields, to put it simply, allow the method you create to take and call blocks. The yield keyword specifically is the spot where the 'stuff' in the block will be performed.

How do I register a DLL file on Windows 7 64-bit?

Everything here was failing as wrong path. Then I remembered a trick from the old Win95 days. Open the program folder where the .dll resides, open C:/Windows/System32 scroll down to regsvr32 and drag and drop the dll from the program folder onto rgsrver32. Boom,done.

Horizontal scroll on overflow of table

On a responsive site for mobiles the whole thing has to be positioned absolute on a relative div. And fixed height. Media Query set for relevance.

@media only screen and (max-width: 480px){_x000D_

Javascript: How to generate formatted easy-to-read JSON straight from an object?

JSON.stringify takes more optional arguments.


 JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, 4); // Indented 4 spaces
 JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, "\t"); // Indented with tab


How can I beautify JSON programmatically?

Should work in modern browsers, and it is included in json2.js if you need a fallback for browsers that don't support the JSON helper functions. For display purposes, put the output in a <pre> tag to get newlines to show.

How do I push to GitHub under a different username?

If under Windows and user Git for Windows and the manager for managing the credentials (aka Git-Credential-Manager-for-Windows Link) the problem is that there is no easy way to switch amongst users when pushing to GitHub over https using OAuth tokens.

The reason is that the token is stored as:

  • Internet Address: git:
  • Username: Personal Access Token
  • Password: OAuth_Token

Variations of the URL in Internet Address don't work, for example:

The solution: namespaces. This is found in the details for the configuration of the Git-Credential-Manager-for-Windows:

Quoting from it:


Sets the namespace for stored credentials.

By default the GCM uses the 'git' namespace for all stored credentials, setting this configuration value allows for control of the namespace used globally, or per host.

git config --global credential.namespace name

Now, store your credential in the Windows Credential Manager as:

  • Internet Address: git.username:
  • Username: Personal Access Token
  • Password: OAuth_Token

Notice that we have changed: git -> git.username (where you change username to your actual username or for the sake of it, to whatever you may want as unique identifier)

Now, inside the repository where you want to use the specific entry, execute:

git config credential.namespace git.username

(Again ... replace username with your desired value)

Your .git/config will now contain:

    namespace = git.username

Et voilá! The right credential will be pulled from the Windows Credential Store.

This, of course, doesn't change which user/e-mail is pushing. For that you have to configure the usual and

Search all the occurrences of a string in the entire project in Android Studio

In Android 3.6 on a Mac if you want to export the results to a text file then do the following

Command+Shift+F then enter the text you want to search

Then on Bottom Right click on "Open In Find Window"

Then Right Click On Found Occurrences

Then Export To Text File

Once in text file you can find and replace to remove, sort lines etc... please see screenshots for assistance.

enter image description here

enter image description here

Align printf output in Java

Format specifications for printf and printf-like methods take an optional width parameter.

System.out.printf( "%10d. %25s $%25.2f\n",
                   i + 1, BOOK_TYPE[i], COST[i] );

Adjust widths to desired values.

Java integer to byte array

If you're using apache-commons

public static byte[] toByteArray(int value) {
    byte result[] = new byte[4];
    return Conversion.intToByteArray(value, 0, result, 0, 4);

handling dbnull data in

For the rows containing strings, I can convert them to strings as in changing

tmpStr = nameItem("lastname") + " " + nameItem("initials")


tmpStr = myItem("lastname").toString + " " + myItem("intials").toString

For the comparison in the if statement myItem("sID")=sID, it needs to be change to


Then the code will run without any runtime errors due to vbNull data.

Difference of keywords 'typename' and 'class' in templates?

  1. No difference
  2. Template type parameter Container is itself a template with two type parameters.

How do you overcome the HTML form nesting limitation?

My solution is to have the buttons call JS functions which write and then submit forms outwith the main form

function removeMe(A, B){
        document.write('<form name="removeForm" method="POST" action="Delete.php">');
        document.write('<input type="hidden" name="customerID" value="' + A + '">');
        document.write('<input type="hidden" name="productID" value="' + B + '">');
function insertMe(A, B){
        document.write('<form name="insertForm" method="POST" action="Insert.php">');
        document.write('<input type="hidden" name="customerID" value="' + A + '">');
        document.write('<input type="hidden" name="productID" value="' + B + '">');

<form method="POST" action="main_form_purpose_page.php">

<input type="button" name="remove" Value="Remove" onclick="removeMe('$customerID','$productID')">
<input type="button" name="insert" Value="Insert" onclick="insertMe('$customerID','$productID')">

<input type="submit" name="submit" value="Submit">

Android canvas draw rectangle

Try paint.setStyle(Paint.Style.STROKE)?

How to hide the title bar for an Activity in XML with existing custom theme

I now did the following.

I declared a style inheriting everything from my general style and then disabling the titleBar.

<style name="generalnotitle" parent="general">
    <item name="android:windowNoTitle">true</item>

Now I can set this style to every Activity in which I want to hide the title bar overwriting the application wide style and inheriting all the other style informations, therefor no duplication in the style code.

To apply the style to a particular Activity, open AndroidManifest.xml and add the following attribute to the activity tag;


FirstOrDefault: Default value other than null

Actually, I use two approaches to avoid NullReferenceException when I'm working with collections:

public class Foo
    public string Bar{get; set;}
void Main()
    var list = new List<Foo>();
    //before C# 6.0
    string barCSharp5 = list.DefaultIfEmpty(new Foo()).FirstOrDefault().Bar;
    //C# 6.0 or later
    var barCSharp6 = list.FirstOrDefault()?.Bar;

For C# 6.0 or later:

Use ?. or ?[ to test if is null before perform a member access Null-conditional Operators documentation

Example: var barCSharp6 = list.FirstOrDefault()?.Bar;

C# older version:

Use DefaultIfEmpty() to retrieve a default value if the sequence is empty.MSDN Documentation

Example: string barCSharp5 = list.DefaultIfEmpty(new Foo()).FirstOrDefault().Bar;

pandas resample documentation

There's more to it than this, but you're probably looking for this list:

B   business day frequency
C   custom business day frequency (experimental)
D   calendar day frequency
W   weekly frequency
M   month end frequency
BM  business month end frequency
MS  month start frequency
BMS business month start frequency
Q   quarter end frequency
BQ  business quarter endfrequency
QS  quarter start frequency
BQS business quarter start frequency
A   year end frequency
BA  business year end frequency
AS  year start frequency
BAS business year start frequency
H   hourly frequency
T   minutely frequency
S   secondly frequency
L   milliseconds
U   microseconds


Spring Boot yaml configuration for a list of strings

From the spring boot docs

YAML lists are represented as property keys with [index] dereferencers, for example this YAML:


Would be transformed into these properties:


To bind to properties like that using the Spring DataBinder utilities (which is what @ConfigurationProperties does) you need to have a property in the target bean of type java.util.List and you either need to provide a setter, or initialize it with a mutable value, e.g. this will bind to the properties above. Here is what the question's code would look like.

public class Filenames {

    private List<String> ignoredFilenames = new ArrayList<String>();

    public List<String> getFilenames() {
        return this.ignoredFilenames;

Java BigDecimal: Round to the nearest whole value

I don't think you can round it like that in a single command. Try

    ArrayList<BigDecimal> list = new ArrayList<BigDecimal>();
    list.add(new BigDecimal("100.12"));
    list.add(new BigDecimal("100.44"));
    list.add(new BigDecimal("100.50"));
    list.add(new BigDecimal("100.75"));

    for (BigDecimal bd : list){
        System.out.println(bd+" -> "+bd.setScale(0,RoundingMode.HALF_UP).setScale(2));

100.12 -> 100.00
100.44 -> 100.00
100.50 -> 101.00
100.75 -> 101.00

I tested for the rest of your examples and it returns the wanted values, but I don't guarantee its correctness.

Invalid syntax when using "print"?

That is because in Python 3, they have replaced the print statement with the print function.

The syntax is now more or less the same as before, but it requires parens:

From the "what's new in python 3" docs:

Old: print "The answer is", 2*2
New: print("The answer is", 2*2)

Old: print x,           # Trailing comma suppresses newline
New: print(x, end=" ")  # Appends a space instead of a newline

Old: print              # Prints a newline
New: print()            # You must call the function!

Old: print >>sys.stderr, "fatal error"
New: print("fatal error", file=sys.stderr)

Old: print (x, y)       # prints repr((x, y))
New: print((x, y))      # Not the same as print(x, y)!

Align text to the bottom of a div

Flex Solution

It is perfectly fine if you want to go with the display: table-cell solution. But instead of hacking it out, we have a better way to accomplish the same using display: flex;. flex is something which has a decent support.

.wrap {_x000D_
  height: 200px;_x000D_
  width: 200px;_x000D_
  border: 1px solid #aaa;_x000D_
  margin: 10px;_x000D_
  display: flex;_x000D_
.wrap span {_x000D_
  align-self: flex-end;_x000D_
<div class="wrap">_x000D_
  <span>Align me to the bottom</span>_x000D_

In the above example, we first set the parent element to display: flex; and later, we use align-self to flex-end. This helps you push the item to the end of the flex parent.

Old Solution (Valid if you are not willing to use flex)

If you want to align the text to the bottom, you don't have to write so many properties for that, using display: table-cell; with vertical-align: bottom; is enough

div {_x000D_
  display: table-cell;_x000D_
  vertical-align: bottom;_x000D_
  border: 1px solid #f00;_x000D_
  height: 100px;_x000D_
  width: 100px;_x000D_

(Or JSFiddle)

Prevent content from expanding grid items

By default, a grid item cannot be smaller than the size of its content.

Grid items have an initial size of min-width: auto and min-height: auto.

You can override this behavior by setting grid items to min-width: 0, min-height: 0 or overflow with any value other than visible.

From the spec:

6.6. Automatic Minimum Size of Grid Items

To provide a more reasonable default minimum size for grid items, this specification defines that the auto value of min-width / min-height also applies an automatic minimum size in the specified axis to grid items whose overflow is visible. (The effect is analogous to the automatic minimum size imposed on flex items.)

Here's a more detailed explanation covering flex items, but it applies to grid items, as well:

This post also covers potential problems with nested containers and known rendering differences among major browsers.

To fix your layout, make these adjustments to your code:

.month-grid {
  display: grid;
  grid-template: repeat(6, 1fr) / repeat(7, 1fr);
  background: #fff;
  grid-gap: 2px;
  min-height: 0;  /* NEW */
  min-width: 0;   /* NEW; needed for Firefox */

.day-item {
  padding: 10px;
  background: #DFE7E7;
  overflow: hidden;  /* NEW */
  min-width: 0;      /* NEW; needed for Firefox */

jsFiddle demo

1fr vs minmax(0, 1fr)

The solution above operates at the grid item level. For a container level solution, see this post:

What steps are needed to stream RTSP from FFmpeg?

You can use FFserver to stream a video using RTSP.

Just change console syntax to something like this:

ffmpeg -i space.mp4 -vcodec libx264 -tune zerolatency -crf 18 http://localhost:1234/feed1.ffm

Create a ffserver.config file (sample) where you declare HTTPPort, RTSPPort and SDP stream. Your config file could look like this (some important stuff might be missing):

HTTPPort 1234
RTSPPort 1235

<Feed feed1.ffm>
        File /tmp/feed1.ffm
        FileMaxSize 2M
        ACL allow

<Stream test1.sdp>
    Feed feed1.ffm
    Format rtp
    VideoCodec libx264
    AVOptionVideo flags +global_header
    AVOptionVideo me_range 16
    AVOptionVideo qdiff 4
    AVOptionVideo qmin 10
    AVOptionVideo qmax 51
    ACL allow

With such setup you can watch the stream with i.e. VLC by typing:


Here is the FFserver documentation.


$protocol = strtolower(substr($_SERVER["SERVER_PROTOCOL"],0,5))=='https'?'https':'http';

$protocol = isset($_SERVER["HTTPS"]) ? 'https' : 'http';

These should both work

Can you nest html forms?

Really not possible... I couldn't nest form tags... However I used this code:


    <div novalidate role="form" method="post" id="fake_form_id_0" data-url="YOUR_POST_URL">

with {% csrf_token %} and stuff

and applied some JS

var url = $(form_id).attr("data-url");

  url: url,
  "type": "POST",
   "data": {
    'csrfmiddlewaretoken': '{{ csrf_token }}',
    'custom-param-attachment': 'value'
  success: function (e, data) {
      if (e.is_valid) {
         DO STUFF

Static Block in Java

Static blocks are used for initializaing the code and will be executed when JVM loads the class.Refer to the below link which gives the detailed explanation.

PostgreSQL Crosstab Query

Install the additional module tablefunc once per database, which provides the function crosstab(). Since Postgres 9.1 you can use CREATE EXTENSION for that:


Improved test case

   section   text
 , status    text
 , ct        integer  -- "count" is a reserved word in standard SQL

  ('A', 'Active', 1), ('A', 'Inactive', 2)
, ('B', 'Active', 4), ('B', 'Inactive', 5)
                    , ('C', 'Inactive', 7);  -- ('C', 'Active') is missing

Simple form - not fit for missing attributes

crosstab(text) with 1 input parameter:

FROM   crosstab(
   'SELECT section, status, ct
    FROM   tbl
    ORDER  BY 1,2'  -- needs to be "ORDER BY 1,2" here
   ) AS ct ("Section" text, "Active" int, "Inactive" int);


 Section | Active | Inactive
 A       |      1 |        2
 B       |      4 |        5
 C       |      7 |           -- !!
  • No need for casting and renaming.
  • Note the incorrect result for C: the value 7 is filled in for the first column. Sometimes, this behavior is desirable, but not for this use case.
  • The simple form is also limited to exactly three columns in the provided input query: row_name, category, value. There is no room for extra columns like in the 2-parameter alternative below.

Safe form

crosstab(text, text) with 2 input parameters:

FROM   crosstab(
   'SELECT section, status, ct
    FROM   tbl
    ORDER  BY 1,2'  -- could also just be "ORDER BY 1" here

  , $$VALUES ('Active'::text), ('Inactive')$$
   ) AS ct ("Section" text, "Active" int, "Inactive" int);


 Section | Active | Inactive
 A       |      1 |        2
 B       |      4 |        5
 C       |        |        7  -- !!
  • Note the correct result for C.

  • The second parameter can be any query that returns one row per attribute matching the order of the column definition at the end. Often you will want to query distinct attributes from the underlying table like this:

    'SELECT DISTINCT attribute FROM tbl ORDER BY 1'

    That's in the manual.

    Since you have to spell out all columns in a column definition list anyway (except for pre-defined crosstabN() variants), it is typically more efficient to provide a short list in a VALUES expression like demonstrated:

    $$VALUES ('Active'::text), ('Inactive')$$)

    Or (not in the manual):

    $$SELECT unnest('{Active,Inactive}'::text[])$$  -- short syntax for long lists
  • I used dollar quoting to make quoting easier.

  • You can even output columns with different data types with crosstab(text, text) - as long as the text representation of the value column is valid input for the target type. This way you might have attributes of different kind and output text, date, numeric etc. for respective attributes. There is a code example at the end of the chapter crosstab(text, text) in the manual.

db<>fiddle here

Advanced examples

\crosstabview in psql

Postgres 9.6 added this meta-command to its default interactive terminal psql. You can run the query you would use as first crosstab() parameter and feed it to \crosstabview (immediately or in the next step). Like:

db=> SELECT section, status, ct FROM tbl \crosstabview

Similar result as above, but it's a representation feature on the client side exclusively. Input rows are treated slightly differently, hence ORDER BY is not required. Details for \crosstabview in the manual. There are more code examples at the bottom of that page.

Related answer on dba.SE by Daniel Vérité (the author of the psql feature):

The previously accepted answer is outdated.

  • The variant of the function crosstab(text, integer) is outdated. The second integer parameter is ignored. I quote the current manual:

    crosstab(text sql, int N) ...

    Obsolete version of crosstab(text). The parameter N is now ignored, since the number of value columns is always determined by the calling query

  • Needless casting and renaming.

  • It fails if a row does not have all attributes. See safe variant with two input parameters above to handle missing attributes properly.

  • ORDER BY is required in the one-parameter form of crosstab(). The manual:

    In practice the SQL query should always specify ORDER BY 1,2 to ensure that the input rows are properly ordered

What's the difference between deadlock and livelock?

Maybe these two examples illustrate you the difference between a deadlock and a livelock:

Java-Example for a deadlock:

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class DeadlockSample {

    private static final Lock lock1 = new ReentrantLock(true);
    private static final Lock lock2 = new ReentrantLock(true);

    public static void main(String[] args) {
        Thread threadA = new Thread(DeadlockSample::doA,"Thread A");
        Thread threadB = new Thread(DeadlockSample::doB,"Thread B");

    public static void doA() {
        System.out.println(Thread.currentThread().getName() + " : waits for lock 1");
        System.out.println(Thread.currentThread().getName() + " : holds lock 1");

        try {
            System.out.println(Thread.currentThread().getName() + " : waits for lock 2");
            System.out.println(Thread.currentThread().getName() + " : holds lock 2");

            try {
                System.out.println(Thread.currentThread().getName() + " : critical section of doA()");
            } finally {
                System.out.println(Thread.currentThread().getName() + " : does not hold lock 2 any longer");
        } finally {
            System.out.println(Thread.currentThread().getName() + " : does not hold lock 1 any longer");

    public static void doB() {
        System.out.println(Thread.currentThread().getName() + " : waits for lock 2");
        System.out.println(Thread.currentThread().getName() + " : holds lock 2");

        try {
            System.out.println(Thread.currentThread().getName() + " : waits for lock 1");
            System.out.println(Thread.currentThread().getName() + " : holds lock 1");

            try {
                System.out.println(Thread.currentThread().getName() + " : critical section of doB()");
            } finally {
                System.out.println(Thread.currentThread().getName() + " : does not hold lock 1 any longer");
        } finally {
            System.out.println(Thread.currentThread().getName() + " : does not hold lock 2 any longer");

Sample output:

Thread A : waits for lock 1
Thread B : waits for lock 2
Thread A : holds lock 1
Thread B : holds lock 2
Thread B : waits for lock 1
Thread A : waits for lock 2

Java-Example for a livelock:

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LivelockSample {

    private static final Lock lock1 = new ReentrantLock(true);
    private static final Lock lock2 = new ReentrantLock(true);

    public static void main(String[] args) {
        Thread threadA = new Thread(LivelockSample::doA, "Thread A");
        Thread threadB = new Thread(LivelockSample::doB, "Thread B");

    public static void doA() {
        try {
            while (!lock1.tryLock()) {
                System.out.println(Thread.currentThread().getName() + " : waits for lock 1");
            System.out.println(Thread.currentThread().getName() + " : holds lock 1");

            try {
                while (!lock2.tryLock()) {
                    System.out.println(Thread.currentThread().getName() + " : waits for lock 2");
                System.out.println(Thread.currentThread().getName() + " : holds lock 2");

                try {
                    System.out.println(Thread.currentThread().getName() + " : critical section of doA()");
                } finally {
                    System.out.println(Thread.currentThread().getName() + " : does not hold lock 2 any longer");
            } finally {
                System.out.println(Thread.currentThread().getName() + " : does not hold lock 1 any longer");
        } catch (InterruptedException e) {
            // can be ignored here for this sample

    public static void doB() {
        try {
            while (!lock2.tryLock()) {
                System.out.println(Thread.currentThread().getName() + " : waits for lock 2");
            System.out.println(Thread.currentThread().getName() + " : holds lock 2");

            try {
                while (!lock1.tryLock()) {
                    System.out.println(Thread.currentThread().getName() + " : waits for lock 1");
                System.out.println(Thread.currentThread().getName() + " : holds lock 1");

                try {
                    System.out.println(Thread.currentThread().getName() + " : critical section of doB()");
                } finally {
                    System.out.println(Thread.currentThread().getName() + " : does not hold lock 1 any longer");
            } finally {
                System.out.println(Thread.currentThread().getName() + " : does not hold lock 2 any longer");
        } catch (InterruptedException e) {
            // can be ignored here for this sample

Sample output:

Thread B : holds lock 2
Thread A : holds lock 1
Thread A : waits for lock 2
Thread B : waits for lock 1
Thread B : waits for lock 1
Thread A : waits for lock 2
Thread A : waits for lock 2
Thread B : waits for lock 1
Thread B : waits for lock 1
Thread A : waits for lock 2
Thread A : waits for lock 2
Thread B : waits for lock 1

Both examples force the threads to aquire the locks in different orders. While the deadlock waits for the other lock, the livelock does not really wait - it desperately tries to acquire the lock without the chance of getting it. Every try consumes CPU cycles.

Is object empty?

EDIT: Note that you should probably use ES5 solution instead of this since ES5 support is widespread these days. It still works for jQuery though.

Easy and cross-browser way is by using jQuery.isEmptyObject:

if ($.isEmptyObject(obj))
    // do something


You need jquery though.

How to get a vCard (.vcf file) into Android contacts from website

AFAIK Android doesn't support vCard files out of the Box at least not until 2.2.

You could use the app vCardIO to read vcf files from your SD card and save to you contacts. So you have to save them on your SD card in the first place and import them afterwards.

vCardIO is also available trough the market.

FormData.append("key", "value") is not working

form data doesn't appear in web browser console

for (var data of formData) {

try this way it will show

Open a facebook link by native Facebook app on iOS

Just verified this today, but if you are trying to open a Facebook page, you can use "fb://page/{Page ID}"

Page ID can be found under your page in the about section near the bottom.

Specific to my use case, in Xamarin.Forms, you can use this snippet to open in the app if available, otherwise in the browser.

Device.OpenUri(new Uri("fb://page/{id}"));

What's the difference between a proxy server and a reverse proxy server?

The previous answers were accurate, but perhaps too terse. I will try to add some examples.

First of all, the word "proxy" describes someone or something acting on behalf of someone else.

In the computer realm, we are talking about one server acting on the behalf of another computer.

For the purposes of accessibility, I will limit my discussion to web proxies - however, the idea of a proxy is not limited to websites.


Most discussion of web proxies refers to the type of proxy known as a "forward proxy."

The proxy event, in this case, is that the "forward proxy" retrieves data from another web site on behalf of the original requestee.

A tale of 3 computers (part I)

For an example, I will list three computers connected to the internet.

  • X = your computer, or "client" computer on the internet
  • Y = the proxy web site,
  • Z = the web site you want to visit,

Normally, one would connect directly from X --> Z.

However, in some scenarios, it is better for Y --> Z on behalf of X, which chains as follows: X --> Y --> Z.

Reasons why X would want to use a forward proxy server:

Here is a (very) partial list of uses of a forward proxy server:

  • 1) X is unable to access Z directly because

    • a) Someone with administrative authority over X's internet connection has decided to block all access to site Z.

      • Examples:

        • The Storm Worm virus is spreading by tricking people into visiting, so the system administrator has blocked access to the site to prevent users from inadvertently infecting themselves.

        • Employees at a large company have been wasting too much time on, so management wants access blocked during business hours.

        • A local elementary school disallows internet access to the website.

        • A government is unable to control the publishing of news, so it controls access to news instead, by blocking sites such as See TOR or FreeNet.

    • b) The administrator of Z has blocked X.

      • Examples:

        • The administrator of Z has noticed hacking attempts coming from X, so the administrator has decided to block X's IP address (and/or netrange).

        • Z is a forum website. X is spamming the forum. Z blocks X.


A tale of 3 computers (part II)

For this example, I will list three computers connected to the internet.

  • X = your computer, or "client" computer on the internet
  • Y = the reverse proxy web site,
  • Z = the web site you want to visit,

Normally, one would connect directly from X --> Z.

However, in some scenarios, it is better for the administrator of Z to restrict or disallow direct access and force visitors to go through Y first. So, as before, we have data being retrieved by Y --> Z on behalf of X, which chains as follows: X --> Y --> Z.

What is different this time compared to a "forward proxy," is that this time the user X does not know he is accessing Z, because the user X only sees he is communicating with Y. The server Z is invisible to clients and only the reverse proxy Y is visible externally. A reverse proxy requires no (proxy) configuration on the client side.

The client X thinks he is only communicating with Y (X --> Y), but the reality is that Y forwarding all communication (X --> Y --> Z again).

Reasons why Z would want to set up a reverse proxy server:

  • 1) Z wants to force all traffic to its web site to pass through Y first.
    • a) Z has a large web site that millions of people want to see, but a single web server cannot handle all the traffic. So Z sets up many servers and puts a reverse proxy on the internet that will send users to the server closest to them when they try to visit Z. This is part of how the Content Distribution Network (CDN) concept works.
  • 2) The administrator of Z is worried about retaliation for content hosted on the server and does not want to expose the main server directly to the public.
    • a) Owners of Spam brands such as "Canadian Pharmacy" appear to have thousands of servers, while in reality having most websites hosted on far fewer servers. Additionally, abuse complaints about the spam will only shut down the public servers, not the main server.

In the above scenarios, Z has the ability to choose Y.

Links to topics from the post:

Content Delivery Network

Forward proxy software (server side)

Reverse proxy software for HTTP (server side)

Reverse proxy software for TCP (server side)

See also:

How to get my project path?

Your program has no knowledge of where your VS project is, so see get path for my .exe and go ../.. to get your project's path.

C# Iterate through Class properties

Yes, you could make an indexer on your Record class that maps from the property name to the correct property. This would keep all the binding from property name to property in one place eg:

public class Record
    public string ItemType { get; set; }

    public string this[string propertyName]
            switch (propertyName)
                case "itemType":
                    ItemType = value;
                    // etc

Alternatively, as others have mentioned, use reflection.

javascript find and remove object in array based on key value

If you are using underscore js, it is easy to remove object based on key. Example:

  var temp1=[{id:1,name:"safeer"},  //temp array

  var id = _.pluck(temp1,'id'); //get id array from temp1
  var ids=[2,5,10];             //ids to be removed
  var bool_ids=[];
     return !bool_ids[];

Compile a DLL in C/C++, then call it from another program

There is but one difference. You have to take care or name mangling win C++. But on windows you have to take care about 1) decrating the functions to be exported from the DLL 2) write a so called .def file which lists all the exported symbols.

In Windows while compiling a DLL have have to use


but while using it you have to write __declspec(dllimport)

So the usual way of doing that is something like

#ifdef BUILD_DLL
#define EXPORT __declspec(dllexport)
#define EXPORT __declspec(dllimport)

The naming is a bit confusing, because it is often named EXPORT.. But that's what you'll find in most of the headers somwhere. So in your case you'd write (with the above #define)

int DLL_EXPORT add.... int DLL_EXPORT mult...

Remember that you have to add the Preprocessor directive BUILD_DLL during building the shared library.

Regards Friedrich

CSS horizontal scroll

Here's a solution with flexbox for images with variable width and height:

.container {
  display: flex;
  flex-wrap: no-wrap;
  overflow-x: auto;
  margin: 20px;
img {
  flex: 0 0 auto;
  width: auto;
  height: 100px;
  max-width: 100%;
  margin-right: 10px;

Example: JsFiddle

Making a drop down list using swift?

Unfortunately if you're looking to apply UIPopoverController in iOS9, you'll get a deprecated class warning. Instead you need to set your desired view's UIModalPresentationPopover property to achieve the same result.


In a horizontally regular environment, a presentation style where the content is displayed in a popover view. The background content is dimmed and taps outside the popover cause the popover to be dismissed. If you do not want taps to dismiss the popover, you can assign one or more views to the passthroughViews property of the associated UIPopoverPresentationController object, which you can get from the popoverPresentationController property.

In a horizontally compact environment, this option behaves the same as UIModalPresentationFullScreen.

Available in iOS 8.0 and later.


Why is System.Web.Mvc not listed in Add References?

I have had the same problem and here is the funny reason: My guess is that you expect System.Web.Mvc to be located under System.Web in the list. But the list is not alphabetical.

First sort the list and then look near the System.Web.

How do I plot in real-time in a while loop using matplotlib?

None of the methods worked for me. But I have found this Real time matplotlib plot is not working while still in a loop

All you need is to add


and then you could see the new plots.

So your code should look like this, and it will work

import matplotlib.pyplot as plt
import numpy as np
plt.ion() ## Note this correction


while i <1000:
    plt.pause(0.0001) #Note this correction

How to apply a CSS filter to a background image

The following is a simple solution for modern browsers in pure CSS with a 'before' pseudo element, like the solution from Matthew Wilcoxson.

To avoid the need of accessing the pseudo element for changing the image and other attributes in JavaScript, simply use inherit as the value and access them via the parent element (here body).

body::before {
    content: ""; /* Important */
    z-index: -1; /* Important */
    position: inherit;
    left: inherit;
    top: inherit;
    width: inherit;
    height: inherit;
    background-image: inherit;
    background-size: cover;
    filter: blur(8px);

body {
  background-image: url("xyz.jpg");
  background-size: 0 0;  /* Image should not be drawn here */
  width: 100%;
  height: 100%;
  position: fixed; /* Or absolute for scrollable backgrounds */

Angular 2 Dropdown Options Default Value

<select class="form-control" name='someting' [ngModel]="selectedWorkout" (ngModelChange)="updateWorkout($event)">
    <option value="{{}}" *ngFor="#workout of workouts">{{}}</option>

If you are using form there should be name field inside select tag.

All you need to do is just add value to the option tag.

selectedWorkout value should be "back" , and its done.

Automatically size JPanel inside JFrame

You can set a layout manager like BorderLayout and then define more specifically, where your panel should go:

MainPanel mainPanel = new MainPanel();
JFrame mainFrame = new JFrame();
mainFrame.setLayout(new BorderLayout());
mainFrame.add(mainPanel, BorderLayout.CENTER);

This puts the panel into the center area of the frame and lets it grow automatically when resizing the frame.

Fix CSS hover on iPhone/iPad/iPod

  1. Assigning an event listener to the target element seems to work. (Works with 'click', at least.) CSS hover on ios works only if an event listener is assigned

  2. Wrapping the target element in an a[href=trivial] also seems to work.

A related note/diagram on mobile Safari's algorithm for handling clicks and other events is here: Is it possible to force ignore the :hover pseudoclass for iPhone/iPad users?

How to align two elements on the same line without changing HTML

#element1 {float:left;}
#element2 {padding-left : 20px; float:left;}

fiddle :


#element1 {float:left;}
#element2 {margin-left : 20px;float:left;}

fiddle :


#element1 {padding-right : 20px; float:left;}
#element2 {float:left;}

fiddle :


#element1 {margin-right : 20px; float:left;}
#element2 {float:left;}

fiddle :

reference : The Difference Between CSS Margins and Padding

Highlight a word with jQuery

Why using a selfmade highlighting function is a bad idea

The reason why it's probably a bad idea to start building your own highlighting function from scratch is because you will certainly run into issues that others have already solved. Challenges:

  • You would need to remove text nodes with HTML elements to highlight your matches without destroying DOM events and triggering DOM regeneration over and over again (which would be the case with e.g. innerHTML)
  • If you want to remove highlighted elements you would have to remove HTML elements with their content and also have to combine the splitted text-nodes for further searches. This is necessary because every highlighter plugin searches inside text nodes for matches and if your keywords will be splitted into several text nodes they will not being found.
  • You would also need to build tests to make sure your plugin works in situations which you have not thought about. And I'm talking about cross-browser tests!

Sounds complicated? If you want some features like ignoring some elements from highlighting, diacritics mapping, synonyms mapping, search inside iframes, separated word search, etc. this becomes more and more complicated.

Use an existing plugin

When using an existing, well implemented plugin, you don't have to worry about above named things. The article 10 jQuery text highlighter plugins on Sitepoint compares popular highlighter plugins. This includes plugins of answers from this question.

Have a look at mark.js

mark.js is such a plugin that is written in pure JavaScript, but is also available as jQuery plugin. It was developed to offer more opportunities than the other plugins with options to:

  • search for keywords separately instead of the complete term
  • map diacritics (For example if "justo" should also match "justò")
  • ignore matches inside custom elements
  • use custom highlighting element
  • use custom highlighting class
  • map custom synonyms
  • search also inside iframes
  • receive not found terms


Alternatively you can see this fiddle.

Usage example:

// Highlight "keyword" in the specified context

// Highlight the custom regular expression in the specified context

It's free and developed open-source on GitHub (project reference).

DataGridView checkbox column - value and functionality

Here's a one liner answer for this question

List<DataGridViewRow> list = DataGridView1.Rows.Cast<DataGridViewRow>().Where(k => Convert.ToBoolean(k.Cells[CheckBoxColumn1.Name].Value) == true).ToList();

Javascript geocoding from address to latitude and longitude numbers not working

The script tag to the api has changed recently. Use something like this to query the Geocoding API and get the JSON object back

<script type="text/javascript" src=""></script>

The address could be something like

1600+Amphitheatre+Parkway,+Mountain+View,+CA (URI Encoded; you should Google it. Very useful)

or simply

1600 Amphitheatre Parkway, Mountain View, CA

By entering this address,+Mountain+View,+CA&key=YOUR_API_KEY inside the browser, along with my API Key, I get back a JSON object which contains the Latitude & Longitude for the city of Moutain view, CA.

{"results" : [
     "address_components" : [
           "long_name" : "1600",
           "short_name" : "1600",
           "types" : [ "street_number" ]
           "long_name" : "Amphitheatre Parkway",
           "short_name" : "Amphitheatre Pkwy",
           "types" : [ "route" ]
           "long_name" : "Mountain View",
           "short_name" : "Mountain View",
           "types" : [ "locality", "political" ]
           "long_name" : "Santa Clara County",
           "short_name" : "Santa Clara County",
           "types" : [ "administrative_area_level_2", "political" ]
           "long_name" : "California",
           "short_name" : "CA",
           "types" : [ "administrative_area_level_1", "political" ]
           "long_name" : "United States",
           "short_name" : "US",
           "types" : [ "country", "political" ]
           "long_name" : "94043",
           "short_name" : "94043",
           "types" : [ "postal_code" ]
     "formatted_address" : "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA",
     "geometry" : {
        "location" : {
           "lat" : 37.4222556,
           "lng" : -122.0838589
        "location_type" : "ROOFTOP",
        "viewport" : {
           "northeast" : {
              "lat" : 37.4236045802915,
              "lng" : -122.0825099197085
           "southwest" : {
              "lat" : 37.4209066197085,
              "lng" : -122.0852078802915
     "place_id" : "ChIJ2eUgeAK6j4ARbn5u_wAGqWA",
     "types" : [ "street_address" ]
  }],"status" : "OK"}

Web Frameworks such like AngularJS allow us to perform these queries with ease.

How do I decode a base64 encoded string?

The m000493 method seems to perform some kind of XOR encryption. This means that the same method can be used for both encrypting and decrypting the text. All you have to do is reverse m0001cd:

string p0 = Encoding.UTF8.GetString(Convert.FromBase64String("OBFZDT..."));

string result = m000493(p0, "_p0lizei.");
//    result == "gaia^unplugged^Ta..."

with return m0001cd(builder3.ToString()); changed to return builder3.ToString();.

Function return value in PowerShell

As a workaround I've been returning the last object in the array that you get back from the function... It is not a great solution, but it's better than nothing:

someFunction {
   $a = "hello"
   "Function is running"
   return $a

$b = someFunction
$b = $b[($b.count - 1)]  # Or
$b = $b[-1]              # Simpler

All in all, a more one-lineish way of writing the same thing could be:

$b = (someFunction $someParameter $andAnotherOne)[-1]

How can I center a div within another div?

Use margin:0 auto; to the child div. Then you can center the child div inside the parent div.

Clearing content of text file using C#

You can use always stream writer.It will erase old data and append new one each time.

using (StreamWriter sw = new StreamWriter(filePath))

How to get value by key from JObject?

Try this:

private string GetJArrayValue(JObject yourJArray, string key)
    foreach (KeyValuePair<string, JToken> keyValuePair in yourJArray)
        if (key == keyValuePair.Key)
            return keyValuePair.Value.ToString();

How to add Date Picker Bootstrap 3 on MVC 5 project using the Razor engine?

I hope this can help someone who was faced with my same problem.

This answer uses the Bootstrap DatePicker Plugin, which is not native to bootstrap.

Make sure you install Bootstrap DatePicker through NuGet

Create a small piece of JavaScript and name it DatePickerReady.js save it in Scripts dir. This will make sure it works even in non HTML5 browsers although those are few nowadays.

if (! {
    $(function () {



Set the bundles

bundles.Add(New ScriptBundle("~/bundles/bootstrap").Include(

bundles.Add(New StyleBundle("~/Content/css").Include(

Now set the Datatype so that when EditorFor is used MVC will identify what is to be used.

Public Property DOB As DateTime? = Nothing

Your view code should be

@Html.EditorFor(Function(model) model.DOB, New With {.htmlAttributes = New With {.class = "form-control datecontrol", .PlaceHolder = "Enter Date of Birth"}})

and voila

enter image description here

Commenting code in Notepad++

Use shortcut: Ctrl+Q. You can customize in Settings

Finish all activities at a time


//add this to the click listner

Find a file by name in Visual Studio Code

When you have opened a folder in a workspace you can do Ctrl+P (Cmd+P on Mac) and start typing the filename, or extension to filter the list of filenames

if you have:

  • plugin.ts
  • page.css
  • plugger.ts

You can type css and press enter and it will open the page.css. If you type .ts the list is filtered and contains two items.

How to check object is nil or not in swift?

Swift 4.2

func isValid(_ object:AnyObject!) -> Bool
    if let _:AnyObject = object
        return true

    return false


if isValid(selectedPost)

Using HTML5 file uploads with AJAX and jQuery

It's not too hard. Firstly, take a look at FileReader Interface.

So, when the form is submitted, catch the submission process and

var file = document.getElementById('fileBox').files[0]; //Files[0] = 1st file
var reader = new FileReader();
reader.readAsText(file, 'UTF-8');
reader.onload = shipOff;
//reader.onloadstart = ...
//reader.onprogress = ... <-- Allows you to update a progress bar.
//reader.onabort = ...
//reader.onerror = ...
//reader.onloadend = ...

function shipOff(event) {
    var result =;
    var fileName = document.getElementById('fileBox').files[0].name; //Should be 'picture.jpg'
    $.post('/myscript.php', { data: result, name: fileName }, continueSubmission);

Then, on the server side (i.e. myscript.php):

$data = $_POST['data'];
$fileName = $_POST['name'];
$serverFile = time().$fileName;
$fp = fopen('/uploads/'.$serverFile,'w'); //Prepends timestamp to prevent overwriting
fwrite($fp, $data);
$returnData = array( "serverFile" => $serverFile );
echo json_encode($returnData);

Or something like it. I may be mistaken (and if I am, please, correct me), but this should store the file as something like 1287916771myPicture.jpg in /uploads/ on your server, and respond with a JSON variable (to a continueSubmission() function) containing the fileName on the server.

Check out fwrite() and

On the above page it details how to use readAsBinaryString(), readAsDataUrl(), and readAsArrayBuffer() for your other needs (e.g. images, videos, etc).

Return outside function error in Python

As already explained by the other contributers, you could print out the counter and then replace the return with a break statement.

N = int(input("enter a positive integer:"))
counter = 1
while (N > 0):
    counter = counter * N
    N = N - 1

Should image size be defined in the img tag height/width attributes or in CSS?

Option a. Simple straight fwd. What you see is what you get easy to make calculations.

Option b. Too messy to do this inline unless you want to have a site that can stretch. IE if you used the with:86em however modern browsers seem to handle this functionally adequately for my purposes.. . Personally the only time that i would use something like this is if i were to create a thumbnails catalogue.

ul.myThumbs li {float:left; width:50px;}
ul.myThumbs li img{width:50px; height:50px;border:0;}

<img src="~/img/products/thumbs/productid.jpg" alt="" />

Option c. Too messy to maintain.

Easy way to use variables of enum types as string in C?

C or C++ does not provide this functionality, although I've needed it often.

The following code works, although it's best suited for non-sparse enums.

typedef enum { ONE, TWO, THREE } Numbers;
char *strNumbers[] = {"one","two","three"};
printf ("Value for TWO is %s\n",strNumbers[TWO]);

By non-sparse, I mean not of the form

typedef enum { ONE, FOUR_THOUSAND = 4000 } Numbers;

since that has huge gaps in it.

The advantage of this method is that it put the definitions of the enums and strings near each other; having a switch statement in a function spearates them. This means you're less likely to change one without the other.

How to change the font color of a disabled TextBox?

hi set the readonly attribute to true from the code side or run time not from the design time

txtFingerPrints.BackColor = System.Drawing.SystemColors.Info;
txtFingerPrints.ReadOnly = true;

Difference between single and double quotes in Bash

Others explained very well and just want to give with simple examples.

Single quotes can be used around text to prevent the shell from interpreting any special characters. Dollar signs, spaces, ampersands, asterisks and other special characters are all ignored when enclosed within single quotes.

$ echo 'All sorts of things are ignored in single quotes, like $ & * ; |.' 

It will give this:

All sorts of things are ignored in single quotes, like $ & * ; |.

The only thing that cannot be put within single quotes is a single quote.

Double quotes act similarly to single quotes, except double quotes still allow the shell to interpret dollar signs, back quotes and backslashes. It is already known that backslashes prevent a single special character from being interpreted. This can be useful within double quotes if a dollar sign needs to be used as text instead of for a variable. It also allows double quotes to be escaped so they are not interpreted as the end of a quoted string.

$ echo "Here's how we can use single ' and double \" quotes within double quotes"

It will give this:

Here's how we can use single ' and double " quotes within double quotes

It may also be noticed that the apostrophe, which would otherwise be interpreted as the beginning of a quoted string, is ignored within double quotes. Variables, however, are interpreted and substituted with their values within double quotes.

$ echo "The current Oracle SID is $ORACLE_SID"

It will give this:

The current Oracle SID is test

Back quotes are wholly unlike single or double quotes. Instead of being used to prevent the interpretation of special characters, back quotes actually force the execution of the commands they enclose. After the enclosed commands are executed, their output is substituted in place of the back quotes in the original line. This will be clearer with an example.

$ today=`date '+%A, %B %d, %Y'`
$ echo $today 

It will give this:

Monday, September 28, 2015 

Convert HTML5 into standalone Android App

You could use PhoneGap.

This has the benefit of being a cross-platform solution. Be warned though that you may need to pay subscription fees. The simplest solution is to just embed a WebView as detailed in @Enigma's answer.

How to invoke function from external .c file in C?

There are many great contributions here, but let me add mine non the less.

First thing i noticed is, you did not make any promises in the main file that you were going to create a function known as add(). This count have been done like this in the main file:

    int add(int a, int b); 

before your main function, that way your main function would recognize the add function and try to look for its executable code. So essentially your files should be


    int add(int a, int b);

    int main(void) {
        int result = add(5,6);
        printf("%d\n", result);

and // add.c

    int add(int a, int b) {
        return a + b;

async await return Task

This is a Task that is returning a Task of type String (C# anonymous function or in other word a delegation is used 'Func')

    public static async Task<string> MyTask()
        //C# anonymous AsyncTask
        return await Task.FromResult<string>(((Func<string>)(() =>
            // your code here
            return  "string result here";


UTF-8 byte[] to String

I use this way

String strIn = new String(_bytes, 0, numBytes);

CSS3 transform: rotate; in IE9

Try this

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
body {
    margin-left: 50px;
    margin-top: 50px;
    margin-right: 50px;
    margin-bottom: 50px;
.rotate {
    font-family: Arial, Helvetica, sans-serif;
    font-size: 16px;
    -webkit-transform: rotate(-10deg);
    -moz-transform: rotate(-10deg);
    -o-transform: rotate(-10deg);
    -ms-transform: rotate(-10deg);
    -sand-transform: rotate(10deg);
    display: block;
    position: fixed;

<div class="rotate">Alpesh</div>

How to run Rake tasks from within Rake tasks?

task :build_all do
  [ :debug, :release ].each do |t|
    $build_type = t

How can I copy the content of a branch to a new local branch?

git branch copyOfMyBranch MyBranch

This avoids the potentially time-consuming and unnecessary act of checking out a branch. Recall that a checkout modifies the "working tree", which could take a long time if it is large or contains large files (images or videos, for example).

new Runnable() but no new thread?

Shouldn't creating a new Runnable class make a new second thread?

No. new Runnable does not create second Thread.

What is the purpose of the Runnable class here apart from being able to pass a Runnable class to postAtTime?

Runnable is posted to Handler. This task runs in the thread, which is associated with Handler.

If Handler is associated with UI Thread, Runnable runs in UI Thread.

If Handler is associated with other HandlerThread, Runnable runs in HandlerThread

To explicitly associate Handler to your MainThread ( UI Thread), write below code.

Handler  mHandler = new Handler(Looper.getMainLooper();

If you write is as below, it uses HandlerThread Looper.

HandlerThread handlerThread = new HandlerThread("HandlerThread");
Handler requestHandler = new Handler(handlerThread.getLooper());

Generating Fibonacci Sequence

I got asked this question recently, and this was my solution:

function fib(n) {_x000D_
  const arr = [0,1]; // the inital array, we need something to sum at the very beginning_x000D_
  for (let i = 2; i <= n; i++) { // we want the last number, so don't forget the '=' sign_x000D_
    let a = arr[i-1]; // previous Number_x000D_
    let b = arr[i-2]; // the one before that_x000D_
    arr.push(a+b); // push the result_x000D_
  return arr; // if you want the n-th number, just return arr[n] or arr.length - 1_x000D_

A recursive solution would be:

// NOTE: This has extremly bad performance => Exponential time complexity 2^n_x000D_
function fib(n) {_x000D_
  if (n < 2) {_x000D_
    return n;_x000D_
  return fib(n-1) + fib(n-2);_x000D_
console.log('The n-th fibonacci number: ', fib(6));_x000D_
console.log('The entire fibonacci sequence: ');_x000D_
// Let's see the entire fibonacci sequence_x000D_
for (let i = 0; i <= 6; i++) {_x000D_

Like mentioned earlier, the above recursive solution has a very bad impact on performance. Fortunately, there's a solution and it's called memoization:

// (and use it on the recursive **fib** function from above):_x000D_
// We want to pass in a function which is going to, eventually, _x000D_
// use this utility function_x000D_
function memo(fn) { _x000D_
  const cache = {}; _x000D_
  // let's make it reusable, and by that I mean, let's assume that_x000D_
  // we don't know the number of arguments that will be eventually passed in _x000D_
 return function(...args) {_x000D_
// if we already call this function with the same args?_x000D_
// YES => return them_x000D_
   if(cache[args]) { _x000D_
     console.log('cached', args[0]);_x000D_
     return cache[args];_x000D_
//    otherwise, we want to call our function _x000D_
// (the one using this 'memo' function) and pass in the arguments_x000D_
// w/ the help of 'apply'_x000D_
   const res = fn.apply(this, args);_x000D_
   cache[args] = res; _x000D_
   // we want to store the result, so later if we'll be able to_x000D_
   // return that if the args don't change_x000D_
   console.log('not cached', args[0]);_x000D_
   return res; // don't forget to return the result of it :)_x000D_
// Now, let's use the memoized function:_x000D_
// NOTE: Remember the above function has to change in a way_x000D_
// that it calls the memoized function instead of itself_x000D_
function fastFib(n) {_x000D_
  if (n<2) { _x000D_
    return n;_x000D_
// But, here is where the 'magic' happens_x000D_
// Very important: We want to call the instantiated 'fibMemo' function _x000D_
// and NOT 'fastFib', cause then it wouldn't be so fast, right :)   _x000D_
  return fibMemo(n-1) + fibMemo(n-2);_x000D_
const fibMemo = memo(fastFib); _x000D_

RestClientException: Could not extract response. no suitable HttpMessageConverter found

The main problem here is content type [text/html;charset=iso-8859-1] received from the service, however the real content type should be application/json;charset=iso-8859-1

In order to overcome this you can introduce custom message converter. and register it for all kind of responses (i.e. ignore the response content type header). Just like this

List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();        
//Add the Jackson Message converter
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();

// Note: here we are making this converter to process any kind of response, 
// not only application/*json, which is the default behaviour

Loop through all elements in XML using NodeList

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document dom = db.parse("file.xml");
    Element docEle = dom.getDocumentElement();
    NodeList nl = docEle.getChildNodes();
    int length = nl.getLength();
    for (int i = 0; i < length; i++) {
        if (nl.item(i).getNodeType() == Node.ELEMENT_NODE) {
            Element el = (Element) nl.item(i);
            if (el.getNodeName().contains("staff")) {
                String name = el.getElementsByTagName("name").item(0).getTextContent();
                String phone = el.getElementsByTagName("phone").item(0).getTextContent();
                String email = el.getElementsByTagName("email").item(0).getTextContent();
                String area = el.getElementsByTagName("area").item(0).getTextContent();
                String city = el.getElementsByTagName("city").item(0).getTextContent();

Iterate over all children and nl.item(i).getNodeType() == Node.ELEMENT_NODE is used to filter text nodes out. If there is nothing else in XML what remains are staff nodes.

For each node under stuff (name, phone, email, area, city)


el.getElementsByTagName("name") will extract the "name" nodes under stuff, .item(0) will get you the first node and .getTextContent() will get the text content inside.

Edit: Since we have jackson I would do this in a different way. Define a pojo for the object:

public class Staff {
    private String name;
    private String phone;
    private String email;
    private String area;
    private String city;
...getters setters

Then using jackson:

    JsonNode root = new XmlMapper().readTree(xml.getBytes());
    ObjectMapper mapper = new ObjectMapper();
    root.forEach(node -> consume(node, mapper));

private void consume(JsonNode node, ObjectMapper mapper) {
    try {
        Staff staff = mapper.treeToValue(node, Staff.class);
        //TODO your job with staff
    } catch (JsonProcessingException e) {

Formatting html email for Outlook

I used VML(Vector Markup Language) based formatting in my email template. In VML Based you have write your code within comment I took help from this site.

How do I check how many options there are in a dropdown menu?

With pure javascript you can just call the length on the id of the select box. It will be more faster. Typically with everything native javascript is performing better and better with modern browsers

This can be achieved in javascript by

     var dropdownFilterSite = document.querySelector( '#dropDownId' );  //Similar to jQuery

var length = dropdownFilterSite.length.

Good website for some learning

A good video to watch by Todd Motto

Error "gnu/stubs-32.h: No such file or directory" while compiling Nachos source code

# sudo apt-get install g++-multilib

Should fix this error on 64-bit machines (Debian/Ubuntu).

how to get current month and year

Use the DateTime.Now property. This returns a DateTime object that contains a Year and Month property (both are integers).

string currentMonth = DateTime.Now.Month.ToString();
string currentYear = DateTime.Now.Year.ToString();

monthLabel.Text = currentMonth;
yearLabel.Text = currentYear;

D3 Appending Text to a SVG Rectangle

A rect can't contain a text element. Instead transform a g element with the location of text and rectangle, then append both the rectangle and the text to it:

var bar = chart.selectAll("g")
    .attr("transform", function(d, i) { return "translate(0," + i * barHeight + ")"; });

    .attr("width", x)
    .attr("height", barHeight - 1);

    .attr("x", function(d) { return x(d) - 3; })
    .attr("y", barHeight / 2)
    .attr("dy", ".35em")
    .text(function(d) { return d; });

Multi-line labels are also a little tricky, you might want to check out this wrap function.

Using BeautifulSoup to extract text without tags

Just loop through all the <strong> tags and use next_sibling to get what you want. Like this:

for strong_tag in soup.find_all('strong'):
    print(strong_tag.text, strong_tag.next_sibling)


from bs4 import BeautifulSoup

html = '''
  <strong class="offender">YOB:</strong> 1987<br />
  <strong class="offender">RACE:</strong> WHITE<br />
  <strong class="offender">GENDER:</strong> FEMALE<br />
  <strong class="offender">HEIGHT:</strong> 5'05''<br />
  <strong class="offender">WEIGHT:</strong> 118<br />
  <strong class="offender">EYE COLOR:</strong> GREEN<br />
  <strong class="offender">HAIR COLOR:</strong> BROWN<br />

soup = BeautifulSoup(html)

for strong_tag in soup.find_all('strong'):
    print(strong_tag.text, strong_tag.next_sibling)

This gives you:

YOB:  1987
HEIGHT:  5'05''
WEIGHT:  118

Truncating all tables in a Postgres database

FrustratedWithFormsDesigner is correct, PL/pgSQL can do this. Here's the script:

CREATE OR REPLACE FUNCTION truncate_tables(username IN VARCHAR) RETURNS void AS $$
    statements CURSOR FOR
        SELECT tablename FROM pg_tables
        WHERE tableowner = username AND schemaname = 'public';
    FOR stmt IN statements LOOP
        EXECUTE 'TRUNCATE TABLE ' || quote_ident(stmt.tablename) || ' CASCADE;';
$$ LANGUAGE plpgsql;

This creates a stored function (you need to do this just once) which you can afterwards use like this:

SELECT truncate_tables('MYUSER');

What is ROWS UNBOUNDED PRECEDING used for in Teradata?

It's the "frame" or "range" clause of window functions, which are part of the SQL standard and implemented in many databases, including Teradata.

A simple example would be to calculate the average amount in a frame of three days. I'm using PostgreSQL syntax for the example, but it will be the same for Teradata:

WITH data (t, a) AS (
  VALUES(1, 1),
        (2, 5),
        (3, 3),
        (4, 5),
        (5, 4),
        (6, 11)
FROM data

... which yields:

t  a  avg
1  1  3.00
2  5  3.00
3  3  4.33
4  5  4.00
5  4  6.67
6 11  7.50

As you can see, each average is calculated "over" an ordered frame consisting of the range between the previous row (1 preceding) and the subsequent row (1 following).

When you write ROWS UNBOUNDED PRECEDING, then the frame's lower bound is simply infinite. This is useful when calculating sums (i.e. "running totals"), for instance:

WITH data (t, a) AS (
  VALUES(1, 1),
        (2, 5),
        (3, 3),
        (4, 5),
        (5, 4),
        (6, 11)
FROM data


t  a  sum
1  1    1
2  5    6
3  3    9
4  5   14
5  4   18
6 11   29

Here's another very good explanations of SQL window functions.

How to delete files older than X hours

Does your find have the -mmin option? That can let you test the number of mins since last modification:

find $LOCATION -name $REQUIRED_FILES -type f -mmin +360 -delete

Or maybe look at using tmpwatch to do the same job. phjr also recommended tmpreaper in the comments.

AngularJS - Value attribute on an input text box is ignored when there is a ng-model used?

If you use AngularJs ngModel directive, remember that the value of value attribute does not bind on ngModel field.You have to init it by yourself and the best way to do it,is

<input type="text"
       ng-init="rootFolders = 'Bob'"

How to Apply global font to whole HTML document

Try this:

    font-family:your font;
    font-size:your value;
    font-weight:your value;

How can I sort a dictionary by key?

In Python 3.

>>> D1 = {2:3, 1:89, 4:5, 3:0}
>>> for key in sorted(D1):
    print (key, D1[key])


1 89
2 3
3 0
4 5

How can I convert a DateTime to the number of seconds since 1970?

That approach will be good if the date-time in question is in UTC, or represents local time in an area that has never observed daylight saving time. The DateTime difference routines do not take into account Daylight Saving Time, and consequently will regard midnight June 1 as being a multiple of 24 hours after midnight January 1. I'm unaware of anything in Windows that reports historical daylight-saving rules for the current locale, so I don't think there's any good way to correctly handle any time prior to the most recent daylight-saving rule change.

What's the difference between abstraction and encapsulation?

Abstraction: Hiding the data. Encapsulation: Binding the data.

jQuery: go to URL with target="_blank"

The .ready function is used to insert the attribute once the page has finished loading.

$(document).ready(function() {
     $("class name or id a.your class name").attr({"target" : "_blank"})

Detecting negative numbers

Just multiply the number by -1 and check if the result is positive.

I'm getting an error "invalid use of incomplete type 'class map'

Your first usage of Map is inside a function in the combat class. That happens before Map is defined, hence the error.

A forward declaration only says that a particular class will be defined later, so it's ok to reference it or have pointers to objects, etc. However a forward declaration does not say what members a class has, so as far as the compiler is concerned you can't use any of them until Map is fully declared.

The solution is to follow the C++ pattern of the class declaration in a .h file and the function bodies in a .cpp. That way all the declarations appear before the first definitions, and the compiler knows what it's working with.

How to write multiple conditions in with "else if"

ptomato's code can also be written in a cleaner manner like:

ifeq ($(TARGET_CPU),x86)
  TARGET_CPU_IS_X86 := 1
else ifeq ($(TARGET_CPU),x86_64)
  TARGET_CPU_IS_X86 := 1
  TARGET_CPU_IS_X86 := 0

This doesn't answer OP's question but as it's the top result on google, I'm adding it here in case it's useful to anyone else.

View markdown files offline

You can use extension called Markdown Syntax Highlighting for Notepad++. It is available on Github

enter image description here

After installation, new option in the Language dropdown will be appeared After installation, new option in the Language dropdown will be appeared

Get the selected value in a dropdown using jQuery.


jQuery("#availability option:selected").val();

Or to get the text of the option, use text():

jQuery("#availability option:selected").text();

More Info:

Reading a single char in Java

You can either scan an entire line:

Scanner s = new Scanner(;
String str = s.nextLine();

Or you can read a single char, given you know what encoding you're dealing with:

char c = (char);

Datatables: Cannot read property 'mData' of undefined

One more reason why this happens is because of the columns parameter in the DataTable initialization.

The number of columns has to match with headers

"columns" : [ {
                "width" : "30%"
            }, {
                "width" : "15%"
            }, {
                "width" : "15%"
            }, {
                "width" : "30%"
            } ]

I had 7 columns

<th>Full Name</th>
<th>Phone Number</th>
<th>Home Location</th>
<th>Current Location</th>
<th>Serving Route</th>

How to draw a rounded Rectangle on HTML Canvas?

Juan, I made a slight improvement to your method to allow for changing each rectangle corner radius individually:

 * Draws a rounded rectangle using the current state of the canvas.  
 * If you omit the last three params, it will draw a rectangle  
 * outline with a 5 pixel border radius  
 * @param {Number} x The top left x coordinate 
 * @param {Number} y The top left y coordinate  
 * @param {Number} width The width of the rectangle  
 * @param {Number} height The height of the rectangle 
 * @param {Object} radius All corner radii. Defaults to 0,0,0,0; 
 * @param {Boolean} fill Whether to fill the rectangle. Defaults to false. 
 * @param {Boolean} stroke Whether to stroke the rectangle. Defaults to true. 
CanvasRenderingContext2D.prototype.roundRect = function (x, y, width, height, radius, fill, stroke) {
    var cornerRadius = { upperLeft: 0, upperRight: 0, lowerLeft: 0, lowerRight: 0 };
    if (typeof stroke == "undefined") {
        stroke = true;
    if (typeof radius === "object") {
        for (var side in radius) {
            cornerRadius[side] = radius[side];

    this.moveTo(x + cornerRadius.upperLeft, y);
    this.lineTo(x + width - cornerRadius.upperRight, y);
    this.quadraticCurveTo(x + width, y, x + width, y + cornerRadius.upperRight);
    this.lineTo(x + width, y + height - cornerRadius.lowerRight);
    this.quadraticCurveTo(x + width, y + height, x + width - cornerRadius.lowerRight, y + height);
    this.lineTo(x + cornerRadius.lowerLeft, y + height);
    this.quadraticCurveTo(x, y + height, x, y + height - cornerRadius.lowerLeft);
    this.lineTo(x, y + cornerRadius.upperLeft);
    this.quadraticCurveTo(x, y, x + cornerRadius.upperLeft, y);
    if (stroke) {
    if (fill) {

Use it like this:

var canvas = document.getElementById("canvas");
var c = canvas.getContext("2d");
c.fillStyle = "blue";
c.roundRect(50, 100, 50, 100, {upperLeft:10,upperRight:10}, true, true);

Int to byte array

This may be OT but if you are serializing a lot of primitive types or POD structures, Google Protocol Buffers for .Net might be useful to you. This addresses the endianness issue @Marc raised above, among other useful features.

How do I get an empty array of any size in python?

Just declare the list and append each element. For ex:

a = []
a.append('first item')
a.append('second item')

How can I clear the content of a file?

The simplest way to do this is perhaps deleting the file via your application and creating a new one with the same name... in even simpler way just make your application overwrite it with a new file.

jquery animate .css

The example from jQuery's website animates size AND font but you could easily modify it to fit your needs

    width: "70%",
    opacity: 0.4,
    marginLeft: "0.6in",
    fontSize: "3em", 
    borderWidth: "10px"
  }, 1500 );

ImportError: no module named win32api

This is resolve my case as found on Where to find the win32api module for Python?

pip install pypiwin32

jQuery check/uncheck radio button onclick

I have expanded on the previous suggestions. This works for me, with multiple radios coupled by the same name.

  var previousValue = $(this).attr('previousValue');
  var name = $(this).attr('name');

  if (previousValue == 'checked')
    $(this).attr('previousValue', false);
    $("input[name="+name+"]:radio").attr('previousValue', false);
    $(this).attr('previousValue', 'checked');

jQuery click events firing multiple times

We must to stopPropagation() In order to avoid Clicks triggers event too many times.

$(this).find('#cameraImageView').on('click', function(evt) {
   console.log("Camera click event.");

It Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event. This method does not accept any arguments.

We can use event.isPropagationStopped() to determine if this method was ever called (on that event object).

This method works for custom events triggered with trigger(), as well.Note that this will not prevent other handlers on the same element from running.

Can you have if-then-else logic in SQL?

--Similar answer as above for the most part. Code included to test

CREATE TABLE table1 (project int, customer int, company int, product int, price money)
INSERT INTO table1 VALUES (1,0,50, 100, 40),(1,0,20, 200, 55),(1,10,30,300, 75),(2,10,30,300, 75)
        , price
        , CASE WhereFound WHEN 1 THEN 'Project'
                WHEN 2 THEN 'Customer'
                WHEN 3 THEN 'Company'
            ELSE 'No Match'
            END AS Source
     SELECT product, price, 1 as WhereFound FROM table1 where project = 11
     SELECT product, price, 2 FROM table1 where customer = 0
     SELECT product, price, 3 FROM table1 where company = 30
    ) AS tbl

How to locate the Path of the current project directory in Java (IDE)?

you can get the current project path use System.getProperty("user.dir")

in that method you write Key name to get your different-different paths, and if you don't know key, you can find all property use of System.getProperties() this method is return all property with key. and you can find key name manually from it.

and write System.getProperty("KEY NAME")

and get your require path.

how to remove json object key and value.?

function omit(obj, key) {
    const {[key]:ignore,} = obj;
    return rest;

You can use ES6 spread operators like this. And to remove your key simply call

const newJson = omit(myjsonobj, "otherIndustry");

Its always better if you maintain pure function when you deal with type=object in javascript.

How to get a variable type in Typescript?

For :


Use the JavaScript operator typeof:

if (typeof abc === "number") {
    // do something

TypeScript understands typeof

This is called a typeguard.


For classes you would use instanceof e.g.

class Foo {}
class Bar {} 

// Later
if (fooOrBar instanceof Foo){
  // TypeScript now knows that `fooOrBar` is `Foo`

There are also other type guards e.g. in etc

How can I consume a WSDL (SOAP) web service in Python?

I recently stumbled up on the same problem. Here is the synopsis of my solution:

Basic constituent code blocks needed

The following are the required basic code blocks of your client application

  1. Session request section: request a session with the provider
  2. Session authentication section: provide credentials to the provider
  3. Client section: create the Client
  4. Security Header section: add the WS-Security Header to the Client
  5. Consumption section: consume available operations (or methods) as needed

What modules do you need?

Many suggested to use Python modules such as urllib2 ; however, none of the modules work-at least for this particular project.

So, here is the list of the modules you need to get. First of all, you need to download and install the latest version of suds from the following link:

Additionally, you need to download and install requests and suds_requests modules from the following links respectively ( disclaimer: I am new to post in here, so I can't post more than one link for now).

Once you successfully download and install these modules, you are good to go.

The code

Following the steps outlined earlier, the code looks like the following: Imports:

import logging
from suds.client import Client
from suds.wsse import *
from datetime import timedelta,date,datetime,tzinfo
import requests
from requests.auth import HTTPBasicAuth
import suds_requests

Session request and authentication:

session = requests.session()
session.auth=(username, password)

Create the Client:

client = Client(WSDL_URL, faults=False, cachingpolicy=1, location=WSDL_URL, transport=suds_requests.RequestsTransport(session))

Add WS-Security Header:


def addSecurityHeader(client,username,password):

Please note that this method creates the security header depicted in Fig.1. So, your implementation may vary depending on the correct security header format provided by the owner of the service you are consuming.

Consume the relevant method (or operation) :



One of the best practices in such implementations as this one is logging to see how the communication is executed. In case there is some issue, it makes debugging easy. The following code does basic logging. However, you can log many aspects of the communication in addition to the ones depicted in the code.



Here is the result in my case. Note that the server returned HTTP 200. This is the standard success code for HTTP request-response.

(200, (collectionNodeLmp){
   timestamp = 2014-12-03 00:00:00-05:00
   nodeLmp[] = 
         pnodeId = 35010357
         name = "YADKIN"
         mccValue = -0.19
         mlcValue = -0.13
         price = 36.46
         type = "500 KV"
         timestamp = 2014-12-03 01:00:00-05:00
         errorCodeId = 0
         pnodeId = 33138769
         name = "ZION 1"
         mccValue = -0.18
         mlcValue = -1.86
         price = 34.75
         type = "Aggregate"
         timestamp = 2014-12-03 01:00:00-05:00
         errorCodeId = 0

Do on-demand Mac OS X cloud services exist, comparable to Amazon's EC2 on-demand instances?

I have tried they are cheap and they have great bandwith so their is low latency. You need teamviewer to log into the virtual system though

Excel formula to search if all cells in a range read "True", if not, then show "False"


This will return TRUE or FALSE (Looks for FALSE, if count isn't 0 (all True) it will be false

Eclipse hangs on loading workbench

no need to delete the entire metadata. just try deleting the .snap file under org.eclipse.core.resources in your workspace folder ex.


How to make Firefox headless programmatically in Selenium with Python?

Used below code to set driver type based on need of Headless / Head for both Firefox and chrome:

// Can pass browser type 

if brower.lower() == 'chrome':
    driver = webdriver.Chrome('..\drivers\chromedriver')
elif brower.lower() == 'headless chrome':
    ch_Options = Options()
    driver = webdriver.Chrome('..\drivers\chromedriver',options=ch_Options)
elif brower.lower() == 'firefox':
    driver = webdriver.Firefox(executable_path=r'..\drivers\geckodriver.exe')
elif brower.lower() == 'headless firefox':
    ff_option = FFOption()
    driver = webdriver.Firefox(executable_path=r'..\drivers\geckodriver.exe', options=ff_option)
elif brower.lower() == 'ie':
    driver = webdriver.Ie('..\drivers\IEDriverServer')
    raise Exception('Invalid Browser Type')

Routing with multiple Get methods in ASP.NET Web API

You might not need to make any change in the routing. Just add following four methods in your customersController.cs file:

public ActionResult Index()

public ActionResult currentMonth()

public ActionResult customerById(int id)

public ActionResult customerByUsername(string userName)

Put the relevant code in the method. With the default routing supplied, you should get appropriate action result from the controller based on the action and parameters for your given urls.

Modify your default route as:

    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new { controller = "Api", action = "Index", id = UrlParameter.Optional } // Parameter defaults

Get yesterday's date in bash on Linux, DST-safe

As this question is tagged "DST safe"

And using fork to date command implie delay, there is a simple and more efficient way using pure bash built-in:

printf -v tznow '%(%z %s)T' -1
TZ=${tznow% *} printf -v yesterday '%(%Y-%m-%d)T' $(( ${tznow#* } - 86400 ))
echo $yesterday

This is a lot quicker on more system friendly than having to fork to date.

From V>=5.0, there is a new variable $EPOCHSECONDS

printf -v tz '%(%z)T' -1
TZ=$tz printf -v yesterday '%(%Y-%m-%d)T' $(( EPOCHSECONDS - 86400 ))
echo $yesterday

Calling stored procedure from another stored procedure SQL Server

First of all, if table2's idProduct is an identity, you cannot insert it explicitly until you set IDENTITY_INSERT on that table


before the insert.

So one of two, you modify your second stored and call it with only the parameters productName and productDescription and then get the new ID

EXEC test2 'productName', 'productDescription'

or you already have the ID of the product and you don't need to call SCOPE_IDENTITY() and can make the insert on table1 with that ID

"error: assignment to expression with array type error" when I assign a struct field (C)

typedef struct{
     char name[30];
     char surname[30];
     int age;
} data;

defines that data should be a block of memory that fits 60 chars plus 4 for the int (see note)

 ^ this is name              ^ this is surname              ^ this is age

This allocates the memory on the stack.

data s1;

Assignments just copies numbers, sometimes pointers.

This fails = "Paulo";

because the compiler knows that is the start of a struct 64 bytes long, and "Paulo" is a char[] 6 bytes long (6 because of the trailing \0 in C strings)
Thus, trying to assign a pointer to a string into a string.

To copy "Paulo" into the struct at the point name and "Rossi" into the struct at point surname.

memcpy(,    "Paulo", 6);
memcpy(s1.surname, "Rossi", 6);
s1.age = 1;

You end up with


strcpy does the same thing but it knows about \0 termination so does not need the length hardcoded.

Alternatively you can define a struct which points to char arrays of any length.

typedef struct {
  char *name;
  char *surname;
  int age;
} data;

This will create


This will now work because you are filling the struct with pointers. = "Paulo";
s1.surname = "Rossi";
s1.age = 1;

Something like this


Where 4 and 10 are pointers.

Note: the ints and pointers can be different sizes, the sizes 4 above are 32bit as an example.

Transposing a 2D-array in JavaScript

If you have an option of using Ramda JS and ES6 syntax, then here's another way to do it:

const transpose = a => => => r[c], a), R.keys(a[0]));_x000D_
  [1, 2, 3, 4],_x000D_
  [5, 6, 7, 8],_x000D_
  [9, 10, 11, 12]_x000D_
])); // =>  [[1,5,9],[2,6,10],[3,7,11],[4,8,12]]
<script src=""></script>

Unable to show a Git tree in terminal

How can you get the tree-like view of commits in terminal?

git log --graph --oneline --all

is a good start.

You may get some strange letters. They are ASCII codes for colors and structure. To solve this problem add the following to your .bashrc:

export LESS="-R"

such that you do not need use Tig's ASCII filter by

git log --graph --pretty=oneline --abbrev-commit | tig   // Masi needed this 

The article text-based graph from Git-ready contains other options:

git log --graph --pretty=oneline --abbrev-commit

git log graph

Regarding the article you mention, I would go with Pod's answer: ad-hoc hand-made output.

Jakub Narebski mentions in the comments tig, a ncurses-based text-mode interface for git. See their releases.
It added a --graph option back in 2007.

Calling the base class constructor from the derived class constructor

The base-class constructor is already automatically called by your derived-class constructor. In C++, if the base class has a default constructor (takes no arguments, can be auto-generated by the compiler!), and the derived-class constructor does not invoke another base-class constructor in its initialisation list, the default constructor will be called. I.e. your code is equivalent to:

class PetStore: public Farm
public :
    : Farm()     // <---- Call base-class constructor in initialision list
    int idF;
    string nameF;

Convert pandas timezone-aware DateTimeIndex to naive timestamp, but in certain timezone

The accepted solution does not work when there are multiple different timezones in a Series. It throws ValueError: Tz-aware datetime.datetime cannot be converted to datetime64 unless utc=True

The solution is to use the apply method.

Please see the examples below:

# Let's have a series `a` with different multiple timezones. 
> a
0    2019-10-04 16:30:00+02:00
1    2019-10-07 16:00:00-04:00
2    2019-09-24 08:30:00-07:00
Name: localized, dtype: object

> a.iloc[0]
Timestamp('2019-10-04 16:30:00+0200', tz='Europe/Amsterdam')

# trying the accepted solution
> a.dt.tz_localize(None)
ValueError: Tz-aware datetime.datetime cannot be converted to datetime64 unless utc=True

# Make it tz-naive. This is the solution:
> a.apply(lambda x:x.tz_localize(None))
0   2019-10-04 16:30:00
1   2019-10-07 16:00:00
2   2019-09-24 08:30:00
Name: localized, dtype: datetime64[ns]

# a.tz_convert() also does not work with multiple timezones, but this works:
> a.apply(lambda x:x.tz_convert('America/Los_Angeles'))
0   2019-10-04 07:30:00-07:00
1   2019-10-07 13:00:00-07:00
2   2019-09-24 08:30:00-07:00
Name: localized, dtype: datetime64[ns, America/Los_Angeles]