Programs & Examples On #Gxt

GXT, also known as Ext GWT, is a dual licensed component framework that seeks to provide similar functionality to ExtJs for Google Web Toolkit (GWT) applications.

How can I add shadow to the widget in flutter?

Screenshot:

enter image description here


  1. Using BoxShadow (more customizations):

    Container(
      width: 100,
      height: 100,
      decoration: BoxDecoration(
        color: Colors.teal,
        borderRadius: BorderRadius.circular(20),
        boxShadow: [
          BoxShadow(
            color: Colors.red,
            blurRadius: 4,
            offset: Offset(4, 8), // Shadow position
          ),
        ],
      ),
    )
    

  1. Using PhysicalModel:

    PhysicalModel(
      color: Colors.teal,
      elevation: 8,
      shadowColor: Colors.red,
      borderRadius: BorderRadius.circular(20),
      child: SizedBox(width: 100, height: 100),
    )
    

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

On a rather unrelated note: more performance hacks!

  • [the first «conjecture» has been finally debunked by @ShreevatsaR; removed]

  • When traversing the sequence, we can only get 3 possible cases in the 2-neighborhood of the current element N (shown first):

    1. [even] [odd]
    2. [odd] [even]
    3. [even] [even]

    To leap past these 2 elements means to compute (N >> 1) + N + 1, ((N << 1) + N + 1) >> 1 and N >> 2, respectively.

    Let`s prove that for both cases (1) and (2) it is possible to use the first formula, (N >> 1) + N + 1.

    Case (1) is obvious. Case (2) implies (N & 1) == 1, so if we assume (without loss of generality) that N is 2-bit long and its bits are ba from most- to least-significant, then a = 1, and the following holds:

    (N << 1) + N + 1:     (N >> 1) + N + 1:
    
            b10                    b1
             b1                     b
           +  1                   + 1
           ----                   ---
           bBb0                   bBb
    

    where B = !b. Right-shifting the first result gives us exactly what we want.

    Q.E.D.: (N & 1) == 1 ? (N >> 1) + N + 1 == ((N << 1) + N + 1) >> 1.

    As proven, we can traverse the sequence 2 elements at a time, using a single ternary operation. Another 2× time reduction.

The resulting algorithm looks like this:

uint64_t sequence(uint64_t size, uint64_t *path) {
    uint64_t n, i, c, maxi = 0, maxc = 0;

    for (n = i = (size - 1) | 1; i > 2; n = i -= 2) {
        c = 2;
        while ((n = ((n & 3)? (n >> 1) + n + 1 : (n >> 2))) > 2)
            c += 2;
        if (n == 2)
            c++;
        if (c > maxc) {
            maxi = i;
            maxc = c;
        }
    }
    *path = maxc;
    return maxi;
}

int main() {
    uint64_t maxi, maxc;

    maxi = sequence(1000000, &maxc);
    printf("%llu, %llu\n", maxi, maxc);
    return 0;
}

Here we compare n > 2 because the process may stop at 2 instead of 1 if the total length of the sequence is odd.

[EDIT:]

Let`s translate this into assembly!

MOV RCX, 1000000;



DEC RCX;
AND RCX, -2;
XOR RAX, RAX;
MOV RBX, RAX;

@main:
  XOR RSI, RSI;
  LEA RDI, [RCX + 1];

  @loop:
    ADD RSI, 2;
    LEA RDX, [RDI + RDI*2 + 2];
    SHR RDX, 1;
    SHRD RDI, RDI, 2;    ror rdi,2   would do the same thing
    CMOVL RDI, RDX;      Note that SHRD leaves OF = undefined with count>1, and this doesn't work on all CPUs.
    CMOVS RDI, RDX;
    CMP RDI, 2;
  JA @loop;

  LEA RDX, [RSI + 1];
  CMOVE RSI, RDX;

  CMP RAX, RSI;
  CMOVB RAX, RSI;
  CMOVB RBX, RCX;

  SUB RCX, 2;
JA @main;



MOV RDI, RCX;
ADD RCX, 10;
PUSH RDI;
PUSH RCX;

@itoa:
  XOR RDX, RDX;
  DIV RCX;
  ADD RDX, '0';
  PUSH RDX;
  TEST RAX, RAX;
JNE @itoa;

  PUSH RCX;
  LEA RAX, [RBX + 1];
  TEST RBX, RBX;
  MOV RBX, RDI;
JNE @itoa;

POP RCX;
INC RDI;
MOV RDX, RDI;

@outp:
  MOV RSI, RSP;
  MOV RAX, RDI;
  SYSCALL;
  POP RAX;
  TEST RAX, RAX;
JNE @outp;

LEA RAX, [RDI + 59];
DEC RDI;
SYSCALL;

Use these commands to compile:

nasm -f elf64 file.asm
ld -o file file.o

See the C and an improved/bugfixed version of the asm by Peter Cordes on Godbolt. (editor's note: Sorry for putting my stuff in your answer, but my answer hit the 30k char limit from Godbolt links + text!)

Saving binary data as file using JavaScript from a browser

Try

_x000D_
_x000D_
let bytes = [65,108,105,99,101,39,115,32,65,100,118,101,110,116,117,114,101];_x000D_
_x000D_
let base64data = btoa(String.fromCharCode.apply(null, bytes));_x000D_
_x000D_
let a = document.createElement('a');_x000D_
a.href = 'data:;base64,' + base64data;_x000D_
a.download = 'binFile.txt'; _x000D_
a.click();
_x000D_
_x000D_
_x000D_

I convert here binary data to base64 (for bigger data conversion use this) - during downloading browser decode it automatically and save raw data in file. 2020.06.14 I upgrade Chrome to 83.0 and above SO snippet stop working (probably due to sandbox security restrictions) - but JSFiddle version works - here

Missing artifact com.sun:tools:jar

After struggling for a while I finally got this to work with eclipse.ini instead of the command line. After finally reading the documentation I realized that the -vm argument must be on a separate line, unquoted, and ahead of any -vmargs:

-vm
C:\Program Files\Java\jdk1.7.0_45\bin\javaw.exe

Is there a difference between "==" and "is"?

Is there a difference between == and is in Python?

Yes, they have a very important difference.

==: check for equality - the semantics are that equivalent objects (that aren't necessarily the same object) will test as equal. As the documentation says:

The operators <, >, ==, >=, <=, and != compare the values of two objects.

is: check for identity - the semantics are that the object (as held in memory) is the object. Again, the documentation says:

The operators is and is not test for object identity: x is y is true if and only if x and y are the same object. Object identity is determined using the id() function. x is not y yields the inverse truth value.

Thus, the check for identity is the same as checking for the equality of the IDs of the objects. That is,

a is b

is the same as:

id(a) == id(b)

where id is the builtin function that returns an integer that "is guaranteed to be unique among simultaneously existing objects" (see help(id)) and where a and b are any arbitrary objects.

Other Usage Directions

You should use these comparisons for their semantics. Use is to check identity and == to check equality.

So in general, we use is to check for identity. This is usually useful when we are checking for an object that should only exist once in memory, referred to as a "singleton" in the documentation.

Use cases for is include:

  • None
  • enum values (when using Enums from the enum module)
  • usually modules
  • usually class objects resulting from class definitions
  • usually function objects resulting from function definitions
  • anything else that should only exist once in memory (all singletons, generally)
  • a specific object that you want by identity

Usual use cases for == include:

  • numbers, including integers
  • strings
  • lists
  • sets
  • dictionaries
  • custom mutable objects
  • other builtin immutable objects, in most cases

The general use case, again, for ==, is the object you want may not be the same object, instead it may be an equivalent one

PEP 8 directions

PEP 8, the official Python style guide for the standard library also mentions two use-cases for is:

Comparisons to singletons like None should always be done with is or is not, never the equality operators.

Also, beware of writing if x when you really mean if x is not None -- e.g. when testing whether a variable or argument that defaults to None was set to some other value. The other value might have a type (such as a container) that could be false in a boolean context!

Inferring equality from identity

If is is true, equality can usually be inferred - logically, if an object is itself, then it should test as equivalent to itself.

In most cases this logic is true, but it relies on the implementation of the __eq__ special method. As the docs say,

The default behavior for equality comparison (== and !=) is based on the identity of the objects. Hence, equality comparison of instances with the same identity results in equality, and equality comparison of instances with different identities results in inequality. A motivation for this default behavior is the desire that all objects should be reflexive (i.e. x is y implies x == y).

and in the interests of consistency, recommends:

Equality comparison should be reflexive. In other words, identical objects should compare equal:

x is y implies x == y

We can see that this is the default behavior for custom objects:

>>> class Object(object): pass
>>> obj = Object()
>>> obj2 = Object()
>>> obj == obj, obj is obj
(True, True)
>>> obj == obj2, obj is obj2
(False, False)

The contrapositive is also usually true - if somethings test as not equal, you can usually infer that they are not the same object.

Since tests for equality can be customized, this inference does not always hold true for all types.

An exception

A notable exception is nan - it always tests as not equal to itself:

>>> nan = float('nan')
>>> nan
nan
>>> nan is nan
True
>>> nan == nan           # !!!!!
False

Checking for identity can be much a much quicker check than checking for equality (which might require recursively checking members).

But it cannot be substituted for equality where you may find more than one object as equivalent.

Note that comparing equality of lists and tuples will assume that identity of objects are equal (because this is a fast check). This can create contradictions if the logic is inconsistent - as it is for nan:

>>> [nan] == [nan]
True
>>> (nan,) == (nan,)
True

A Cautionary Tale:

The question is attempting to use is to compare integers. You shouldn't assume that an instance of an integer is the same instance as one obtained by another reference. This story explains why.

A commenter had code that relied on the fact that small integers (-5 to 256 inclusive) are singletons in Python, instead of checking for equality.

Wow, this can lead to some insidious bugs. I had some code that checked if a is b, which worked as I wanted because a and b are typically small numbers. The bug only happened today, after six months in production, because a and b were finally large enough to not be cached. – gwg

It worked in development. It may have passed some unittests.

And it worked in production - until the code checked for an integer larger than 256, at which point it failed in production.

This is a production failure that could have been caught in code review or possibly with a style-checker.

Let me emphasize: do not use is to compare integers.

method in class cannot be applied to given types

I think you want something like this. The formatting is off, but it should give the essential information you want.

   import java.util.Scanner;
public class BookstoreCredit 
{

   public static void computeDiscount(String name, double gpa) 
   {
      double credits;
      credits = gpa * 10;
      System.out.println(name + " your GPA is " +
         gpa + " so your credit is $" + credits);
   
   }

   public static void main (String args[]) 
   {
      String studentName;
      double gradeAverage;
      Scanner inputDevice = new Scanner(System.in);
      System.out.println("Enter Student name: ");
      studentName = inputDevice.nextLine();
      System.out.println("Enter student GPA: ");
      gradeAverage = inputDevice.nextDouble();  
      
      computeDiscount(studentName, gradeAverage);
   }
}

Save a subplot in matplotlib

Applying the full_extent() function in an answer by @Joe 3 years later from here, you can get exactly what the OP was looking for. Alternatively, you can use Axes.get_tightbbox() which gives a little tighter bounding box

import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
from matplotlib.transforms import Bbox

def full_extent(ax, pad=0.0):
    """Get the full extent of an axes, including axes labels, tick labels, and
    titles."""
    # For text objects, we need to draw the figure first, otherwise the extents
    # are undefined.
    ax.figure.canvas.draw()
    items = ax.get_xticklabels() + ax.get_yticklabels() 
#    items += [ax, ax.title, ax.xaxis.label, ax.yaxis.label]
    items += [ax, ax.title]
    bbox = Bbox.union([item.get_window_extent() for item in items])

    return bbox.expanded(1.0 + pad, 1.0 + pad)

# Make an example plot with two subplots...
fig = plt.figure()
ax1 = fig.add_subplot(2,1,1)
ax1.plot(range(10), 'b-')

ax2 = fig.add_subplot(2,1,2)
ax2.plot(range(20), 'r^')

# Save the full figure...
fig.savefig('full_figure.png')

# Save just the portion _inside_ the second axis's boundaries
extent = full_extent(ax2).transformed(fig.dpi_scale_trans.inverted())
# Alternatively,
# extent = ax.get_tightbbox(fig.canvas.renderer).transformed(fig.dpi_scale_trans.inverted())
fig.savefig('ax2_figure.png', bbox_inches=extent)

I'd post a pic but I lack the reputation points

How to create a showdown.js markdown extension

In your last block you have a comma after 'lang', followed immediately with a function. This is not valid json.

EDIT

It appears that the readme was incorrect. I had to to pass an array with the string 'twitter'.

var converter = new Showdown.converter({extensions: ['twitter']}); converter.makeHtml('whatever @meandave2020'); // output "<p>whatever <a href="http://twitter.com/meandave2020">@meandave2020</a></p>" 

I submitted a pull request to update this.

Easy way to convert Iterable to Collection

Concise solution with Java 8 using java.util.stream:

public static <T> List<T> toList(final Iterable<T> iterable) {
    return StreamSupport.stream(iterable.spliterator(), false)
                        .collect(Collectors.toList());
}

ggplot with 2 y axes on each side and different scales

Sometimes a client wants two y scales. Giving them the "flawed" speech is often pointless. But I do like the ggplot2 insistence on doing things the right way. I am sure that ggplot is in fact educating the average user about proper visualization techniques.

Maybe you can use faceting and scale free to compare the two data series? - e.g. look here: https://github.com/hadley/ggplot2/wiki/Align-two-plots-on-a-page

Split list into smaller lists (split in half)

This is similar to other solutions, but a little faster.

# Usage: split_half([1,2,3,4,5]) Result: ([1, 2], [3, 4, 5])

def split_half(a):
    half = len(a) >> 1
    return a[:half], a[half:]

how to disable DIV element and everything inside

I think inline scripts are hard to stop instead you can try with this:

<div id="test">
    <div>Click Me</div>
</div>

and script:

$(function () {
    $('#test').children().click(function(){
      alert('hello');
    });
    $('#test').children().off('click');
});

CHEKOUT FIDDLE AND SEE IT HELPS

Read More about .off()

How to add a second css class with a conditional value in razor MVC 4

This:

    <div class="details @(Model.Details.Count > 0 ? "show" : "hide")">

will render this:

    <div class="details hide">

and is the mark-up I want.

String index out of range: 4

You are using the wrong iteration counter, replace inp.charAt(i) with inp.charAt(j).

How to get URL parameter using jQuery or plain JavaScript?

There is another example with using URI.js library.

Example answers the questions exactly as asked.

_x000D_
_x000D_
var url = 'http://example.com?sent=yes';_x000D_
var urlParams = new URI(url).search(true);_x000D_
// 1. Does sent exist?_x000D_
var sendExists = urlParams.sent !== undefined;_x000D_
// 2. Is it equal to "yes"?_x000D_
var sendIsEqualtToYes = urlParams.sent == 'yes';_x000D_
_x000D_
// output results in readable form_x000D_
// not required for production_x000D_
if (sendExists) {_x000D_
  console.log('Url has "sent" param, its value is "' + urlParams.sent + '"');_x000D_
  if (urlParams.sent == 'yes') {_x000D_
    console.log('"Sent" param is equal to "yes"');_x000D_
  } else {_x000D_
    console.log('"Sent" param is not equal to "yes"');_x000D_
  }_x000D_
} else {_x000D_
  console.log('Url hasn\'t "sent" param');_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/URI.js/1.18.2/URI.min.js"></script>
_x000D_
_x000D_
_x000D_

Return index of greatest value in an array

This is probably the best way, since it’s reliable and works on old browsers:

function indexOfMax(arr) {
    if (arr.length === 0) {
        return -1;
    }

    var max = arr[0];
    var maxIndex = 0;

    for (var i = 1; i < arr.length; i++) {
        if (arr[i] > max) {
            maxIndex = i;
            max = arr[i];
        }
    }

    return maxIndex;
}

There’s also this one-liner:

let i = arr.indexOf(Math.max(...arr));

It performs twice as many comparisons as necessary and will throw a RangeError on large arrays, though. I’d stick to the function.

The entitlements specified...profile. (0xE8008016). Error iOS 4.2

I had the same problem as 'Snips' above - I forgot to add my phone to an updated dev provisioning profile! Just go to the provisioning portal, add your phone & then download the new profile. And agreed - the message you get isn't very helpful!

How to set Navigation Drawer to be opened from right to left

SOLUTION


your_layout.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="end">

    <include layout="@layout/app_bar_root"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="end"
        android:fitsSystemWindows="true"
        app:itemTextColor="@color/black"
        app:menu="@menu/activity_root_drawer" />

</android.support.v4.widget.DrawerLayout>

YourActivity.java:

@Override
protected void onCreate(Bundle savedInstanceState) {
//...
toolbar = (Toolbar) findViewById(R.id.toolbar);

drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();

toolbar.setNavigationOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if (drawer.isDrawerOpen(Gravity.RIGHT)) {
                drawer.closeDrawer(Gravity.RIGHT);
            } else {
                drawer.openDrawer(Gravity.RIGHT);
            }
        }
    });
//...
}

jQuery .search() to any string

if (str.toLowerCase().indexOf("yes") >= 0)

Or,

if (/yes/i.test(str))

How to get the EXIF data from a file using C#

The command line tool ExifTool by Phil Harvey works with dozens of images formats - including plenty of proprietary RAW formats - and can manipulate a variety of metadata formats including EXIF, GPS, IPTC, XMP, JFIF.

Very easy to use, lightweight, impressive application.

How do I get the "id" after INSERT into MySQL database with Python?

Python DBAPI spec also define 'lastrowid' attribute for cursor object, so...

id = cursor.lastrowid

...should work too, and it's per-connection based obviously.

Could not find com.android.tools.build:gradle:3.0.0-alpha1 in circle ci

I have this problem when update android studio from 3.2 to 3.3 and test every answers that i none of them was working. at the end i enabled Maven repository and its work.

enter image description here

Update or Insert (multiple rows and columns) from subquery in PostgreSQL

UPDATE table1 SET (col1, col2) = (col2, col3) FROM othertable WHERE othertable.col1 = 123;

Bootstrap tab activation with JQuery

This one is quite straightforward from w3schools: https://www.w3schools.com/bootstrap/bootstrap_ref_js_tab.asp

// Select tab by name
$('.nav-tabs a[href="#home"]').tab('show')

// Select first tab
$('.nav-tabs a:first').tab('show') 

// Select last tab
$('.nav-tabs a:last').tab('show') 

// Select fourth tab (zero-based)
$('.nav-tabs li:eq(3) a').tab('show')

Limit results in jQuery UI Autocomplete

I could solve this problem by adding the following content to my CSS file:

.ui-autocomplete {
    max-height: 200px;
    overflow-y: auto;
    overflow-x: hidden;
}

Updating Python on Mac

On a mac use the following in the terminal to update python if you have anaconda:

conda update python

FPDF utf-8 encoding (HOW-TO)

None of the above solutions are going to work.

Try this:

function filter_html($value){
    $value = mb_convert_encoding($value, 'ISO-8859-1', 'UTF-8');
    return $value;
}

how to change text in Android TextView

setting the text to sam textview twice is overwritting the first written text. So the second time when we use settext we just append the new string like

textview.append("Step Two: fry egg");

Set adb vendor keys

I had the same problem running Ubuntu 18.04. I tried multiple solutions but my device (OnePlus 5T) was always unauthorized.

Solution

  1. Configure udev rules on Ubuntu. To do this, just follow the official documentation: https://developer.android.com/studio/run/device

    The idVendor of my device (OnePlus) is not listed. To get it, just connect your device and use lsusb:

    Bus 003 Device 008: ID 2a70:4ee7

    In this example, 2a70 is the idVendor.

  2. Remove existing adb keys on Ubuntu:

    rm -v ~/.android/adbkey* ~/.android/adbkey ~/.android/adbkey.pub

  3. 'Revoke USB debugging authorizations' on your device configuration (developer options).

  4. Finally, restart the adb server to create a new key:

    sudo adb kill-server sudo adb devices

After that, I got the authorization prompt on my device and I authorized it.

How do I detect whether 32-bit Java is installed on x64 Windows, only looking at the filesystem and registry?

Do you have access to the command prompt ?

Method 1 : Command Prompt

The specifics of the Java installed on the system can be determined by executing the following command java -version

Method 2 : Folder Structure

In case you do not have access to command prompt then determining the folder where Java.

32 Bit : C:\Program Files (x86)\Java\jdk1.6.0_30

64 Bit : C:\Program Files\Java\jdk1.6.0_25

However during the installation it is possible that the user might change the installation folder.

Method 3 : Registry

You can also see the version installed in registry editor.

  1. Go to registry editor

  2. Edit -> Find

  3. Search for Java. You will get the registry entries for Java.

  4. In the entry with name : DisplayName & DisplayVersion, the installed java version is displayed

How to get Map data using JDBCTemplate.queryForMap

You can do something like this.

 List<Map<String, Object>> mapList = jdbctemplate.queryForList(query));
    return mapList.stream().collect(Collectors.toMap(k -> (Long) k.get("userid"), k -> (String) k.get("username")));

Output:

 {
  1: "abc",
  2: "def",
  3: "ghi"
}

How to fix "'System.AggregateException' occurred in mscorlib.dll"

You could handle the exception directly so it would not crash your program (catching the AggregateException). You could also look at the Inner Exception, this will give you a more detailed explanation of what went wrong:

try {
    // your code 
} catch (AggregateException e) {

}

update package.json version automatically

I am using husky and git-branch-is:

As of husky v1+:

// package.json
{
  "husky": {
    "hooks": {
      "post-merge": "(git-branch-is master && npm version minor || 
  (git-branch-is dev && npm --no-git-tag-version version patch)",
    }
  }
}

Prior to husky V1:

"scripts": {
  ...
  "postmerge": "(git-branch-is master && npm version minor || 
  (git-branch-is dev && npm --no-git-tag-version version patch)",
  ...
},

Read more about npm version

Webpack or Vue.js

If you are using webpack or Vue.js, you can display this in the UI using Auto inject version - Webpack plugin

NUXT

In nuxt.config.js:

var WebpackAutoInject = require('webpack-auto-inject-version');

module.exports = {
  build: {
    plugins: [
      new WebpackAutoInject({
        // options
        // example:
        components: {
          InjectAsComment: false
        },
      }),
    ]
  },
}

Inside your template for example in the footer:

<p> All rights reserved © 2018 [v[AIV]{version}[/AIV]]</p>

How do I get the value of a textbox using jQuery?

You can access the value of Texbox control either by its ID or by its Class name.

Here is the example code:

<input type="text" id="txtEmail" class="textbox" value="1">

$(document).ready(function(){
   alert($("#txtEmail").val());
   alert($(".textbox").val());//Not recommended 
});

Using class name for getting any text-box control value can return other or wrong value as same class name can also be defined for any other control. So getting value of a specific textbox can be fetch by its id.

Convert a string to a datetime

Try converting date like this:

    Dim expenddt as Date = Date.ParseExact(edate, "dd/mm/yyyy", 
System.Globalization.DateTimeFormatInfo.InvariantInfo);

Hope this helps.

Error: The processing instruction target matching "[xX][mM][lL]" is not allowed

Reason for me is 2 of following code in one xml

<?xml version="1.0" encoding="utf-8"?>

How to set default value to the input[type="date"]

Use Microsoft Visual Studio

Date separator '-'

@{string dateValue = request.Date.ToString("yyyy'-'MM'-'ddTHH:mm:ss");}

< input type="datetime-local" class="form-control" name="date1" value="@dateValue" >

APR based Apache Tomcat Native library was not found on the java.library.path?

My case: Seeing the same INFO message.

Centos 6.2 x86_64 Tomcat 6.0.24

This fixed the problem for me:

yum install tomcat-native

boom!

OkHttp Post Body as JSON

Another approach is by using FormBody.Builder().
Here's an example of callback:

Callback loginCallback = new Callback() {
    @Override
    public void onFailure(Call call, IOException e) {
        try {
            Log.i(TAG, "login failed: " + call.execute().code());
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        // String loginResponseString = response.body().string();
        try {
            JSONObject responseObj = new JSONObject(response.body().string());
            Log.i(TAG, "responseObj: " + responseObj);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        // Log.i(TAG, "loginResponseString: " + loginResponseString);
    }
};

Then, we create our own body:

RequestBody formBody = new FormBody.Builder()
        .add("username", userName)
        .add("password", password)
        .add("customCredential", "")
        .add("isPersistent", "true")
        .add("setCookie", "true")
        .build();

OkHttpClient client = new OkHttpClient.Builder()
        .addInterceptor(this)
        .build();
Request request = new Request.Builder()
        .url(loginUrl)
        .post(formBody)
        .build();

Finally, we call the server:

client.newCall(request).enqueue(loginCallback);

Create file path from variables

Yes there is such a built-in function: os.path.join.

>>> import os.path
>>> os.path.join('/my/root/directory', 'in', 'here')
'/my/root/directory/in/here'

Button text toggle in jquery

$(".pushme").click(function () {
  var button = $(this);
  button.text(button.text() == "PUSH ME" ? "DON'T PUSH ME" : "PUSH ME")           
});

This ternary operator has an implicit return. If the expression before ? is true it returns "DON'T PUSH ME", else returns "PUSH ME"

This if-else statement:

if (condition) { return A }
else { return B }

has the equivalent ternary expression:

condition ? A : B

What does ^M character mean in Vim?

If it breaks your configuration, and the ^M characters are required in mappings, you can simply replace the ^M characters by <Enter> or even <C-m> (both typed as simple character sequences, so 7 and 5 characters, respectively).

This is the single recommended, portable way of storing special keycodes in mappings

AngularJS: How to set a variable inside of a template?

Use ngInit: https://docs.angularjs.org/api/ng/directive/ngInit

<div ng-repeat="day in forecast_days" ng-init="f = forecast[day.iso]">
  {{$index}} - {{day.iso}} - {{day.name}}
  Temperature: {{f.temperature}}<br>
  Humidity: {{f.humidity}}<br>
  ...
</div>

Example: http://jsfiddle.net/coma/UV4qF/

How to convert string to integer in PowerShell

Example:

2.032 MB (2,131,022 bytes)

$u=($mbox.TotalItemSize.value).tostring()

$u=$u.trimend(" bytes)") #yields 2.032 MB (2,131,022

$u=$u.Split("(") #yields `$u[1]` as 2,131,022

$uI=[int]$u[1]

The result is 2131022 in integer form.

Asp.net - Add blank item at top of dropdownlist

The databinding takes place after you've added your blank list item, and it replaces what's there already, you need to add the blank item to the beginning of the List from your controller, or add it after databinding.

EDIT:

After googling this quickly as of ASP.Net 2.0 there's an "AppendDataBoundItems" true property that you can set to...append the databound items.

for details see

http://imar.spaanjaars.com/QuickDocId.aspx?quickdoc=281 or

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listcontrol.appenddatabounditems.aspx

How to get the range of occupied cells in excel sheet

dim lastRow as long   'in VBA it's a long 
lastrow = wks.range("A65000").end(xlup).row

Excel VBA - read cell value from code

I think you need this ..

Dim n as Integer   

For n = 5 to 17
  msgbox cells(n,3) '--> sched waste
  msgbox cells(n,4) '--> type of treatm
  msgbox format(cells(n,5),"dd/MM/yyyy") '--> Lic exp
  msgbox cells(n,6) '--> email col
Next

How can I add an item to a ListBox in C# and WinForms?

If you are adding integers, as you say in your question, this will add 50 (from 1 to 50):

for (int x = 1; x <= 50; x++)
{
   list.Items.Add(x);
}

You do not need to set DisplayMember and ValueMember unless you are adding objects that have specific properties that you want to display to the user. In your example:

listbox1.Items.Add(new { clan = "Foo", sifOsoba = 1234 });

How can I sanitize user input with PHP?

PHP has the new nice filter_input functions now, that for instance liberate you from finding 'the ultimate e-mail regex' now that there is a built-in FILTER_VALIDATE_EMAIL type

My own filter class (uses JavaScript to highlight faulty fields) can be initiated by either an ajax request or normal form post. (see the example below)

/**
 *  Pork.FormValidator
 *  Validates arrays or properties by setting up simple arrays. 
 *  Note that some of the regexes are for dutch input!
 *  Example:
 * 
 *  $validations = array('name' => 'anything','email' => 'email','alias' => 'anything','pwd'=>'anything','gsm' => 'phone','birthdate' => 'date');
 *  $required = array('name', 'email', 'alias', 'pwd');
 *  $sanitize = array('alias');
 *
 *  $validator = new FormValidator($validations, $required, $sanitize);
 *                  
 *  if($validator->validate($_POST))
 *  {
 *      $_POST = $validator->sanitize($_POST);
 *      // now do your saving, $_POST has been sanitized.
 *      die($validator->getScript()."<script type='text/javascript'>alert('saved changes');</script>");
 *  }
 *  else
 *  {
 *      die($validator->getScript());
 *  }   
 *  
 * To validate just one element:
 * $validated = new FormValidator()->validate('blah@bla.', 'email');
 * 
 * To sanitize just one element:
 * $sanitized = new FormValidator()->sanitize('<b>blah</b>', 'string');
 * 
 * @package pork
 * @author SchizoDuckie
 * @copyright SchizoDuckie 2008
 * @version 1.0
 * @access public
 */
class FormValidator
{
    public static $regexes = Array(
            'date' => "^[0-9]{1,2}[-/][0-9]{1,2}[-/][0-9]{4}\$",
            'amount' => "^[-]?[0-9]+\$",
            'number' => "^[-]?[0-9,]+\$",
            'alfanum' => "^[0-9a-zA-Z ,.-_\\s\?\!]+\$",
            'not_empty' => "[a-z0-9A-Z]+",
            'words' => "^[A-Za-z]+[A-Za-z \\s]*\$",
            'phone' => "^[0-9]{10,11}\$",
            'zipcode' => "^[1-9][0-9]{3}[a-zA-Z]{2}\$",
            'plate' => "^([0-9a-zA-Z]{2}[-]){2}[0-9a-zA-Z]{2}\$",
            'price' => "^[0-9.,]*(([.,][-])|([.,][0-9]{2}))?\$",
            '2digitopt' => "^\d+(\,\d{2})?\$",
            '2digitforce' => "^\d+\,\d\d\$",
            'anything' => "^[\d\D]{1,}\$"
    );
    private $validations, $sanatations, $mandatories, $errors, $corrects, $fields;


    public function __construct($validations=array(), $mandatories = array(), $sanatations = array())
    {
        $this->validations = $validations;
        $this->sanitations = $sanitations;
        $this->mandatories = $mandatories;
        $this->errors = array();
        $this->corrects = array();
    }

    /**
     * Validates an array of items (if needed) and returns true or false
     *
     */
    public function validate($items)
    {
        $this->fields = $items;
        $havefailures = false;
        foreach($items as $key=>$val)
        {
            if((strlen($val) == 0 || array_search($key, $this->validations) === false) && array_search($key, $this->mandatories) === false) 
            {
                $this->corrects[] = $key;
                continue;
            }
            $result = self::validateItem($val, $this->validations[$key]);
            if($result === false) {
                $havefailures = true;
                $this->addError($key, $this->validations[$key]);
            }
            else
            {
                $this->corrects[] = $key;
            }
        }

        return(!$havefailures);
    }

    /**
     *
     *  Adds unvalidated class to thos elements that are not validated. Removes them from classes that are.
     */
    public function getScript() {
        if(!empty($this->errors))
        {
            $errors = array();
            foreach($this->errors as $key=>$val) { $errors[] = "'INPUT[name={$key}]'"; }

            $output = '$$('.implode(',', $errors).').addClass("unvalidated");'; 
            $output .= "new FormValidator().showMessage();";
        }
        if(!empty($this->corrects))
        {
            $corrects = array();
            foreach($this->corrects as $key) { $corrects[] = "'INPUT[name={$key}]'"; }
            $output .= '$$('.implode(',', $corrects).').removeClass("unvalidated");';   
        }
        $output = "<script type='text/javascript'>{$output} </script>";
        return($output);
    }


    /**
     *
     * Sanitizes an array of items according to the $this->sanitations
     * sanitations will be standard of type string, but can also be specified.
     * For ease of use, this syntax is accepted:
     * $sanitations = array('fieldname', 'otherfieldname'=>'float');
     */
    public function sanitize($items)
    {
        foreach($items as $key=>$val)
        {
            if(array_search($key, $this->sanitations) === false && !array_key_exists($key, $this->sanitations)) continue;
            $items[$key] = self::sanitizeItem($val, $this->validations[$key]);
        }
        return($items);
    }


    /**
     *
     * Adds an error to the errors array.
     */ 
    private function addError($field, $type='string')
    {
        $this->errors[$field] = $type;
    }

    /**
     *
     * Sanitize a single var according to $type.
     * Allows for static calling to allow simple sanitization
     */
    public static function sanitizeItem($var, $type)
    {
        $flags = NULL;
        switch($type)
        {
            case 'url':
                $filter = FILTER_SANITIZE_URL;
            break;
            case 'int':
                $filter = FILTER_SANITIZE_NUMBER_INT;
            break;
            case 'float':
                $filter = FILTER_SANITIZE_NUMBER_FLOAT;
                $flags = FILTER_FLAG_ALLOW_FRACTION | FILTER_FLAG_ALLOW_THOUSAND;
            break;
            case 'email':
                $var = substr($var, 0, 254);
                $filter = FILTER_SANITIZE_EMAIL;
            break;
            case 'string':
            default:
                $filter = FILTER_SANITIZE_STRING;
                $flags = FILTER_FLAG_NO_ENCODE_QUOTES;
            break;

        }
        $output = filter_var($var, $filter, $flags);        
        return($output);
    }

    /** 
     *
     * Validates a single var according to $type.
     * Allows for static calling to allow simple validation.
     *
     */
    public static function validateItem($var, $type)
    {
        if(array_key_exists($type, self::$regexes))
        {
            $returnval =  filter_var($var, FILTER_VALIDATE_REGEXP, array("options"=> array("regexp"=>'!'.self::$regexes[$type].'!i'))) !== false;
            return($returnval);
        }
        $filter = false;
        switch($type)
        {
            case 'email':
                $var = substr($var, 0, 254);
                $filter = FILTER_VALIDATE_EMAIL;    
            break;
            case 'int':
                $filter = FILTER_VALIDATE_INT;
            break;
            case 'boolean':
                $filter = FILTER_VALIDATE_BOOLEAN;
            break;
            case 'ip':
                $filter = FILTER_VALIDATE_IP;
            break;
            case 'url':
                $filter = FILTER_VALIDATE_URL;
            break;
        }
        return ($filter === false) ? false : filter_var($var, $filter) !== false ? true : false;
    }       



}

Of course, keep in mind that you need to do your sql query escaping too depending on what type of db your are using (mysql_real_escape_string() is useless for an sql server for instance). You probably want to handle this automatically at your appropriate application layer like an ORM. Also, as mentioned above: for outputting to html use the other php dedicated functions like htmlspecialchars ;)

For really allowing HTML input with like stripped classes and/or tags depend on one of the dedicated xss validation packages. DO NOT WRITE YOUR OWN REGEXES TO PARSE HTML!

How can I split a string with a string delimiter?

.Split(new string[] { "is Marco and" }, StringSplitOptions.None)

Consider the spaces surronding "is Marco and". Do you want to include the spaces in your result, or do you want them removed? It's quite possible that you want to use " is Marco and " as separator...

Add data to JSONObject

The answer is to use a JSONArray as well, and to dive "deep" into the tree structure:

JSONArray arr = new JSONArray();
arr.put (...); // a new JSONObject()
arr.put (...); // a new JSONObject()

JSONObject json = new JSONObject();
json.put ("aoColumnDefs",arr);

Command for restarting all running docker containers?

Just run

docker restart $(docker ps -q)

Update

For Docker 1.13.1 use docker restart $(docker ps -a -q) as in answer lower.

How do I install soap extension?

find this line in php.ini :

;extension=soap

then remove the semicolon ; and restart Apache server

How to check if a file contains a specific string using Bash

grep -q [PATTERN] [FILE] && echo $?

The exit status is 0 (true) if the pattern was found; otherwise blankstring.

Most efficient method to groupby on an array of objects

A simple solution using ES6:

The method has a return model and allows the comparison of n properties.

const compareKey = (item, key, compareItem) => {
    return item[key] === compareItem[key]
}

const handleCountingRelatedItems = (listItems, modelCallback, compareKeyCallback) => {
    return listItems.reduce((previousValue, currentValue) => {
        if (Array.isArray(previousValue)) {
        const foundIndex = previousValue.findIndex(item => compareKeyCallback(item, currentValue))

        if (foundIndex > -1) {
            const count = previousValue[foundIndex].count + 1

            previousValue[foundIndex] = modelCallback(currentValue, count)

            return previousValue
        }

        return [...previousValue, modelCallback(currentValue, 1)]
        }

        if (compareKeyCallback(previousValue, currentValue)) {
        return [modelCallback(currentValue, 2)]
        }

        return [modelCallback(previousValue, 1), modelCallback(currentValue, 1)]
    })
}

const itemList = [
    { type: 'production', human_readable: 'Production' },
    { type: 'test', human_readable: 'Testing' },
    { type: 'production', human_readable: 'Production' }
]

const model = (currentParam, count) => ({
    label: currentParam.human_readable,
    type: currentParam.type,
    count
})

const compareParameter = (item, compareValue) => {
    const isTypeEqual = compareKey(item, 'type', compareValue)
    return isTypeEqual
}

const result = handleCountingRelatedItems(itemList, model, compareParameter)

 console.log('Result: \n', result)
/** Result: 
    [
        { label: 'Production', type: 'production', count: 2 },
        { label: 'Testing', type: 'testing', count: 1 }
    ]
*/

How can I use LEFT & RIGHT Functions in SQL to get last 3 characters?

You can use RTRIM or cast your value to VARCHAR:

SELECT RIGHT(RTRIM(Field),3), LEFT(Field,LEN(Field)-3)

Or

SELECT RIGHT(CAST(Field AS VARCHAR(15)),3), LEFT(Field,LEN(Field)-3)

JavaScript: Passing parameters to a callback function

I was looking for the same thing and end up with the solution and here it's a simple example if anybody wants to go through this.

var FA = function(data){
   console.log("IN A:"+data)
   FC(data,"LastName");
};
var FC = function(data,d2){
   console.log("IN C:"+data,d2)
};
var FB = function(data){
   console.log("IN B:"+data);
    FA(data)
};
FB('FirstName')

Also posted on the other question here

React: Expected an assignment or function call and instead saw an expression

You must return something

instead of this (this is not the right way)

const def = (props) => { <div></div> };

try

const def = (props) => ( <div></div> );

or use return statement

const def = (props) => { return  <div></div> };

PostgreSQL return result set as JSON array?

Also if you want selected field from table and aggregated then as array .

SELECT json_agg(json_build_object('data_a',a,
                                  'data_b',b,
))  from t;

The result will come .

 [{'data_a':1,'data_b':'value1'}
  {'data_a':2,'data_b':'value2'}]

What is the difference between Python and IPython?

Compared to Python, IPython (created by Fernando Perez in 2001) can do every thing what python can do. Ipython provides even extra features like tab-completion, testing, debugging, system calls and many other features. You can think IPython as a powerful interface to the Python language.

You can install Ipython using pip - pip install ipython

You can run Ipython by typing ipython in your terminal window.

How do I install a custom font on an HTML site

there is a simple way to do this: in the html file add:

<link rel="stylesheet" href="fonts/vermin_vibes.ttf" />

Note: you put the name of .ttf file you have. then go to to your css file and add:

h1 {
    color: blue;
    font-family: vermin vibes;
}

Note: you put the font family name of the font you have.

Note: do not write the font-family name as your font.ttf name example: if your font.ttf name is: "vermin_vibes.ttf" your font-family will be: "vermin vibes" font family doesn't contain special chars as "-,_"...etc it only can contain spaces.

Is there a way to cast float as a decimal without rounding and preserving its precision?

Try SELECT CAST(field1 AS DECIMAL(10,2)) field1 and replace 10,2 with whatever precision you need.

Build android release apk on Phonegap 3.x CLI

Building PhoneGap Android app for deployment to the Google Play Store

These steps would work for Cordova, PhoneGap or Ionic. The only difference would be, wherever a call to cordova is placed, replace it with phonegap or ionic, for your particular scenario.

Once you are done with the development and are ready to deploy, follow these steps:

  1. Open a command line window (Terminal on macOS and Linux OR Command Prompt on Windows).

  2. Head over to the /path/to/your/project/, which we would refer to as the Project Root.

  3. While at the project root, remove the "Console" plugin from your set of plugins.

    The command is: cordova plugin rm cordova-plugin-console

  4. While still at the project root, use the cordova build command to create an APK for release distribution.

    The command is: cordova build --release android

  5. The above process creates a file called android-release-unsigned.apk in the folder ProjectRoot/platforms/android/build/outputs/apk/

  6. Sign and align the APK using the instructions at https://developer.android.com/studio/publish/app-signing.html#signing-manually

    At the end of this step the APK which you get can be uploaded to the Play Store.

Note: As a newbie or a beginner, the last step may be a bit confusing as it was to me. One may run into a few issues and may have some questions as to what these commands are and where to find them.

Q1. What are jarsigner and keytool?
Ans: The Android App Signing instructions do tell you specifically what jarsigner and keytool are all about BUT it doesn't tell you where to find them if you run into a 'command not found error' on the command line window.

Thus, if you've got the Java Development Kit(JDK) added to your PATH variable, simply running the commands as in the Guide would work. BUT, if you don't have it in your PATH, you can always access them from the bin folder of your JDK installation.

Q2. Where is zipalign?
Ans: There is a high probability to not find the zipalign command and receive the 'command not found error'. You'd probably be googling zipalign and where to find it?

The zipalign utility is present within the Android SDK installation folder. On macOS, the default location is at, user-name/Library/Android/sdk/. If you head over to the folder you would find a bunch of other folders like docs, platform-tools, build-tools, tools, add-ons...

Open the build-tools folder. cd build-tools. In here, there would be a number of folders which are versioned according to the build tool-chain you are using in the Android SDK Manager. ZipAlign is available in each of these folders. I personally go for the folder with the latest version on it. Open Any.

On macOS or Linux you may have to use ./zipalign rather than simply typing in zipalign as the documentation mentions. On Windows, zipalign is good enough.

Python - OpenCV - imread - Displaying Image

Looks like the image is too big and the window simply doesn't fit the screen. Create window with the cv2.WINDOW_NORMAL flag, it will make it scalable. Then you can resize it to fit your screen like this:

from __future__ import division
import cv2


img = cv2.imread('1.jpg')

screen_res = 1280, 720
scale_width = screen_res[0] / img.shape[1]
scale_height = screen_res[1] / img.shape[0]
scale = min(scale_width, scale_height)
window_width = int(img.shape[1] * scale)
window_height = int(img.shape[0] * scale)

cv2.namedWindow('dst_rt', cv2.WINDOW_NORMAL)
cv2.resizeWindow('dst_rt', window_width, window_height)

cv2.imshow('dst_rt', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

According to the OpenCV documentation CV_WINDOW_KEEPRATIO flag should do the same, yet it doesn't and it's value not even presented in the python module.

Java: How to read a text file

Using Java 7 to read files with NIO.2

Import these packages:

import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

This is the process to read a file:

Path file = Paths.get("C:\\Java\\file.txt");

if(Files.exists(file) && Files.isReadable(file)) {

    try {
        // File reader
        BufferedReader reader = Files.newBufferedReader(file, Charset.defaultCharset());

        String line;
        // read each line
        while((line = reader.readLine()) != null) {
            System.out.println(line);
            // tokenize each number
            StringTokenizer tokenizer = new StringTokenizer(line, " ");
            while (tokenizer.hasMoreElements()) {
                // parse each integer in file
                int element = Integer.parseInt(tokenizer.nextToken());
            }
        }
        reader.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

To read all lines of a file at once:

Path file = Paths.get("C:\\Java\\file.txt");
List<String> lines = Files.readAllLines(file, StandardCharsets.UTF_8);

How do I install ASP.NET MVC 5 in Visual Studio 2012?

Following Microsoft tutorial-upgrade ASP.NET MVC 4 to ASP.NET MVC 5, http://www.asp.net/mvc/tutorials/mvc-5/how-to-upgrade-an-aspnet-mvc-4-and-web-api-project-to-aspnet-mvc-5-and-web-api-2, you can achieve that with one problem that Visual Studio 2012 will not be able to recognize your project as neither ASP.NET MVC 4 nor 5.

It will deal with it as a Web Form project. For example, options such adding a controller will not be there any more...

Loop Through Each HTML Table Column and Get the Data using jQuery

Using a nested .each() means that your inner loop is doing one td at a time, so you can't set the productId and product and quantity all in the inner loop.

Also using function(key, val) and then val[key].innerHTML isn't right: the .each() method passes the index (an integer) and the actual element, so you'd use function(i, element) and then element.innerHTML. Though jQuery also sets this to the element, so you can just say this.innerHTML.

Anyway, here's a way to get it to work:

    table.find('tr').each(function (i, el) {
        var $tds = $(this).find('td'),
            productId = $tds.eq(0).text(),
            product = $tds.eq(1).text(),
            Quantity = $tds.eq(2).text();
        // do something with productId, product, Quantity
    });

Demo: http://jsfiddle.net/bqX7Q/

Assign output of a program to a variable using a MS batch file

One way is:

application arg0 arg1 > temp.txt
set /p VAR=<temp.txt

Another is:

for /f %%i in ('application arg0 arg1') do set VAR=%%i

Note that the first % in %%i is used to escape the % after it and is needed when using the above code in a batch file rather than on the command line. Imagine, your test.bat has something like:

for /f %%i in ('c:\cygwin64\bin\date.exe +"%%Y%%m%%d%%H%%M%%S"') do set datetime=%%i
echo %datetime%

How to add a second x-axis in matplotlib

If You want your upper axis to be a function of the lower axis tick-values you can do as below. Please note: sometimes get_xticks() will have a ticks outside of the visible range, which you have to allow for when converting.

import matplotlib.pyplot as plt

fig, ax1 = plt.subplots()

ax1 = fig.add_subplot(111)

ax1.plot(range(5), range(5))

ax1.grid(True)

ax2 = ax1.twiny()
ax2.set_xticks( ax1.get_xticks() )
ax2.set_xbound(ax1.get_xbound())
ax2.set_xticklabels([x * 2 for x in ax1.get_xticks()])

title = ax1.set_title("Upper x-axis ticks are lower x-axis ticks doubled!")
title.set_y(1.1)
fig.subplots_adjust(top=0.85)

fig.savefig("1.png")

Gives:

enter image description here

how to wait for first command to finish?

Shell scripts, no matter how they are executed, execute one command after the other. So your code will execute results.sh after the last command of st_new.sh has finished.

Now there is a special command which messes this up: &

cmd &

means: "Start a new background process and execute cmd in it. After starting the background process, immediately continue with the next command in the script."

That means & doesn't wait for cmd to do it's work. My guess is that st_new.sh contains such a command. If that is the case, then you need to modify the script:

cmd &
BACK_PID=$!

This puts the process ID (PID) of the new background process in the variable BACK_PID. You can then wait for it to end:

while kill -0 $BACK_PID ; do
    echo "Process is still active..."
    sleep 1
    # You can add a timeout here if you want
done

or, if you don't want any special handling/output simply

wait $BACK_PID

Note that some programs automatically start a background process when you run them, even if you omit the &. Check the documentation, they often have an option to write their PID to a file or you can run them in the foreground with an option and then use the shell's & command instead to get the PID.

How to change the default GCC compiler in Ubuntu?

This is the great description and step-by-step instruction how to create and manage master and slave (gcc and g++) alternatives.

Shortly it's:

sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.6 60 --slave /usr/bin/g++ g++ /usr/bin/g++-4.6
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.7 40 --slave /usr/bin/g++ g++ /usr/bin/g++-4.7
sudo update-alternatives --config gcc

C: printf a float value

printf("%9.6f", myFloat) specifies a format with 9 total characters: 2 digits before the dot, the dot itself, and six digits after the dot.

Is there a way to make text unselectable on an HTML page?

There are many occasions when turning off selectability enhances the user experience.

For instance allowing the user to copy a block of text on the page without copying the text of any interface elements associated with it (that would become interspersed within the text being copied).

How does one set up the Visual Studio Code compiler/debugger to GCC?

EDIT: As of ~March 2016, Microsoft offers a C/C++ extension for Visual Studio Code and therefor the answer I originally gave is no longer valid.

Visual Studio Code doesn't support C/C++ very well. As such it doesn't >naturally support gcc or gdb within the Visual Studio Code application. The most it will do is syntax highlighting, the advanced features like >intellisense aren't supported with C. You can still compile and debug code >that you wrote in VSC, but you'll need to do that outside the program itself.

How to use MySQL DECIMAL?

There are correct solutions in the comments, but to summarize them into a single answer:

You have to use DECIMAL(6,4).

Then you can have 6 total number of digits, 2 before and 4 after the decimal point (the scale). At least according to this.

Property 'value' does not exist on type 'EventTarget'

Here is another simple approach, I used;

    inputChange(event: KeyboardEvent) {      
    const target = event.target as HTMLTextAreaElement;
    var activeInput = target.id;
    }

Getting each individual digit from a whole integer

Agree with previous answers.

A little correction: There's a better way to print the decimal digits from left to right, without allocating extra buffer. In addition you may want to display a zero characeter if the score is 0 (the loop suggested in the previous answers won't print anythng).

This demands an additional pass:

int div;
for (div = 1; div <= score; div *= 10)
    ;

do
{
    div /= 10;
    printf("%d\n", score / div);
    score %= div;
} while (score);

Preprocessor check if multiple defines are not defined

FWIW, @SergeyL's answer is great, but here is a slight variant for testing. Note the change in logical or to logical and.

main.c has a main wrapper like this:

#if !defined(TEST_SPI) && !defined(TEST_SERIAL) && !defined(TEST_USB)
int main(int argc, char *argv[]) {
  // the true main() routine.
}

spi.c, serial.c and usb.c have main wrappers for their respective test code like this:

#ifdef TEST_USB
int main(int argc, char *argv[]) {
  // the  main() routine for testing the usb code.
}

config.h Which is included by all the c files has an entry like this:

// Uncomment below to test the serial
//#define TEST_SERIAL


// Uncomment below to test the spi code
//#define TEST_SPI

// Uncomment below to test the usb code
#define TEST_USB

How to keep keys/values in same order as declared?

From Python 3.6 onwards, the standard dict type maintains insertion order by default.

Defining

d = {'ac':33, 'gw':20, 'ap':102, 'za':321, 'bs':10}

will result in a dictionary with the keys in the order listed in the source code.

This was achieved by using a simple array with integers for the sparse hash table, where those integers index into another array that stores the key-value pairs (plus the calculated hash). That latter array just happens to store the items in insertion order, and the whole combination actually uses less memory than the implementation used in Python 3.5 and before. See the original idea post by Raymond Hettinger for details.

In 3.6 this was still considered an implementation detail; see the What's New in Python 3.6 documentation:

The order-preserving aspect of this new implementation is considered an implementation detail and should not be relied upon (this may change in the future, but it is desired to have this new dict implementation in the language for a few releases before changing the language spec to mandate order-preserving semantics for all current and future Python implementations; this also helps preserve backwards-compatibility with older versions of the language where random iteration order is still in effect, e.g. Python 3.5).

Python 3.7 elevates this implementation detail to a language specification, so it is now mandatory that dict preserves order in all Python implementations compatible with that version or newer. See the pronouncement by the BDFL. As of Python 3.8, dictionaries also support iteration in reverse.

You may still want to use the collections.OrderedDict() class in certain cases, as it offers some additional functionality on top of the standard dict type. Such as as being reversible (this extends to the view objects), and supporting reordering (via the move_to_end() method).

SQL Insert Multiple Rows

You can use UNION All clause to perform multiple insert in a table.

ex:

INSERT INTO dbo.MyTable (ID, Name)
SELECT 123, 'Timmy'
UNION ALL
SELECT 124, 'Jonny'
UNION ALL
SELECT 125, 'Sally'

Check here

What is the function __construct used for?

class Person{
 private $fname;
 private $lname;

 public function __construct($fname,$lname){
  $this->fname = $fname;
  $this->lname = $lname;
 }
}
$objPerson1 = new Person('john','smith');

What should I do when 'svn cleanup' fails?

When starting all over is not an option...

I deleted the log file in the .svn directory (I also deleted the offending file in .svn/props-base), did a cleanup, and resumed my update.

Intermediate language used in scalac?

The nearest equivalents would be icode and bcode as used by scalac, view Miguel Garcia's site on the Scalac optimiser for more information, here: http://magarciaepfl.github.io/scala/

You might also consider Java bytecode itself to be your intermediate representation, given that bytecode is the ultimate output of scalac.

Or perhaps the true intermediate is something that the JIT produces before it finally outputs native instructions?

Ultimately though... There's no single place that you can point at an claim "there's the intermediate!". Scalac works in phases that successively change the abstract syntax tree, every single phase produces a new intermediate. The whole thing is like an onion, and it's very hard to try and pick out one layer as somehow being more significant than any other.

Java get last element of a collection

A Collection is not a necessarily ordered set of elements so there may not be a concept of the "last" element. If you want something that's ordered, you can use a SortedSet which has a last() method. Or you can use a List and call mylist.get(mylist.size()-1);

If you really need the last element you should use a List or a SortedSet. But if all you have is a Collection and you really, really, really need the last element, you could use toArray() or you could use an Iterator and iterate to the end of the list.

For example:

public Object getLastElement(final Collection c) {
    final Iterator itr = c.iterator();
    Object lastElement = itr.next();
    while(itr.hasNext()) {
        lastElement = itr.next();
    }
    return lastElement;
}

Radio/checkbox alignment in HTML/CSS

_x000D_
_x000D_
input[type="radio"], input[type="checkbox"] {_x000D_
    vertical-align: middle;_x000D_
    margin-top: -1;_x000D_
}
_x000D_
_x000D_
_x000D_

Update only specific fields in a models.Model

Usually, the correct way of updating certain fields in one or more model instances is to use the update() method on the respective queryset. Then you do something like this:

affected_surveys = Survey.objects.filter(
    # restrict your queryset by whatever fits you
    # ...
    ).update(active=True)

This way, you don't need to call save() on your model anymore because it gets saved automatically. Also, the update() method returns the number of survey instances that were affected by your update.

How to upload multiple files using PHP, jQuery and AJAX

Using this source code you can upload multiple file like google one by one through ajax. Also you can see the uploading progress

HTML

 <input type="file" id="multiupload" name="uploadFiledd[]" multiple >
 <button type="button" id="upcvr" class="btn btn-primary">Start Upload</button>
 <div id="uploadsts"></div>

Javascript

    <script>

    function uploadajax(ttl,cl){

    var fileList = $('#multiupload').prop("files");
    $('#prog'+cl).removeClass('loading-prep').addClass('upload-image');

    var form_data =  "";

    form_data = new FormData();
    form_data.append("upload_image", fileList[cl]);


    var request = $.ajax({
              url: "upload.php",
              cache: false,
              contentType: false,
              processData: false,
              async: true,
              data: form_data,
              type: 'POST', 
              xhr: function() {  
                  var xhr = $.ajaxSettings.xhr();
                  if(xhr.upload){ 
                  xhr.upload.addEventListener('progress', function(event){
                      var percent = 0;
                      if (event.lengthComputable) {
                          percent = Math.ceil(event.loaded / event.total * 100);
                      }
                      $('#prog'+cl).text(percent+'%') 
                   }, false);
                 }
                 return xhr;
              },
              success: function (res, status) {
                  if (status == 'success') {
                      percent = 0;
                      $('#prog' + cl).text('');
                      $('#prog' + cl).text('--Success: ');
                      if (cl < ttl) {
                          uploadajax(ttl, cl + 1);
                      } else {
                          alert('Done');
                      }
                  }
              },
              fail: function (res) {
                  alert('Failed');
              }    
          })
    }

    $('#upcvr').click(function(){
        var fileList = $('#multiupload').prop("files");
        $('#uploadsts').html('');
        var i;
        for ( i = 0; i < fileList.length; i++) {
            $('#uploadsts').append('<p class="upload-page">'+fileList[i].name+'<span class="loading-prep" id="prog'+i+'"></span></p>');
            if(i == fileList.length-1){
                uploadajax(fileList.length-1,0);
            }
         }
    });
    </script>

PHP

upload.php
    move_uploaded_file($_FILES["upload_image"]["tmp_name"],$_FILES["upload_image"]["name"]);

Check if table exists without using "select from"

After reading all of the above, I prefer the following statement:

SELECT EXISTS(
       SELECT * FROM information_schema.tables 
       WHERE table_schema = 'db' 
       AND table_name = 'table'
);

It indicates exactly what you want to do and it actually returns a 'boolean'.

Pandas split column of lists into multiple columns

Much simpler solution:

pd.DataFrame(df2["teams"].to_list(), columns=['team1', 'team2'])

Yields,

  team1 team2
-------------
0    SF   NYG
1    SF   NYG
2    SF   NYG
3    SF   NYG
4    SF   NYG
5    SF   NYG
6    SF   NYG
7    SF   NYG

If you wanted to split a column of delimited strings rather than lists, you could similarly do:

pd.DataFrame(df["teams"].str.split('<delim>', expand=True).values,
             columns=['team1', 'team2'])

How to check if string input is a number?

Here is the simplest solution:

a= input("Choose the option\n")

if(int(a)):
    print (a);
else:
    print("Try Again")

Http Get using Android HttpURLConnection

I have created with callBack(delegate) response to Activity class.

public class WebService extends AsyncTask<String, Void, String> {

    private Context mContext;
    private OnTaskDoneListener onTaskDoneListener;
    private String urlStr = "";

    public WebService(Context context, String url, OnTaskDoneListener onTaskDoneListener) {
        this.mContext = context;
        this.urlStr = url;
        this.onTaskDoneListener = onTaskDoneListener;
    }

    @Override
    protected String doInBackground(String... params) {
        try {

            URL mUrl = new URL(urlStr);
            HttpURLConnection httpConnection = (HttpURLConnection) mUrl.openConnection();
            httpConnection.setRequestMethod("GET");
            httpConnection.setRequestProperty("Content-length", "0");
            httpConnection.setUseCaches(false);
            httpConnection.setAllowUserInteraction(false);
            httpConnection.setConnectTimeout(100000);
            httpConnection.setReadTimeout(100000);

            httpConnection.connect();

            int responseCode = httpConnection.getResponseCode();

            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader br = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line + "\n");
                }
                br.close();
                return sb.toString();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);

        if (onTaskDoneListener != null && s != null) {
            onTaskDoneListener.onTaskDone(s);
        } else
            onTaskDoneListener.onError();
    }
}

where

public interface OnTaskDoneListener {
    void onTaskDone(String responseData);

    void onError();
}

You can modify according to your needs. It's for get

Set the default value in dropdownlist using jQuery

You can just do this:

$('#myCombobox').val(1)

Efficiently sorting a numpy array in descending order?

Here is a quick trick

In[3]: import numpy as np
In[4]: temp = np.random.randint(1,10, 10)
In[5]: temp
Out[5]: array([5, 4, 2, 9, 2, 3, 4, 7, 5, 8])

In[6]: sorted = np.sort(temp)
In[7]: rsorted = list(reversed(sorted))
In[8]: sorted
Out[8]: array([2, 2, 3, 4, 4, 5, 5, 7, 8, 9])

In[9]: rsorted
Out[9]: [9, 8, 7, 5, 5, 4, 4, 3, 2, 2]

Is putting a div inside an anchor ever correct?

With HTML5 specification... It is now possible to put a block-level element inside of an inline element. So now it's perfectly appropriate to put a 'div' or 'h1' inside of an 'a' element.

TypeError: 'str' object cannot be interpreted as an integer

You will have to put:

X = input("give starting number") 
X = int(X)
Y = input("give ending number") 
Y = int(Y)

Case Statement Equivalent in R

I am using in those cases you are referring switch(). It looks like a control statement but actually, it is a function. The expression is evaluated and based on this value, the corresponding item in the list is returned.

switch works in two distinct ways depending whether the first argument evaluates to a character string or a number.

What follows is a simple string example which solves your problem to collapse old categories to new ones.

For the character-string form, have a single unnamed argument as the default after the named values.

newCat <- switch(EXPR = category,
       cat1   = catX,
       cat2   = catX,
       cat3   = catY,
       cat4   = catY,
       cat5   = catZ,
       cat6   = catZ,
       "not available")

Detecting Browser Autofill

I had a hard time detecting auto-fill in Firefox. This is the only solution that worked for me:

Demo

HTML:

<div class="inputFields">
   <div class="f_o">
      <div class="field_set">
        <label class="phold">User</label>
        <input type="tel" class="form_field " autocomplete="off" value="" maxlength="50">
      </div>
   </div>
   <div class="f_o">
      <div class="field_set">
         <label class="phold">Password</label>
         <input type="password" class="form_field " autocomplete="off" value="" maxlength="50">
      </div>
   </div>
</div>

CSS:

/* Detect autofill for Chrome */
.inputFields input:-webkit-autofill {
    animation-name: onAutoFillStart;
    transition: background-color 50000s ease-in-out 0s;
}
.inputFields input:not(:-webkit-autofill) {
    animation-name: onAutoFillCancel;
}

@keyframes onAutoFillStart {
}

@keyframes onAutoFillCancel {
}
.inputFields {
  max-width: 414px;
}

.field_set .phold{
  display: inline-block;
  position: absolute;
  font-size: 14px;
  color: #848484;
  -webkit-transform: translate3d(0,8px,0);
  -ms-transform: translate3d(0,8px,0);
  transform: translate3d(0,8px,0);
  -webkit-transition: all 200ms ease-out;
  transition: all 200ms ease-out;
  background-color: transparent;
  -webkit-backface-visibility: hidden;
  backface-visibility: hidden;
  margin-left: 8px;
  z-index: 1;
  left: 0;
  pointer-events: none;
}

.field_set .phold_active {
   font-size: 12px;
   -webkit-transform: translate3d(0,-8px,0);
  -ms-transform: translate3d(0,-8px,0);
  transform: translate3d(0,-8px,0);
  background-color: #FFF;
  padding-left: 3px;
  padding-right: 3px;
}

.field_set input[type='text'], .field_set select, .field_set input[type='tel'], .field_set input[type='password'] {
    height: 36px;
}

.field_set input[type='text'], .field_set input[type='tel'], .field_set input[type='password'], .field_set select, .field_set textarea {
    box-sizing: border-box;
    width: 100%;
    padding: 5px;
    -webkit-appearance: none;
    -moz-appearance: none;
    appearance: none;
    border: 1px solid #ababab;
    border-radius: 0;
}

.field_set {
    margin-bottom: 10px;
    position: relative;
}

.inputFields .f_o {
    width: 100%;
    line-height: 1.42857143;
    float: none;
}

JavaScript:

    // detect auto-fill when page is loading
  $(window).on('load', function() {
    // for sign in forms when the user name and password are filled by browser
    getAutofill('.inputFields');
  });

  function getAutofill(parentClass) {
    if ($(parentClass + ' .form_field').length > 0) {    
      var formInput = $(parentClass + ' .form_field');
      formInput.each(function(){   
        // for Chrome:  $(this).css('animation-name') == 'onAutoFillStart'
        // for Firefox: $(this).val() != ''
        if ($(this).css('animation-name') == 'onAutoFillStart' || $(this).val() != '') {
          $(this).siblings('.phold').addClass('phold_active');
        } else {
          $(this).siblings('.phold').removeClass('phold_active');
        }
      });
    }
  } 

  $(document).ready(function(){

    $(document).on('click','.phold',function(){
      $(this).siblings('input, textarea').focus();
    });
    $(document).on('focus','.form_field', function(){
      $(this).siblings('.phold').addClass('phold_active');
    });

    // blur for Chrome and change for Firefox
    $(document).on('blur change','.form_field', function(){
      var $this = $(this);
      if ($this.val().length == 0) {        
        $(this).siblings('.phold').removeClass('phold_active');
      } else {
        $(this).siblings('.phold').addClass('phold_active');
      }
    });

    // case when form is reloaded due to errors
    if ($('.form_field').length > 0) {
      var formInput = $('.form_field');
      formInput.each(function(){
        if ($(this).val() != '') {
          $(this).siblings('.phold').addClass('phold_active');
        } else {
          $(this).siblings('.phold').removeClass('phold_active');
        }
      });
    }

  }); 

For Chrome I use: if ($(this).css('animation-name') == 'onAutoFillStart')

For Firefox: if ($(this).val() != '')

Regular expression for URL validation (in JavaScript)

Try this regex, it works for me:

function isUrl(s) {
    var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
    return regexp.test(s);
}

Read a file one line at a time in node.js?

function createLineReader(fileName){
    var EM = require("events").EventEmitter
    var ev = new EM()
    var stream = require("fs").createReadStream(fileName)
    var remainder = null;
    stream.on("data",function(data){
        if(remainder != null){//append newly received data chunk
            var tmp = new Buffer(remainder.length+data.length)
            remainder.copy(tmp)
            data.copy(tmp,remainder.length)
            data = tmp;
        }
        var start = 0;
        for(var i=0; i<data.length; i++){
            if(data[i] == 10){ //\n new line
                var line = data.slice(start,i)
                ev.emit("line", line)
                start = i+1;
            }
        }
        if(start<data.length){
            remainder = data.slice(start);
        }else{
            remainder = null;
        }
    })

    stream.on("end",function(){
        if(null!=remainder) ev.emit("line",remainder)
    })

    return ev
}


//---------main---------------
fileName = process.argv[2]

lineReader = createLineReader(fileName)
lineReader.on("line",function(line){
    console.log(line.toString())
    //console.log("++++++++++++++++++++")
})

if arguments is equal to this string, define a variable like this string

Don't forget about spaces:

source=""
samples=("")
if [ $1 = "country" ]; then
   source="country"
   samples="US Canada Mexico..."
else
  echo "try again"
fi

How to hide columns in HTML table?

Kos's answer is almost right, but can have damaging side effects. This is more correct:

#myTable tr td:nth-child(1), #myTable th:nth-child(1) {
    display: none;
}

CSS (Cascading Style Sheets) will cascade attributes to all of its children. This means that *:nth-child(1) will hide the first td of each tr AND hide the first element of all td children. If any of your td have things like buttons, icons, inputs, or selects, the first one will be hidden (woops!).

Even if you don't currently have things that will be hidden, image your frustration down the road if you need to add one. Don't punish your future self like that, that's going to be a pain to debug!

My answer will only hide the first td and th on all tr in #myTable keeping your other elements safe.

How to use a class object in C++ as a function parameter

If you want to pass class instances (objects), you either use

 void function(const MyClass& object){
   // do something with object  
 }

or

 void process(MyClass& object_to_be_changed){
   // change member variables  
 }

On the other hand if you want to "pass" the class itself

template<class AnyClass>
void function_taking_class(){
   // use static functions of AnyClass
   AnyClass::count_instances();
   // or create an object of AnyClass and use it
   AnyClass object;
   object.member = value;
}
// call it as 
function_taking_class<MyClass>();
// or 
function_taking_class<MyStruct>();

with

class MyClass{
  int member;
  //...
};
MyClass object1;

403 Forbidden You don't have permission to access /folder-name/ on this server

under etc/apache2/apache2.conf, you can find one or more blocks that describe the server directories and permissions

As an example, this is the default configuration

<Directory /var/www/>
   Options Indexes FollowSymLinks
   AllowOverride None
   Require all granted
</Directory>

you can replicate this but change the directory path /var/www/ with the new directory.

Finally, you need to restart the apache server, you can do that from a terminal with the command: sudo service apache2 restart

Convert Month Number to Month Name Function in SQL

i think this is enough to get month name when u have date.

SELECT DATENAME(month ,GETDATE())

Decoding JSON String in Java

This is the JSON String we want to decode :

{ 
   "stats": { 
       "sdr": "aa:bb:cc:dd:ee:ff", 
       "rcv": "aa:bb:cc:dd:ee:ff", 
       "time": "UTC in millis", 
       "type": 1, 
       "subt": 1, 
       "argv": [
          {"1": 2}, 
          {"2": 3}
       ]}
}

I store this string under the variable name "sJSON" Now, this is how to decode it :)

// Creating a JSONObject from a String 
JSONObject nodeRoot  = new JSONObject(sJSON); 

// Creating a sub-JSONObject from another JSONObject
JSONObject nodeStats = nodeRoot.getJSONObject("stats");

// Getting the value of a attribute in a JSONObject
String sSDR = nodeStats.getString("sdr");

Loop in react-native

First of all, I recommend writing the item you want to render multiple times (in your case list of fields) as a separate component:

function Field() {
    return (
        <View>
            <View>
                <TextInput />
            </View>
            <View>
                <TextInput />
            </View>
            <View>
                <TextInput />
            </View>
        </View>
    );
}

Then, in your case, when rendering based on some number and not a list, I'd move the for loop outside of the render method for a more readable code:

renderFields() {
    const noGuest = this.state.guest;
    const fields = [];
    for (let i=0; i < noGuest; i++) {
        // Try avoiding the use of index as a key, it has to be unique!
        fields.push(
            <Field key={"guest_"+i} />
        );
    }
    return fields;
}

render () {
    return (
        <View>
            <View>
                <View><Text>No</Text></View>
                <View><Text>Name</Text></View>
                <View><Text>Preference</Text></View>
            </View>
            {this.renderFields()}
        </View>;
    )
}

However, there are many more ways to render looped content in react native. Most of the ways are covered in this article, so please check it out if you're interested in more details! The examples in article are from React, but everything applies to React Native as well!

How do write IF ELSE statement in a MySQL query

SELECT col1, col2, IF( action = 2 AND state = 0, 1, 0 ) AS state from tbl1;

OR

SELECT col1, col2, (case when (action = 2 and state = 0) then 1 else 0 end) as state from tbl1;

both results will same....

How to convert password into md5 in jquery?

You need additional plugin for this.

take a look at this plugin

How can I determine the current CPU utilization from the shell?

Linux does not have any system variables that give the current CPU utilization. Instead, you have to read /proc/stat several times: each column in the cpu(n) lines gives the total CPU time, and you have to take subsequent readings of it to get percentages. See this document to find out what the various columns mean.

xml.LoadData - Data at the root level is invalid. Line 1, position 1

The hidden character is probably BOM. The explanation to the problem and the solution can be found here, credits to James Schubert, based on an answer by James Brankin found here.

Though the previous answer does remove the hidden character, it also removes the whole first line. The more precise version would be:

string _byteOrderMarkUtf8 = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble());
if (xml.StartsWith(_byteOrderMarkUtf8))
{
    xml = xml.Remove(0, _byteOrderMarkUtf8.Length);
}

I encountered this problem when fetching an XSLT file from Azure blob and loading it into an XslCompiledTransform object. On my machine the file looked just fine, but after uploading it as a blob and fetching it back, the BOM character was added.

Javascript - How to detect if document has loaded (IE 7/Firefox 3)

if(document.readyState === 'complete') {
    DoStuffFunction();
} else {
    if (window.addEventListener) {  
        window.addEventListener('load', DoStuffFunction, false);
    } else {
        window.attachEvent('onload', DoStuffFunction);
    }
}

How do I use CSS with a ruby on rails application?

The original post might have been true back in 2009, but now it is actually incorrect now, and no linking is even required for the stylesheet as I see mentioned in some of the other responses. Rails will now do this for you by default.

  • Place any new sheet .css (or other) in app/assets/stylesheets
  • Test your server with rails-root/scripts/rails server and you'll see the link is added by rails itself.

You can test this with a path in your browser like testserverpath:3000/assets/filename_to_test.css?body=1

Function for C++ struct

Yes, a struct is identical to a class except for the default access level (member-wise and inheritance-wise). (and the extra meaning class carries when used with a template)

Every functionality supported by a class is consequently supported by a struct. You'd use methods the same as you'd use them for a class.

struct foo {
  int bar;
  foo() : bar(3) {}   //look, a constructor
  int getBar() 
  { 
    return bar; 
  }
};

foo f;
int y = f.getBar(); // y is 3

What is path of JDK on Mac ?

/System/Library/Frameworks/JavaVM.framework/

Also see Java 7 path on mountain lion

Functions that return a function

Returning b is returning a function object. In Javascript, functions are just objects, like any other object. If you find that not helpful, just replace the word "object" with "thing". You can return any object from a function. You can return a true/false value. An integer (1,2,3,4...). You can return a string. You can return a complex object with multiple properties. And you can return a function. a function is just a thing.

In your case, returning b returns the thing, the thing is a callable function. Returning b() returns the value returned by the callable function.

Consider this code:

function b() {
   return 42;
}

Using the above definition, return b(); returns the value 42. On the other hand return b; returns a function, that itself returns the value of 42. They are two different things.

What does the error "JSX element type '...' does not have any construct or call signatures" mean?

When declaring React Class component, use React.ComponentClass instead of React.Component then it will fix the ts error.

gradlew command not found?

First thing is you need to run the gradle task that you mentioned for this wrapper. Ex : gradle wrapper After running this command, check your directory for gradlew and gradlew.bat files. gradlew is the shell script file & can be used in linux/Mac OS. gradlew.bat is the batch file for windows OS. Then run,

./gradlew build (linux/mac). It will work.

How to customize the configuration file of the official PostgreSQL Docker image?

My solution is for colleagues who needs to make changes in config before launching docker-entrypoint-initdb.d

I was needed to change 'shared_preload_libraries' setting so during it's work postgres already has new library preloaded and code in docker-entrypoint-initdb.d can use it.

So I just patched postgresql.conf.sample file in Dockerfile:

RUN echo "shared_preload_libraries='citus,pg_cron'" >> /usr/share/postgresql/postgresql.conf.sample
RUN echo "cron.database_name='newbie'" >> /usr/share/postgresql/postgresql.conf.sample

And with this patch it become possible to add extension in .sql file in docker-entrypoint-initdb.d/:

CREATE EXTENSION pg_cron;

How to call loading function with React useEffect only once

we developed a module on GitHub that has hooks for fetching data so you can use it like this for your purpose:

import { useFetching } from "react-concurrent";

const app = () => {
  const { data, isLoading, error , refetch } = useFetching(() =>
    fetch("http://example.com"),
  );
};

You can fork that out, but any PRs are welcome. https://github.com/hosseinmd/react-concurrent#react-concurrent

Java: Check if command line arguments are null

If you don't pass any argument then even in that case args gets initialized but without any item/element. Try the following one, you will get the same effect:

 
public static void main(String[] args) throws InterruptedException {
        String [] dummy= new String [] {};
        if(dummy[0] == null)
        {
            System.out.println("Proper Usage is: java program filename");
            System.exit(0);
        }

    }

mysql query: SELECT DISTINCT column1, GROUP BY column2

Replacing FROM tablename with FROM (SELECT DISTINCT * FROM tablename) should give you the result you want (ignoring duplicated rows) for example:

SELECT name, COUNT(*)
FROM (SELECT DISTINCT * FROM Table1) AS T1
GROUP BY name

Result for your test data:

dave 2
mark 2

How to increase font size in the Xcode editor?

for Xocde 12.0 beta 5:

preferences > Themes > at the bottom you will see the font family.

preview

Merge 2 arrays of objects

_x000D_
_x000D_
var arr1 = [{ name: "lang", value: "English" }, { name: "age", value: "18" }];
var arr2 = [{ name: "childs", value: '5' }, { name: "lang", value: "German" }];

function mergeArrayByProperty(arr1, arr2, prop) {
    var newArray =
        arr1.map(item => {
            if (typeof (item[prop]) !== "undefined") {
                var nItems = arr2.filter(ni => { if (typeof (ni[prop]) !== "undefined" && ni[prop] === item[prop]) return ni; });
                if (nItems.length > 0) {
                    item = Object.assign({}, item, nItems[0]);
                }
                return item;
            }
        });
    var arr2nd = arr2.flatMap(item => { return item[prop] });
    var arr1nd = arr1.flatMap(item => { return item[prop] });
    var nonDupArr = arr2nd.map(p => { if (arr1nd.includes(p) === false) return arr2.filter(i2 => { if (i2[prop] === p) return Object.assign({}, i2) })[0]; });
    return newArray.concat(nonDupArr).filter(i=>{if(i !== null)return i})
}
var arr = mergeArrayByProperty(arr1, arr2, 'name');
console.log(arr)
_x000D_
_x000D_
_x000D_ I know this has been answered a lot, but I thought I would share.

This finds the duplicate key in the first array and merges the second arrays object having the same key value. If no value is found in the second array, it uses the original object. As you can see, lang is only found once in the result set; having german for the value.

When to use React setState callback

Yes there is, since setState works in an asynchronous way. That means after calling setState the this.state variable is not immediately changed. so if you want to perform an action immediately after setting state on a state variable and then return a result, a callback will be useful

Consider the example below

....
changeTitle: function changeTitle (event) {
  this.setState({ title: event.target.value });
  this.validateTitle();
},
validateTitle: function validateTitle () {
  if (this.state.title.length === 0) {
    this.setState({ titleError: "Title can't be blank" });
  }
},
....

The above code may not work as expected since the title variable may not have mutated before validation is performed on it. Now you may wonder that we can perform the validation in the render() function itself but it would be better and a cleaner way if we can handle this in the changeTitle function itself since that would make your code more organised and understandable

In this case callback is useful

....
changeTitle: function changeTitle (event) {
  this.setState({ title: event.target.value }, function() {
    this.validateTitle();
  });

},
validateTitle: function validateTitle () {
  if (this.state.title.length === 0) {
    this.setState({ titleError: "Title can't be blank" });
  }
},
....

Another example will be when you want to dispatch and action when the state changed. you will want to do it in a callback and not the render() as it will be called everytime rerendering occurs and hence many such scenarios are possible where you will need callback.

Another case is a API Call

A case may arise when you need to make an API call based on a particular state change, if you do that in the render method, it will be called on every render onState change or because some Prop passed down to the Child Component changed.

In this case you would want to use a setState callback to pass the updated state value to the API call

....
changeTitle: function (event) {
  this.setState({ title: event.target.value }, () => this.APICallFunction());
},
APICallFunction: function () {
  // Call API with the updated value
}
....

Why avoid increment ("++") and decrement ("--") operators in JavaScript?

The "pre" and "post" nature of increment and decrement operators can tend to be confusing for those who are not familiar with them; that's one way in which they can be tricky.

Is it possible to install iOS 6 SDK on Xcode 5?

From 1st february Apple will reject app built only for iOS6 or lower. Here is also the official communication from Apple. Better start building for iOS7.

To clarify my statement: If you build for iOS6 or lower, apple will reject your app. If you build for iOS7 AND lower everything is fine, this means:

  1. you must use xcode5
  2. you should deploy on iOS7 at least.

The content of the Apple email is pretty clear at me

"Make sure your apps work seamlessly with the innovative technologies in iOS 7. Starting February 1, new apps and app updates submitted to the App Store must be built with Xcode 5 and iOS 7 SDK."

Reading a List from properties file and load with spring annotation @Value

My preferred way (for strings, in particular), is the following one:

admin.user={'Doe, John','Headroom, Max','Mouse, Micky'}

and use

@Value("#{${admin.user}}")
private List<String> userList;

In this way, you can include also commas in your parameter. It works also for Sets.

Is there an upper bound to BigInteger?

BigInteger would only be used if you know it will not be a decimal and there is a possibility of the long data type not being large enough. BigInteger has no cap on its max size (as large as the RAM on the computer can hold).

From here.

It is implemented using an int[]:

  110       /**
  111        * The magnitude of this BigInteger, in <i>big-endian</i> order: the
  112        * zeroth element of this array is the most-significant int of the
  113        * magnitude.  The magnitude must be "minimal" in that the most-significant
  114        * int ({@code mag[0]}) must be non-zero.  This is necessary to
  115        * ensure that there is exactly one representation for each BigInteger
  116        * value.  Note that this implies that the BigInteger zero has a
  117        * zero-length mag array.
  118        */
  119       final int[] mag;

From the source

From the Wikipedia article Arbitrary-precision arithmetic:

Several modern programming languages have built-in support for bignums, and others have libraries available for arbitrary-precision integer and floating-point math. Rather than store values as a fixed number of binary bits related to the size of the processor register, these implementations typically use variable-length arrays of digits.

Select multiple columns from a table, but group by one

Your Data

DECLARE @OrderDetails TABLE 
(ProductID INT,ProductName VARCHAR(10), OrderQuantity INT)

INSERT INTO @OrderDetails VALUES
(1001,'abc',5),(1002,'abc',23),(2002,'xyz',8),
(3004,'ytp',15),(4001,'aze',19),(1001,'abc',7)

Query

 Select ProductID, ProductName, Sum(OrderQuantity) AS Total
 from @OrderDetails 
 Group By ProductID, ProductName  ORDER BY ProductID

Result

+---------------------------------+
¦ ProductID ¦ ProductName ¦ Total ¦
¦-----------+-------------+-------¦
¦      1001 ¦ abc         ¦    12 ¦
¦      1002 ¦ abc         ¦    23 ¦
¦      2002 ¦ xyz         ¦     8 ¦
¦      3004 ¦ ytp         ¦    15 ¦
¦      4001 ¦ aze         ¦    19 ¦
+---------------------------------+

How can I determine the URL that a local Git repository was originally cloned from?

You cloned your repo with SSH clone.

git config --get remote.origin.url
[email protected]:company/product/production.git

But you want to get http url to open it in the browser or share it:

git config --get remote.origin.url | sed -e 's/:/\//g'| sed -e 's/ssh\/\/\///g'| sed -e 's/git@/https:\/\//g'

https://gitlab.com/company/product/production.git

GitHub or GitLab doesn’t matter.

Where to find the complete definition of off_t type?

As the "GNU C Library Reference Manual" says

off_t
    This is a signed integer type used to represent file sizes. 
    In the GNU C Library, this type is no narrower than int.
    If the source is compiled with _FILE_OFFSET_BITS == 64 this 
    type is transparently replaced by off64_t.

and

off64_t
    This type is used similar to off_t. The difference is that 
    even on 32 bit machines, where the off_t type would have 32 bits,
    off64_t has 64 bits and so is able to address files up to 2^63 bytes
    in length. When compiling with _FILE_OFFSET_BITS == 64 this type 
    is available under the name off_t.

Thus if you want reliable way of representing file size between client and server, you can:

  1. Use off64_t type and stat64() function accordingly (as it fills structure stat64, which contains off64_t type itself). Type off64_t guaranties the same size on 32 and 64 bit machines.
  2. As was mentioned before compile your code with -D_FILE_OFFSET_BITS == 64 and use usual off_t and stat().
  3. Convert off_t to type int64_t with fixed size (C99 standard). Note: (my book 'C in a Nutshell' says that it is C99 standard, but optional in implementation). The newest C11 standard says:
7.20.1.1 Exact-width integer types

    1 The typedef name intN_t designates a signed integer type with width N ,
    no padding bits, and a two’s complement representation. Thus, int8_t 
    denotes such a signed integer type with a width of exactly 8 bits.
    without mentioning.

And about implementation:

7.20 Integer types <stdint.h>

    ... An implementation shall provide those types described as ‘‘required’’,
    but need not provide any of the others (described as ‘‘optional’’).
    ...
    The following types are required:
    int_least8_t  uint_least8_t
    int_least16_t uint_least16_t
    int_least32_t uint_least32_t
    int_least64_t uint_least64_t
    All other types of this form are optional.

Thus, in general, C standard can't guarantee types with fixed sizes. But most compilers (including gcc) support this feature.

Force download a pdf link using javascript/ajax/jquery

Here is a Javascript solution (for folks like me who were looking for an answer to the title):

function SaveToDisk(fileURL, fileName) {
    // for non-IE
    if (!window.ActiveXObject) {
        var save = document.createElement('a');
        save.href = fileURL;
        save.target = '_blank';
        save.download = fileName || 'unknown';

        var evt = new MouseEvent('click', {
            'view': window,
            'bubbles': true,
            'cancelable': false
        });
        save.dispatchEvent(evt);

        (window.URL || window.webkitURL).revokeObjectURL(save.href);
    }

    // for IE < 11
    else if ( !! window.ActiveXObject && document.execCommand)     {
        var _window = window.open(fileURL, '_blank');
        _window.document.close();
        _window.document.execCommand('SaveAs', true, fileName || fileURL)
        _window.close();
    }
}

source: http://muaz-khan.blogspot.fr/2012/10/save-files-on-disk-using-javascript-or.html

Unfortunately the working for me with IE11, which is not accepting new MouseEvent. I use the following in that case:

//...
try {
    var evt = new MouseEvent(...);
} catch (e) {
    window.open(fileURL, fileName);
}
//...

How to change letter spacing in a Textview?

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

How to Customize the time format for Python logging?

Using logging.basicConfig, the following example works for me:

logging.basicConfig(
    filename='HISTORYlistener.log',
    level=logging.DEBUG,
    format='%(asctime)s.%(msecs)03d %(levelname)s %(module)s - %(funcName)s: %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S',
)

This allows you to format & config all in one line. A resulting log record looks as follows:

2014-05-26 12:22:52.376 CRITICAL historylistener - main: History log failed to start

How to remove new line characters from data rows in mysql?

Removes trailing returns when importing from Excel. When you execute this, you may receive an error that there is no WHERE; ignore and execute.

UPDATE table_name SET col_name = TRIM(TRAILING '\r' FROM col_name)

How to find substring inside a string (or how to grep a variable)?

You can use "index" if you only want to find a single character, e.g.:

LIST="server1 server2 server3 server4 server5"
SOURCE="3"
if expr index "$LIST" "$SOURCE"; then
    echo "match"
    exit -1
else
    echo "no match"
fi

Output is:

23
match

Tomcat 7 is not running on browser(http://localhost:8080/ )

1)Goto Server tab 2)Right on server -> general -> click on switch location. 3)Double click on the server -> under server location -> select tomcat installation. 4) restart the server.

Setting Environment Variables for Node to retrieve

You can set the environment variable through process global variable as follows:

process.env['NODE_ENV'] = 'production';

Works in all platforms.

How can I override inline styles with external CSS?

You can easily override inline style except inline !important style

so

<div style="font-size: 18px; color: red;">
    Hello World, How Can I Change The Color To Blue?
</div>

div {
   color: blue !important; 
   /* This will  Work */
}

but if you have

<div style="font-size: 18px; color: red !important;">
    Hello World, How Can I Change The Color To Blue?
</div>

div {
   color: blue !important; 
   /* This Isn't Working */
}

now it will be red only .. and you can not override it

Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize

Please to solve this problem we just have set installed JDK path in

standalone.conf

file which under the bin folder of JBoss\Wildfly Server. To solve this we do the following steps:

  1. Open the standlone.conf file which under JBoss_or_wildfly\bin folder
  2. Within this file find for #JAVA_HOME text.
  3. Remove the # character and set your installed JDK path as JAVA_HOME="C:\Program Files\Java\jdk1.8.0_65" Hope this will solve your problem Thanks

Setting up FTP on Amazon Cloud Server

FileZila is good FTP tool to setup with Amazon Cloud.

  1. Download FileZila client from https://filezilla-project.org/
  2. Click on File -> Site Manager - >
  3. New Site
  4. Provide Host Name IP address of your amazon cloud location (Port if any)
  5. Protocol - SFTP (May change based on your requirement)
  6. Login Type - Normal (So system will not ask for password each time)
  7. Provide user name and password.
  8. Connect.

You need to do these step only 1 time, later it will upload content to the same IP address and same site.

Error: getaddrinfo ENOTFOUND in nodejs for get call

for me it was because in /etc/hosts file the hostname is not added

What is the size of a pointer?

To answer your other question. The size of a pointer and the size of what it points to are not related. A good analogy is to consider them like postal addresses. The size of the address of a house has no relationship to the size of the house.

Removing border from table cells

If none of the solutions on this page work and you are having the below issue:

enter image description here

You can simply use this snippet of CSS:

td {
   padding: 0;
}

How to set gradle home while importing existing project in Android studio

I ran into same problem. I selected location C:\Program Files (x86)\Android\android-studio\plugins\gradle as Gradle Home

java: use StringBuilder to insert at the beginning

How about:

StringBuilder builder = new StringBuilder();
for(int i=99;i>=0;i--){
    builder.append(Integer.toString(i));
}
builder.toString();

OR

StringBuilder builder = new StringBuilder();
for(int i=0;i<100;i++){
  builder.insert(0, Integer.toString(i));
}
builder.toString();

But with this, you are making the operation O(N^2) instead of O(N).

Snippet from java docs:

Inserts the string representation of the Object argument into this character sequence. The overall effect is exactly as if the second argument were converted to a string by the method String.valueOf(Object), and the characters of that string were then inserted into this character sequence at the indicated offset.

How to check a radio button with jQuery?

function rbcitiSelction(e) {
     debugger
    $('#trpersonalemail').hide();
    $('#trcitiemail').show();
}

function rbpersSelction(e) {
    var personalEmail = $(e).val();
    $('#trpersonalemail').show();
    $('#trcitiemail').hide();
}

$(function() {  
    $("#citiEmail").prop("checked", true)
});

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

Somewhere you will need to set a fixed height, instead of using auto everywhere. You will find that if you set a fixed height on your content and/or container, then using auto for things inside it will work.

Also, your boxes will still expand height-wise with more content in, even though you have set a height for it - so don't worry about that :)

#container {
  height:500px;
  min-height:500px;
}

ListView with OnItemClickListener

Asked by many, The childs in list must not have width "match_parent" if you are looking for listview click only.

Even if you set the "Focusable" to false it wont work. Set the child's Width to wrap_content

<TextView
    android:id="@+id/itemchild"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    ...

How to call URL action in MVC with javascript function?

Within your onDropDownChange handler, just make a jQuery AJAX call, passing in any data you need to pass up to your URL. You can handle successful and failure calls with the success and error options. In the success option, use the data contained in the data argument to do whatever rendering you need to do. Remember these are asynchronous by default!

function onDropDownChange(e) {
    var url = '/Home/Index/' + e.value;
    $.ajax({
      url: url,
      data: {}, //parameters go here in object literal form
      type: 'GET',
      datatype: 'json',
      success: function(data) { alert('got here with data'); },
      error: function() { alert('something bad happened'); }
    });
}

jQuery's AJAX documentation is here.

Material effect on button with background color

If you are interested in ImageButton you can try this simple thing :

<ImageButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@android:drawable/ic_button"
    android:background="?attr/selectableItemBackgroundBorderless"
/>

Spring Data JPA findOne() change to Optional how to use this?

I always write a default method "findByIdOrError" in widely used CrudRepository repos/interfaces.

@Repository 
public interface RequestRepository extends CrudRepository<Request, Integer> {

    default Request findByIdOrError(Integer id) {
        return findById(id).orElseThrow(EntityNotFoundException::new);
    } 
}

How do I get the name of the active user via the command line in OS X?

You can also use the logname command from the BSD General Commands Manual under Linux or MacOS to see the username of the user currently logged in, even if the user is performing a sudo operation. This is useful, for instance, when modifying a user's crontab while installing a system-wide package with sudo: crontab -u $(logname)

Per man logname:

LOGNAME(1)

NAME
    logname -- display user's login name

Download/Stream file from URL - asp.net

Download url to bytes and convert bytes into stream:

using (var client = new WebClient())
{
    var content = client.DownloadData(url);
    using (var stream = new MemoryStream(content))
    {
        ...
    }
}   

How to efficiently build a tree from a flat structure?

It's not exactly the same as what the asker looked for, but I had difficulty wrapping my head around the ambiguously phrased answers provided here, and I still think this answer fits under the title.

My answer is for mapping a flat structure to a directly-on-object tree where all you have is a ParentID on each object. ParentID is null or 0 if it is a root. Opposite of the asker, I assume all valid ParentID's point to something else in the list:

var rootNodes = new List<DTIntranetMenuItem>();
var dictIntranetMenuItems = new Dictionary<long, DTIntranetMenuItem>();

//Convert the flat database items to the DTO's,
//that has a list of children instead of a ParentID.
foreach (var efIntranetMenuItem in flatIntranetMenuItems) //List<tblIntranetMenuItem>
{
    //Automapper (nuget)
    DTIntranetMenuItem intranetMenuItem =
                                   Mapper.Map<DTIntranetMenuItem>(efIntranetMenuItem);
    intranetMenuItem.Children = new List<DTIntranetMenuItem>();
    dictIntranetMenuItems.Add(efIntranetMenuItem.ID, intranetMenuItem);
}

foreach (var efIntranetMenuItem in flatIntranetMenuItems)
{
    //Getting the equivalent object of the converted ones
    DTIntranetMenuItem intranetMenuItem = dictIntranetMenuItems[efIntranetMenuItem.ID];

    if (efIntranetMenuItem.ParentID == null || efIntranetMenuItem.ParentID <= 0)
    {
        rootNodes.Add(intranetMenuItem);
    }
    else
    {
        var parent = dictIntranetMenuItems[efIntranetMenuItem.ParentID.Value];
        parent.Children.Add(intranetMenuItem);
        //intranetMenuItem.Parent = parent;
    }
}
return rootNodes;

Saving changes after table edit in SQL Server Management Studio

Go into Tools -> Options -> Designers-> Uncheck "Prevent saving changes that require table re-creation". Voila.

That happens because sometimes it is necessary to drop and recreate a table in order to change something. This can take a while, since all data must be copied to a temp table and then re-inserted in the new table. Since SQL Server by default doesn't trust you, you need to say "OK, I know what I'm doing, now let me do my work."

ini_set("memory_limit") in PHP 5.3.3 is not working at all

Most likely your sushosin updated, which changed the default of suhosin.memory_limit from disabled to 0 (which won't allow any updates to memory_limit).

On Debian, change /etc/php5/conf.d/suhosin.ini

;suhosin.memory_limit = 0

to

suhosin.memory_limit = 2G

Or whichever value you are comfortable with. You can find the changelog of Sushosin at http://www.hardened-php.net/hphp/changelog.html, which says:

Changed the way the memory_limit protection is implemented

JPanel Padding in Java

When you need padding inside the JPanel generally you add padding with the layout manager you are using. There are cases that you can just expand the border of the JPanel.

When running WebDriver with Chrome browser, getting message, "Only local connections are allowed" even though browser launches properly

Had the same problem, solved it by getting the appropriate webdriver from: https://chromedriver.chromium.org/downloads

You can know the exact version of your chrome browser by entering the link:

chrome://settings/help

How do I use the lines of a file as arguments of a command?

In my bash shell the following worked like a charm:

cat input_file | xargs -I % sh -c 'command1 %; command2 %; command3 %;'

where input_file is

arg1
arg2
arg3

As evident, this allows you to execute multiple commands with each line from input_file, a nice little trick I learned here.

Mysql select distinct

DISTINCT is not a function that applies only to some columns. It's a query modifier that applies to all columns in the select-list.

That is, DISTINCT reduces rows only if all columns are identical to the columns of another row.

DISTINCT must follow immediately after SELECT (along with other query modifiers, like SQL_CALC_FOUND_ROWS). Then following the query modifiers, you can list columns.

  • RIGHT: SELECT DISTINCT foo, ticket_id FROM table...

    Output a row for each distinct pairing of values across ticket_id and foo.

  • WRONG: SELECT foo, DISTINCT ticket_id FROM table...

    If there are three distinct values of ticket_id, would this return only three rows? What if there are six distinct values of foo? Which three values of the six possible values of foo should be output?
    It's ambiguous as written.

Test process.env with Jest

In ./package.json:

"jest": {
  "setupFiles": [
    "<rootDir>/jest/setEnvVars.js"
  ]
}

In ./jest/setEnvVars.js:

process.env.SOME_VAR = 'value';

CSS-Only Scrollable Table with fixed headers

As I was recently in need of this, I will share a solution that uses 3 tables, but does not require JavaScript.

Table 1 (parent) contains two rows. The first row contains table 2 (child 1) for the column headers. The second row contains table 3 (child 2) for the scrolling content.

It must be noted the childTbl must be 25px shorter than the parentTbl for the scroller to appear properly.

This is the source, where I got the idea from. I made it HTML5-friendly without the deprecated tags and the inline CSS.

_x000D_
_x000D_
.parentTbl table {_x000D_
  border-spacing: 0;_x000D_
  border-collapse: collapse;_x000D_
  border: 0;_x000D_
  width: 690px;_x000D_
}_x000D_
.childTbl table {_x000D_
  border-spacing: 0;_x000D_
  border-collapse: collapse;_x000D_
  border: 1px solid #d7d7d7;_x000D_
  width: 665px;_x000D_
}_x000D_
.childTbl th,_x000D_
.childTbl td {_x000D_
  border: 1px solid #d7d7d7;_x000D_
}_x000D_
.scrollData {_x000D_
  width: 690;_x000D_
  height: 150px;_x000D_
  overflow-x: hidden;_x000D_
}
_x000D_
<div class="parentTbl">_x000D_
  <table>_x000D_
    <tr>_x000D_
      <td>_x000D_
        <div class="childTbl">_x000D_
          <table class="childTbl">_x000D_
            <tr>_x000D_
              <th>Header 1</th>_x000D_
              <th>Header 2</th>_x000D_
              <th>Header 3</th>_x000D_
              <th>Header 4</th>_x000D_
              <th>Header 5</th>_x000D_
              <th>Header 6</th>_x000D_
            </tr>_x000D_
          </table>_x000D_
        </div>_x000D_
      </td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>_x000D_
        <div class="scrollData childTbl">_x000D_
          <table>_x000D_
            <tr>_x000D_
              <td>Table Data 1</td>_x000D_
              <td>Table Data 2</td>_x000D_
              <td>Table Data 3</td>_x000D_
              <td>Table Data 4</td>_x000D_
              <td>Table Data 5</td>_x000D_
              <td>Table Data 6</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
              <td>Table Data 1</td>_x000D_
              <td>Table Data 2</td>_x000D_
              <td>Table Data 3</td>_x000D_
              <td>Table Data 4</td>_x000D_
              <td>Table Data 5</td>_x000D_
              <td>Table Data 6</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
              <td>Table Data 1</td>_x000D_
              <td>Table Data 2</td>_x000D_
              <td>Table Data 3</td>_x000D_
              <td>Table Data 4</td>_x000D_
              <td>Table Data 5</td>_x000D_
              <td>Table Data 6</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
              <td>Table Data 1</td>_x000D_
              <td>Table Data 2</td>_x000D_
              <td>Table Data 3</td>_x000D_
              <td>Table Data 4</td>_x000D_
              <td>Table Data 5</td>_x000D_
              <td>Table Data 6</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
              <td>Table Data 1</td>_x000D_
              <td>Table Data 2</td>_x000D_
              <td>Table Data 3</td>_x000D_
              <td>Table Data 4</td>_x000D_
              <td>Table Data 5</td>_x000D_
              <td>Table Data 6</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
              <td>Table Data 1</td>_x000D_
              <td>Table Data 2</td>_x000D_
              <td>Table Data 3</td>_x000D_
              <td>Table Data 4</td>_x000D_
              <td>Table Data 5</td>_x000D_
              <td>Table Data 6</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
              <td>Table Data 1</td>_x000D_
              <td>Table Data 2</td>_x000D_
              <td>Table Data 3</td>_x000D_
              <td>Table Data 4</td>_x000D_
              <td>Table Data 5</td>_x000D_
              <td>Table Data 6</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
              <td>Table Data 1</td>_x000D_
              <td>Table Data 2</td>_x000D_
              <td>Table Data 3</td>_x000D_
              <td>Table Data 4</td>_x000D_
              <td>Table Data 5</td>_x000D_
              <td>Table Data 6</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
              <td>Table Data 1</td>_x000D_
              <td>Table Data 2</td>_x000D_
              <td>Table Data 3</td>_x000D_
              <td>Table Data 4</td>_x000D_
              <td>Table Data 5</td>_x000D_
              <td>Table Data 6</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
              <td>Table Data 1</td>_x000D_
              <td>Table Data 2</td>_x000D_
              <td>Table Data 3</td>_x000D_
              <td>Table Data 4</td>_x000D_
              <td>Table Data 5</td>_x000D_
              <td>Table Data 6</td>_x000D_
            </tr>_x000D_
          </table>_x000D_
        </div>_x000D_
      </td>_x000D_
    </tr>_x000D_
  </table>_x000D_
</div>
_x000D_
_x000D_
_x000D_

This is reliable on different browsers, the downside would be having to hard code the table widths.

INNER JOIN in UPDATE sql for DB2

Just to update only the rows that match the conditions, and avoid updating nulls in the other rows:

update table_one set field_1 = 'ACTIVE' where exists 
(select 1 from table_two where table_one.customer = table_two.customer);

It works in a DB2/AIX64 9.7.8

What is the difference between Unidirectional and Bidirectional JPA and Hibernate associations?

In terms of coding, a bidirectional relationship is more complex to implement because the application is responsible for keeping both sides in synch according to JPA specification 5 (on page 42). Unfortunately the example given in the specification does not give more details, so it does not give an idea of the level of complexity.

When not using a second level cache it is usually not a problem to do not have the relationship methods correctly implemented because the instances get discarded at the end of the transaction.

When using second level cache, if anything gets corrupted because of wrongly implemented relationship handling methods, this means that other transactions will also see the corrupted elements (the second level cache is global).

A correctly implemented bi-directional relationship can make queries and the code simpler, but should not be used if it does not really make sense in terms of business logic.

How change List<T> data to IQueryable<T> data

var list = new List<string>();
var queryable = list.AsQueryable();

Add a reference to: System.Linq

Getting A File's Mime Type In Java

It is better to use two layer validation for files upload.

First you can check for the mimeType and validate it.

Second you should look to convert the first 4 bytes of your file to hexadecimal and then compare it with the magic numbers. Then it will be a really secure way to check for file validations.

Python: Number of rows affected by cursor.execute("SELECT ...)

The number of rows effected is returned from execute:

rows_affected=cursor.execute("SELECT ... ")

of course, as AndiDog already mentioned, you can get the row count by accessing the rowcount property of the cursor at any time to get the count for the last execute:

cursor.execute("SELECT ... ")
rows_affected=cursor.rowcount

From the inline documentation of python MySQLdb:

 def execute(self, query, args=None):

    """Execute a query.

    query -- string, query to execute on server
    args -- optional sequence or mapping, parameters to use with query.

    Note: If args is a sequence, then %s must be used as the
    parameter placeholder in the query. If a mapping is used,
    %(key)s must be used as the placeholder.

    Returns long integer rows affected, if any

    """

javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"Group")

None of the solutions mentioned here worked for me, I was still getting:

Exception in thread "main" javax.xml.bind.UnmarshalException: unexpected element (uri:"java:XXX.XX.XX.XXX", local:"XXXXX")

After lot of research through other sites below code worked for me-

FileInputStream fis = new FileInputStream("D:/group.xml");
SOAPMessage message = factory.createMessage(new MimeHeaders(), fis);
JAXBContext jc = JAXBContext.newInstance(Group.class);
Unmarshaller u = jc.createUnmarshaller();
JAXBElement<Group> r = u.unmarshal(message.getSOAPBody().extractContentAsDocument(), Group.class);
Group group = r.getValue();

Postgresql, update if row with some unique value exists, else insert

Firstly It tries insert. If there is a conflict on url column then it updates content and last_analyzed fields. If updates are rare this might be better option.

INSERT INTO URLs (url, content, last_analyzed)
VALUES
    (
        %(url)s,
        %(content)s,
        NOW()
    ) 
ON CONFLICT (url) 
DO
UPDATE
SET content=%(content)s, last_analyzed = NOW();

Android: How to set password property in an edit text?

You need to use PasswordTransformationMethod.getInstance() instead of new PasswordTransformationMethod().

C - The %x format specifier

From http://en.wikipedia.org/wiki/Printf_format_string

use 0 instead of spaces to pad a field when the width option is specified. For example, printf("%2d", 3) results in " 3", while printf("%02d", 3) results in "03".

How to parse dates in multiple formats using SimpleDateFormat

You'll need to use a different SimpleDateFormat object for each different pattern. That said, you don't need that many different ones, thanks to this:

Number: For formatting, the number of pattern letters is the minimum number of digits, and shorter numbers are zero-padded to this amount. For parsing, the number of pattern letters is ignored unless it's needed to separate two adjacent fields.

So, you'll need these formats:

  • "M/y" (that covers 9/09, 9/2009, and 09/2009)
  • "M/d/y" (that covers 9/1/2009)
  • "M-d-y" (that covers 9-1-2009)

So, my advice would be to write a method that works something like this (untested):

// ...
List<String> formatStrings = Arrays.asList("M/y", "M/d/y", "M-d-y");
// ...

Date tryParse(String dateString)
{
    for (String formatString : formatStrings)
    {
        try
        {
            return new SimpleDateFormat(formatString).parse(dateString);
        }
        catch (ParseException e) {}
    }

    return null;
}

How to re import an updated package while in Python Interpreter?

dragonfly's answer worked for me (python 3.4.3).

import sys
del sys.modules['module_name']

Here is a lower level solution :

exec(open("MyClass.py").read(), globals())

How can I increase a scrollbar's width using CSS?

This can be done in WebKit-based browsers (such as Chrome and Safari) with only CSS:

::-webkit-scrollbar {
    width: 2em;
    height: 2em
}
::-webkit-scrollbar-button {
    background: #ccc
}
::-webkit-scrollbar-track-piece {
    background: #888
}
::-webkit-scrollbar-thumb {
    background: #eee
}?

JSFiddle Demo


References:

Crop image to specified size and picture location

You would need to do something like this. I am typing this off the top of my head, so this may not be 100% correct.

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef context = CGBitmapContextCreate(NULL, 640, 360, 8, 4 * width, colorSpace, kCGImageAlphaPremultipliedFirst); CGColorSpaceRelease(colorSpace);  CGContextDrawImage(context, CGRectMake(0,-160,640,360), cgImgFromAVCaptureSession);  CGImageRef image = CGBitmapContextCreateImage(context); UIImage* myCroppedImg = [UIImage imageWithCGImage:image]; CGContextRelease(context);       

jQuery select box validation

To put a require rule on a select list you just need an option with an empty value

<option value="">Year</option>

then just applying required on its own is enough

<script>
    $(function () {
        $("form").validate();
    });
</script>

with form

<form>
<select name="year" id="year" class="required">
    <option value="">Year</option>
    <option value="1">1919</option>
    <option value="2">1920</option>
    <option value="3">1921</option>
    <option value="4">1922</option>
</select>
<input type="submit" />
</form>

fiddle is here

Convert an int to ASCII character

This will only work for int-digits 0-9, but your question seems to suggest that might be enough.

It works by adding the ASCII value of char '0' to the integer digit.

int i=6;
char c = '0'+i;  // now c is '6'

For example:

'0'+0 = '0'
'0'+1 = '1'
'0'+2 = '2'
'0'+3 = '3'

Edit

It is unclear what you mean, "work for alphabets"? If you want the 5th letter of the alphabet:

int i=5;
char c = 'A'-1 + i; // c is now 'E', the 5th letter.

Note that because in C/Ascii, A is considered the 0th letter of the alphabet, I do a minus-1 to compensate for the normally understood meaning of 5th letter.

Adjust as appropriate for your specific situation.
(and test-test-test! any code you write)

Get all unique values in a JavaScript array (remove duplicates)

Shortest solution with ES6: [...new Set( [1, 1, 2] )];

Or if you want to modify the Array prototype (like in the original question):

Array.prototype.getUnique = function() {
    return [...new Set( [this] )];
};

EcmaScript 6 is only partially implemented in modern browsers at the moment (Aug. 2015), but Babel has become very popular for transpiling ES6 (and even ES7) back to ES5. That way you can write ES6 code today!

If you're wondering what the ... means, it's called the spread operator. From MDN: «The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected». Because a Set is an iterable (and can only have unique values), the spread operator will expand the Set to fill the array.

Resources for learning ES6:

Unit testing with Spring Security

Without answering the question about how to create and inject Authentication objects, Spring Security 4.0 provides some welcome alternatives when it comes to testing. The @WithMockUser annotation enables the developer to specify a mock user (with optional authorities, username, password and roles) in a neat way:

@Test
@WithMockUser(username = "admin", authorities = { "ADMIN", "USER" })
public void getMessageWithMockUserCustomAuthorities() {
    String message = messageService.getMessage();
    ...
}

There is also the option to use @WithUserDetails to emulate a UserDetails returned from the UserDetailsService, e.g.

@Test
@WithUserDetails("customUsername")
public void getMessageWithUserDetailsCustomUsername() {
    String message = messageService.getMessage();
    ...
}

More details can be found in the @WithMockUser and the @WithUserDetails chapters in the Spring Security reference docs (from which the above examples were copied)

SQL LEFT-JOIN on 2 fields for MySQL

select a.ip, a.os, a.hostname, a.port, a.protocol,
       b.state
from a
left join b on a.ip = b.ip 
           and a.port = b.port

Android - running a method periodically using postDelayed() call

You should set andrid:allowRetainTaskState="true" to Launch Activity in Manifest.xml. If this Activty is not Launch Activity. you should set android:launchMode="singleTask" at this activity

WordPress asking for my FTP credentials to install plugins

If during installation of a plugin, Wordpress asks for your hostname or FTP details. Then follow these steps:

Login to your server and navigate to /var/www/html/wordpress/. Open wp-config.php and add this line after define(‘DB_COLLATE’)

define('FS_METHOD', 'direct');

If you get "Could not create directory" error. Give write permissions to your wordpress directory in recursive as

chmod -R go+w wordpress

NOTE. For security, revoke these permissions once you install a plugin as

chmod -R go-w wordpress

CSS rule to apply only if element has BOTH classes

Below applies to all tags with the following two classes

.abc.xyz {  
  width: 200px !important;
}

applies to div tags with the following two classes

div.abc.xyz {  
  width: 200px !important;
}

If you wanted to modify this using jQuery

$(document).ready(function() {
  $("div.abc.xyz").width("200px");
});

error: expected primary-expression before ')' token (C)

You're passing a type as an argument, not an object. You need to do characterSelection(screen, test); where test is of type SelectionneNonSelectionne.

How do I delete specific lines in Notepad++?

Investigate what is your EOL, \n or \r\n. Then replace .*#region.*\r\n with nothing in regexpr mode.

HTML: Select multiple as dropdown

Here is the documentation of <select>. You are using 2 attributes:

multiple
This Boolean attribute indicates that multiple options can be selected in the list. If it is not specified, then only one option can be selected at a time. When multiple is specified, most browsers will show a scrolling list box instead of a single line dropdown.

size
If the control is presented as a scrolling list box (e.g. when multiple is specified), this attribute represents the number of rows in the list that should be visible at one time. Browsers are not required to present a select element as a scrolled list box. The default value is 0.

As described in the docs. <select size="1" multiple> will render a List box only 1 line visible and a scrollbar. So you are loosing the dropdown/arrow with the multiple attribute.

WPF Datagrid set selected row

// In General to Access all rows //

foreach (var item in dataGrid1.Items)
{
    string str = ((DataRowView)dataGrid1.Items[1]).Row["ColumnName"].ToString();
}

//To Access Selected Rows //

private void dataGrid1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    try
    {
        string str = ((DataRowView)dataGrid1.SelectedItem).Row["ColumnName"].ToString();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

Is there a Google Voice API?

I needed a C# API and after spending hours looking for it (all I found was outdated and non-working) and unsuccessfully trying to port the PHP/Python/Java versions listed here (none worked either) I decided to create my own. It's SMS-only for now...

https://bitbucket.org/jitbit/sharpgooglevoice/wiki/Home

Get decimal portion of a number with JavaScript

This function splits float number into integers and returns it in array:

_x000D_
_x000D_
function splitNumber(num)
{
  num = ("0" + num).match(/([0-9]+)([^0-9]([0-9]+))?/);
  return [ ~~num[1], ~~num[3] ];
}

console.log(splitNumber(3.2));     // [ 3, 2 ]
console.log(splitNumber(123.456)); // [ 123, 456 ]
console.log(splitNumber(789));     // [ 789, 0 ]
console.log(splitNumber("test"));  // [ 0, 0 ]
_x000D_
_x000D_
_x000D_

You can extend it to only return existing numbers and null if no number exists:

_x000D_
_x000D_
function splitNumber(num)
{
  num = ("" + num).match(/([0-9]+)([^0-9]([0-9]+))?/);
  return [num ? ~~num[1] : null, num && num[3] !== undefined ? ~~num[3] : null];
}

console.log(splitNumber(3.2));     // [ 3, 2 ]
console.log(splitNumber(123.456)); // [ 123, 456 ]
console.log(splitNumber(789));     // [ 789, null ]
console.log(splitNumber("test"));  // [ null, null ]
_x000D_
_x000D_
_x000D_

Reversing an Array in Java

I would do something like this:

public int[] reverse3(int[] nums) {
  int[] numsReturn = new int[nums.length()]; 
  int count = nums.length()-1;
  for(int num : nums) {
    numsReturn[count] = num;
    count--;
  }
  return numsReturn;
}

Python import csv to list

Pandas is pretty good at dealing with data. Here is one example how to use it:

import pandas as pd

# Read the CSV into a pandas data frame (df)
#   With a df you can do many things
#   most important: visualize data with Seaborn
df = pd.read_csv('filename.csv', delimiter=',')

# Or export it in many ways, e.g. a list of tuples
tuples = [tuple(x) for x in df.values]

# or export it as a list of dicts
dicts = df.to_dict().values()

One big advantage is that pandas deals automatically with header rows.

If you haven't heard of Seaborn, I recommend having a look at it.

See also: How do I read and write CSV files with Python?

Pandas #2

import pandas as pd

# Get data - reading the CSV file
import mpu.pd
df = mpu.pd.example_df()

# Convert
dicts = df.to_dict('records')

The content of df is:

     country   population population_time    EUR
0    Germany   82521653.0      2016-12-01   True
1     France   66991000.0      2017-01-01   True
2  Indonesia  255461700.0      2017-01-01  False
3    Ireland    4761865.0             NaT   True
4      Spain   46549045.0      2017-06-01   True
5    Vatican          NaN             NaT   True

The content of dicts is

[{'country': 'Germany', 'population': 82521653.0, 'population_time': Timestamp('2016-12-01 00:00:00'), 'EUR': True},
 {'country': 'France', 'population': 66991000.0, 'population_time': Timestamp('2017-01-01 00:00:00'), 'EUR': True},
 {'country': 'Indonesia', 'population': 255461700.0, 'population_time': Timestamp('2017-01-01 00:00:00'), 'EUR': False},
 {'country': 'Ireland', 'population': 4761865.0, 'population_time': NaT, 'EUR': True},
 {'country': 'Spain', 'population': 46549045.0, 'population_time': Timestamp('2017-06-01 00:00:00'), 'EUR': True},
 {'country': 'Vatican', 'population': nan, 'population_time': NaT, 'EUR': True}]

Pandas #3

import pandas as pd

# Get data - reading the CSV file
import mpu.pd
df = mpu.pd.example_df()

# Convert
lists = [[row[col] for col in df.columns] for row in df.to_dict('records')]

The content of lists is:

[['Germany', 82521653.0, Timestamp('2016-12-01 00:00:00'), True],
 ['France', 66991000.0, Timestamp('2017-01-01 00:00:00'), True],
 ['Indonesia', 255461700.0, Timestamp('2017-01-01 00:00:00'), False],
 ['Ireland', 4761865.0, NaT, True],
 ['Spain', 46549045.0, Timestamp('2017-06-01 00:00:00'), True],
 ['Vatican', nan, NaT, True]]

AngularJS - convert dates in controller

All solutions here doesn't really bind the model to the input because you will have to change back the dateAsString to be saved as date in your object (in the controller after the form will be submitted).

If you don't need the binding effect, but just to show it in the input,

a simple could be:

<input type="date" value="{{ item.date | date: 'yyyy-MM-dd' }}" id="item_date" />

Then, if you like, in the controller, you can save the edited date in this way:

  $scope.item.date = new Date(document.getElementById('item_date').value).getTime();

be aware: in your controller, you have to declare your item variable as $scope.item in order for this to work.

XCOPY switch to create specified directory if it doesn't exist?

Answer to use "/I" is working but with little trick - in target you must end with character \ to tell xcopy that target is directory and not file!

Example:

xcopy "$(TargetDir)$(TargetName).dll" "$(SolutionDir)_DropFolder" /F /R /Y /I

does not work and return code 2, but this one:

xcopy "$(TargetDir)$(TargetName).dll" "$(SolutionDir)_DropFolder\" /F /R /Y /I

Command line arguments used in my sample:

/F - Displays full source & target file names

/R - This will overwrite read-only files

/Y - Suppresses prompting to overwrite an existing file(s)

/I - Assumes that destination is directory (but must ends with \)

Use string contains function in oracle SQL query

By lines I assume you mean rows in the table person. What you're looking for is:

select p.name
from   person p
where  p.name LIKE '%A%'; --contains the character 'A'

The above is case sensitive. For a case insensitive search, you can do:

select p.name
from   person p
where  UPPER(p.name) LIKE '%A%'; --contains the character 'A' or 'a'

For the special character, you can do:

select p.name
from   person p
where  p.name LIKE '%'||chr(8211)||'%'; --contains the character chr(8211)

The LIKE operator matches a pattern. The syntax of this command is described in detail in the Oracle documentation. You will mostly use the % sign as it means match zero or more characters.

How to set custom header in Volley Request

try this

{
    @Override
       public Map<String, String> getHeaders() throws AuthFailureError {
           String bearer = "Bearer ".concat(token);
            Map<String, String> headersSys = super.getHeaders();
            Map<String, String> headers = new HashMap<String, String>();
            headersSys.remove("Authorization");
            headers.put("Authorization", bearer);
            headers.putAll(headersSys);
            return headers;
       }
};

Echo off but messages are displayed

@echo off
// quote the path or else it won't work if there are spaces in the path
SET INSTALL_PATH="c:\\etc etc\\test";
if exist %INSTALL_PATH% (
   //
   echo 222;
)

How to call VS Code Editor from terminal / command line

Step 1: create a .bat file with the name you want e.g vscode.bat Step 2: Write your path to Visual Studio Code Step 3: Save it in C:\Windows\System32 directory

**
C:
cd Users\Bino\AppData\Local\Programs\Microsoft VS Code
Code.exe**

Step 4: You can call visual studio code from any where by typing "vscode" which is the name of your bat file

File name without extension name VBA

This gets the file type as from the last character (so avoids the problem with dots in file names)

Function getFileType(fn As String) As String

''get last instance of "." (full stop) in a filename then returns the part of the filename starting at that dot to the end
Dim strIndex As Integer
Dim x As Integer
Dim myChar As String

strIndex = Len(fn)
For x = 1 To Len(fn)

    myChar = Mid(fn, strIndex, 1)

    If myChar = "." Then
        Exit For
    End If

    strIndex = strIndex - 1

Next x

getFileType = UCase(Mid(fn, strIndex, Len(fn) - x + 1))

End Function

Add an index (numeric ID) column to large data frame

You can add a sequence of numbers very easily with

data$ID <- seq.int(nrow(data))

If you are already using library(tidyverse), you can use

data <- tibble::rowid_to_column(data, "ID")

SQL Count for each date

You can use:

Select
     count(created_date) as counted_leads,
     created_date as count_date
from
     table
group by
     created_date

Python extending with - using super() Python 3 vs Python 2

Just to have a simple and complete example for Python 3, which most people seem to be using now.

class MySuper(object):
    def __init__(self,a):
        self.a = a

class MySub(MySuper):
    def __init__(self,a,b):
        self.b = b
        super().__init__(a)

my_sub = MySub(42,'chickenman')
print(my_sub.a)
print(my_sub.b)

gives

42
chickenman