Programs & Examples On #Putchar

Anything related to C or C++ standard library functions `putchar` (C) or `std::putchar` (C++). These functions are used to write a single character to the standard output stream `stdout`.

C - Convert an uppercase letter to lowercase

In ASCII the upper and lower case alphabet is 0x20 (in ASCII 0x20 is space ' ') apart from each other, so this is another way to do it.

int lower(int a) 
    return a | ' ';  

How to correctly save instance state of Fragments in back stack?

To correctly save the instance state of Fragment you should do the following:

1. In the fragment, save instance state by overriding onSaveInstanceState() and restore in onActivityCreated():

class MyFragment extends Fragment {

    public void onActivityCreated(Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            //Restore the fragment's state here
    public void onSaveInstanceState(Bundle outState) {

        //Save the fragment's state here


2. And important point, in the activity, you have to save the fragment's instance in onSaveInstanceState() and restore in onCreate().

class MyActivity extends Activity {

    private MyFragment 

    public void onCreate(Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            //Restore the fragment's instance
            mMyFragment = getSupportFragmentManager().getFragment(savedInstanceState, "myFragmentName");

    protected void onSaveInstanceState(Bundle outState) {

        //Save the fragment's instance
        getSupportFragmentManager().putFragment(outState, "myFragmentName", mMyFragment);


Hope this helps.

`getchar()` gives the same output as the input string

Strings, by C definition, are terminated by '\0'. You have no "C strings" in your program.

Your program reads characters (buffered till ENTER) from the standard input (the keyboard) and writes them back to the standard output (the screen). It does this no matter how many characters you type or for how long you do this.

To stop the program you have to indicate that the standard input has no more data (huh?? how can a keyboard have no more data?).

You simply press Ctrl+D (Unix) or Ctrl+Z (Windows) to pretend the file has reached its end.
Ctrl+D (or Ctrl+Z) are not really characters in the C sense of the word.

If you run your program with input redirection, the EOF is the actual end of file, not a make belief one
./a.out < source.c

How to avoid pressing Enter with getchar() for reading a single character only?

I/O is an operating system function. In many cases, the operating system won't pass typed character to a program until ENTER is pressed. This allows the user to modify the input (such as backspacing and retyping) before sending it to the program. For most purposes, this works well, presents a consistent interface to the user, and relieves the program from having to deal with this. In some cases, it's desirable for a program to get characters from keys as they are pressed.

The C library itself deals with files, and doesn't concern itself with how data gets into the input file. Therefore, there's no way in the language itself to get keys as they are pressed; instead, this is platform-specific. Since you haven't specified OS or compiler, we can't look it up for you.

Also, the standard output is normally buffered for efficiency. This is done by the C libraries, and so there is a C solution, which is to fflush(stdout); after each character written. After that, whether the characters are displayed immediately is up to the operating system, but all the OSes I'm familiar with will display the output immediately, so that's not normally a problem.

Rerouting stdin and stdout from C

This is a modified version of Tim Post's method; I used /dev/tty instead of /dev/stdout. I don't know why it doesn't work with stdout (which is a link to /proc/self/fd/1):


By using /dev/tty the output is redirected to the terminal from where the app was launched.

Hope this info is useful.

How do I get the current username in .NET using C#?

I totally second the other answers, but I would like to highlight one more method which says

String UserName = Request.LogonUserIdentity.Name;

The above method returned me the username in the format: DomainName\UserName. For example, EUROPE\UserName

Which is different from:

String UserName = Environment.UserName;

Which displayed in the format: UserName

And finally:

String UserName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;

which gave: NT AUTHORITY\IUSR (while running the application on IIS server) and DomainName\UserName (while running the application on a local server).

cartesian product in pandas

Minimal code needed for this one. Create a common 'key' to cartesian merge the two:

df1['key'] = 0
df2['key'] = 0

df_cartesian = df1.merge(df2, how='outer')

How to export non-exportable private key from store

This worked for me on Windows Server 2012 - I needed to export a non-exportable certificate to setup another ADFS server and this did the trick. Remember to use the jailbreak instructions above i.e.:

crypto::certificates /export /systemstore:CERT_SYSTEM_STORE_LOCAL_MACHINE

How do I compare version numbers in Python?

... and getting back to easy ... for simple scripts you can use:

import sys
needs = (3, 9) # or whatever
pvi = sys.version_info.major, sys.version_info.minor    

later in your code

    assert pvi >= needs
    print("will fail!")
    # etc.

How to use a keypress event in AngularJS?

You can also apply it to a controller on a parent element. This example can be used to highlight a row in a table by pressing up/down arrow keys.

app.controller('tableCtrl', [ '$scope', '$element', function($scope, $element) {
  $scope.index = 0; // row index
  $ = []; // array of items
  $scope.keypress = function(offset) {
    console.log('keypress', offset);
    var i = $scope.index + offset;
    if (i < 0) { i = $ - 1; }
    if (i >= $ { i = 0; }
  $element.bind("keydown keypress", function (event) {
    console.log('keypress', event, event.which);
    if(event.which === 38) { // up
    } else if (event.which === 40) { // down
    } else {

<table class="table table-striped" ng-controller="tableCtrl">
        <th ng-repeat="(key, value) in data[0]">{{key}}</th>
    <tr ng-repeat="row in data track by $index" ng-click="draw($index)" ng-class="$index == index ? 'info' : ''">
        <td ng-repeat="(key, value) in row">{{value}}</td>

I'm trying to use python in powershell

For a permanent solution I found the following worked:

[Environment]::SetEnvironmentVariable("Path", "$env:Path;C:\Python 3.5")

Can't import org.apache.http.HttpResponse in Android Studio

Main build.gradle - /build.gradle

buildscript {
    dependencies {
        classpath '' 
        // Versions:

Module specific build.gradle - /app/build.gradle

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"
    useLibrary 'org.apache.http.legacy'

CRON job to run on the last day of the month

Some cron implementations support the "L" flag to represent the last day of the month.

If you're lucky to be using one of those implementations, it's as simple as:

0 55 23 L * ?

That will run at 11:55 pm on the last day of every month.

How to convert empty spaces into null values, using SQL Server?

SQL Server ignores trailing whitespace when comparing strings, so ' ' = ''. Just use the following query for your update

UPDATE table
SET col1 = NULL
WHERE col1 = ''

NULL values in your table will stay NULL, and col1s with any number on space only characters will be changed to NULL.

If you want to do it during your copy from one table to another, use this:

INSERT INTO newtable ( col1, othercolumn )
   NULLIF(col1, ''),
FROM table

Which keycode for escape key with jQuery

Your code works just fine. It's most likely the window thats not focused. I use a similar function to close iframe boxes etc.


    // Set focus


$(document).keypress(function(e) {

    // Enable esc
    if (e.keyCode == 27) {


Java Wait and Notify: IllegalMonitorStateException

You're calling both wait and notifyAll without using a synchronized block. In both cases the calling thread must own the lock on the monitor you call the method on.

From the docs for notify (wait and notifyAll have similar documentation but refer to notify for the fullest description):

This method should only be called by a thread that is the owner of this object's monitor. A thread becomes the owner of the object's monitor in one of three ways:

  • By executing a synchronized instance method of that object.
  • By executing the body of a synchronized statement that synchronizes on the object.
  • For objects of type Class, by executing a synchronized static method of that class.

Only one thread at a time can own an object's monitor.

Only one thread will be able to actually exit wait at a time after notifyAll as they'll all have to acquire the same monitor again - but all will have been notified, so as soon as the first one then exits the synchronized block, the next will acquire the lock etc.

Finding all possible permutations of a given string in python

why do you not simple do:

from itertools import permutations
perms = [''.join(p) for p in permutations(['s','t','a','c','k'])]
print perms
print len(perms)
print len(set(perms))

you get no duplicate as you can see :

 ['stack', 'stakc', 'stcak', 'stcka', 'stkac', 'stkca', 'satck', 'satkc', 
'sactk', 'sackt', 'saktc', 'sakct', 'sctak', 'sctka', 'scatk', 'scakt', 'sckta',
 'sckat', 'sktac', 'sktca', 'skatc', 'skact', 'skcta', 'skcat', 'tsack', 
'tsakc', 'tscak', 'tscka', 'tskac', 'tskca', 'tasck', 'taskc', 'tacsk', 'tacks', 
'taksc', 'takcs', 'tcsak', 'tcska', 'tcask', 'tcaks', 'tcksa', 'tckas', 'tksac', 
'tksca', 'tkasc', 'tkacs', 'tkcsa', 'tkcas', 'astck', 'astkc', 'asctk', 'asckt', 
'asktc', 'askct', 'atsck', 'atskc', 'atcsk', 'atcks', 'atksc', 'atkcs', 'acstk', 
'acskt', 'actsk', 'actks', 'ackst', 'ackts', 'akstc', 'aksct', 'aktsc', 'aktcs', 
'akcst', 'akcts', 'cstak', 'cstka', 'csatk', 'csakt', 'cskta', 'cskat', 'ctsak', 
'ctska', 'ctask', 'ctaks', 'ctksa', 'ctkas', 'castk', 'caskt', 'catsk', 'catks', 
'cakst', 'cakts', 'cksta', 'cksat', 'cktsa', 'cktas', 'ckast', 'ckats', 'kstac', 
'kstca', 'ksatc', 'ksact', 'kscta', 'kscat', 'ktsac', 'ktsca', 'ktasc', 'ktacs', 
'ktcsa', 'ktcas', 'kastc', 'kasct', 'katsc', 'katcs', 'kacst', 'kacts', 'kcsta', 
'kcsat', 'kctsa', 'kctas', 'kcast', 'kcats']
    [Finished in 0.3s]

Default string initialization: NULL or Empty?

This is actually a gaping hole in the C# language. There is no way to define a string that cannot be null. This causes problems as simple as the one you are describing, which forces programmers to make a decision they shouldn't have to make, since in many cases NULL and String.Empty mean the same thing. That, in turn, can later force other programmers to have to handle both NULL and String.Empty, which is annoying.

A bigger problem is that databases allow you to define fields that map to a C# string, but database fields can be defined as NOT NULL. So, there is no way to accurately represent, say, a varchar( 100 ) NOT NULL field in SQL Server using a C# type.

Other languages, such as Spec #, do allow this.

In my opinion, C#'s inability to define a string that doesn't allow null is just as bad as its previous inability to define an int that does allow null.

To completely answer your question: I always use empty string for default initialization because it is more similar to how database data types work. (Edit: This statement was very unclear. It should read "I use empty string for default initialization when NULL is a superfluous state, much in the same way I set up a database column as NOT NULL if NULL would be a superfluous state. Similarly, many of my DB columns are set up as NOT NULL, so when I bring those into a C# string, the string will be empty or have a value, but will never be NULL. In other words, I only initialize a string to NULL if null has a meaning that is distinct from the meaning of String.Empty, and I find that case to be less than common (but people here have given legitimate examples of this case).")

Get decimal portion of a number with JavaScript

You could convert it to a string and use the replace method to replace the integer part with zero, then convert the result back to a number :

var number = 123.123812,
    decimals = +number.toString().replace(/^[^\.]+/,'0');

How can I convert JSON to a HashMap using Gson?

I have overcome a similar problem with a Custom JsonDeSerializer. I tried to make it a bit generic but still not enough. It is a solution though that fits my needs.

First of all you need to implement a new JsonDeserializer for Map objects.

public class MapDeserializer<T, U> implements JsonDeserializer<Map<T, U>>

And the deserialize method will look similar to this:

public Map<T, U> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {

        if (!json.isJsonObject()) {
            return null;

        JsonObject jsonObject = json.getAsJsonObject();
        Set<Entry<String, JsonElement>> jsonEntrySet = jsonObject.entrySet();
        Map<T, U> deserializedMap = new HashMap<T, U>();

        for (Entry<java.lang.String, JsonElement> entry : jsonEntrySet) {
            try {
                U value = context.deserialize(entry.getValue(), getMyType());
                deserializedMap.put((T) entry.getKey(), value);
            } catch (Exception ex) {
      "Could not deserialize map.", ex);

        return deserializedMap;

The con with this solution, is that my Map's key is always of Type "String". However by chaning some things someone can make it generic. In addition, i need to say, that the value's class should be passed in the constructor. So the method getMyType() in my code returns the type of the Map's values, which was passed in the constructor.

You can reference this post How do I write a custom JSON deserializer for Gson? in order to learn more about custom deserializers.

Count how many files in directory PHP

Working Demo


$directory = "../images/team/harry/"; // dir location
if (glob($directory . "*.*") != false)
 $filecount = count(glob($directory . "*.*"));
 echo $filecount;
 echo 0;


PostgreSQL: Which version of PostgreSQL am I running?

For the current version of PgAdmin: 4.16 at the time of writing.

  1. Select the DB whose version you need.
  2. Click on the properties tab in the right pane.

See screenshot below: PGAdmin 4.16 showing DB version 10.10

What does -1 mean in numpy reshape?

It simply means that you are not sure about what number of rows or columns you can give and you are asking numpy to suggest number of column or rows to get reshaped in.

numpy provides last example for -1

check below code and its output to better understand about (-1):


import numpy
a = numpy.matrix([[1, 2, 3, 4], [5, 6, 7, 8]])
print("Without reshaping  -> ")
b = numpy.reshape(a, -1)
print("HERE We don't know about what number we should give to row/col")
print("Reshaping as (a,-1)")
c = numpy.reshape(a, (-1,2))
print("HERE We just know about number of columns")
print("Reshaping as (a,(-1,2))")
d = numpy.reshape(a, (2,-1))
print("HERE We just know about number of rows")
print("Reshaping as (a,(2,-1))")


Without reshaping  -> 
[[1 2 3 4]
 [5 6 7 8]]
HERE We don't know about what number we should give to row/col
Reshaping as (a,-1)
[[1 2 3 4 5 6 7 8]]
HERE We just know about number of columns
Reshaping as (a,(-1,2))
[[1 2]
 [3 4]
 [5 6]
 [7 8]]
HERE We just know about number of rows
Reshaping as (a,(2,-1))
[[1 2 3 4]
 [5 6 7 8]]

int value under 10 convert to string two digit number

I will start my answer saying that most of previous answers were perfectly good answers at the time of writing them. So, thank you to them who wrote them.

Now, you can also use String Interpolation for same solution.

Edit: Adding this explanation after receiving a perfectively valid constructive comment from Heretic Monkey. I have preferred to use .ToString whenever I had need to convert an integer to string and not add the result to any other string. And, I have preferred to use interpolation whenever I had need to combine string(s) and an integer, like in below examples.

String Interpolation







How to access accelerometer/gyroscope data from Javascript?

There are currently three distinct events which may or may not be triggered when the client devices moves. Two of them are focused around orientation and the last on motion:

  • ondeviceorientation is known to work on the desktop version of Chrome, and most Apple laptops seems to have the hardware required for this to work. It also works on Mobile Safari on the iPhone 4 with iOS 4.2. In the event handler function, you can access alpha, beta, gamma values on the event data supplied as the only argument to the function.

  • onmozorientation is supported on Firefox 3.6 and newer. Again, this is known to work on most Apple laptops, but might work on Windows or Linux machines with accelerometer as well. In the event handler function, look for x, y, z fields on the event data supplied as first argument.

  • ondevicemotion is known to work on iPhone 3GS + 4 and iPad (both with iOS 4.2), and provides data related to the current acceleration of the client device. The event data passed to the handler function has acceleration and accelerationIncludingGravity, which both have three fields for each axis: x, y, z

The "earthquake detecting" sample website uses a series of if statements to figure out which event to attach to (in a somewhat prioritized order) and passes the data received to a common tilt function:

if (window.DeviceOrientationEvent) {
    window.addEventListener("deviceorientation", function () {
        tilt([event.beta, event.gamma]);
    }, true);
} else if (window.DeviceMotionEvent) {
    window.addEventListener('devicemotion', function () {
        tilt([event.acceleration.x * 2, event.acceleration.y * 2]);
    }, true);
} else {
    window.addEventListener("MozOrientation", function () {
        tilt([orientation.x * 50, orientation.y * 50]);
    }, true);

The constant factors 2 and 50 are used to "align" the readings from the two latter events with those from the first, but these are by no means precise representations. For this simple "toy" project it works just fine, but if you need to use the data for something slightly more serious, you will have to get familiar with the units of the values provided in the different events and treat them with respect :)

How to set a Fragment tag by code?

This is the best way I have found :

   public class MainActivity extends AppCompatActivity {
    public void onCreate(Bundle savedInstanceState) {
        if (savedInstanceState == null) {
          // Let's first dynamically add a fragment into a frame container
              replace(, new DemoFragment(), "SOMETAG").
          // Now later we can lookup the fragment by tag
          DemoFragment fragmentDemo = (DemoFragment) 

Replace last occurrence of a string in a string

$string = "picture_0007_value";
$findChar =strrpos($string,"_");
if($findChar !== FALSE) {

echo $string;

Apart from the mistakes in the code, Faruk Unal has the best anwser. One function does the trick.

Importing large sql file to MySql via command line

You can import .sql file using the standard input like this:

mysql -u <user> -p<password> <dbname> < file.sql

Note: There shouldn't space between <-p> and <password>


Note for suggested edits: This answer was slightly changed by suggested edits to use inline password parameter. I can recommend it for scripts but you should be aware that when you write password directly in the parameter (-p<password>) it may be cached by a shell history revealing your password to anyone who can read the history file. Whereas -p asks you to input password by standard input.

Unable to start Service Intent

I hope I can help someone with this info as well: I moved my service class into another package and I fixed the references. The project was perfectly fine, BUT the service class could not be found by the activity.

By watching the log in logcat I noticed the warning about the issue: the activity could not find the service class, but the funny thing was that the package was incorrect, it contained a "/" char. The compiler was looking for


instead of


I moved the service class out from the package and back in and everything worked just fine.

Can a JSON value contain a multiline string

Not pretty good solution, but you can try the hjson tool. It allows you to write text multi-lined in editor and then converts it to the proper valid JSON format.

Note: it adds '\n' characters for the new lines, but you can simply delete them in any text editor with the "Replace all.." function.

Getting parts of a URL (Regex)

I tried this regex for parsing url partitions:




Group 1.    0-7 https:/
Group 2.    0-5 https
Group 3.    8-22
Group 6.    22-50   /my/path/sample/asd-dsa/this
Group 7.    22-46   /my/path/sample/asd-dsa/
Group 8.    46-50   this
Group 9.    50-74   ?key1=value1&key2=value2
Group 10.   51-74   key1=value1&key2=value2

C++ equivalent of Java's toString?

As an extension to what John said, if you want to extract the string representation and store it in a std::string do this:

#include <sstream>    
// ...
// Suppose a class A
A a;
std::stringstream sstream;
sstream << a;
std::string s = sstream.str(); // or you could use sstream >> s but that would skip out whitespace

std::stringstream is located in the <sstream> header.

How can I remove a style added with .css() function?

you remove style using

removeAttr( 'style' );

error: package javax.servlet does not exist

The answer provided by @Matthias Herlitzius is mostly correct. Just for further clarity.

The servlet-api jar is best left up to the server to manage see here for detail

With that said, the dependency to add may vary according to your server/container. For example in Wildfly the dependency would be


So becareful to check how your container has provided the servlet implementation.

How to get a substring of text?

if you need it in rails you can use first (source code)

'1234567890'.first(5) # => "12345"

there is also last (source code)

'1234567890'.last(2) # => "90"

alternatively check from/to (source code):

"hello".from(1).to(-2) # => "ell"

How to verify Facebook access token?

I found this official tool from facebook developer page, this page will you following information related to access token - App ID, Type, App-Scoped,User last installed this app via, Issued, Expires, Data Access Expires, Valid, Origin, Scopes. Just need access token.

Convert Pandas DataFrame to JSON format

In newer versions of pandas (0.20.0+, I believe), this can be done directly:

df.to_json('temp.json', orient='records', lines=True)

Direct compression is also possible:

df.to_json('temp.json.gz', orient='records', lines=True, compression='gzip')

OpenVPN failed connection / All TAP-Win32 adapters on this system are currently in use

I found a solution to this. It's bloody witchcraft, but it works.

When you install the client, open Control Panel > Network Connections.

You'll see a disabled network connection that was added by the TAP installer (Local Area Connection 3 or some such).

Right Click it, click Enable.

The device will not reset itself to enabled, but that's ok; try connecting w/ the client again. It'll work.

Python: Figure out local timezone

tzlocal from dateutil.

Code example follows. Last string suitable for use in filenames.

>>> from datetime import datetime
>>> from import tzlocal
>>> str(
'2015-04-01 11:19:47.980883-07:00'
>>> str(' ','-').replace(':','').replace('.','-')

Add day(s) to a Date object

Note : Use it if calculating / adding days from current date.

Be aware: this answer has issues (see comments)

var myDate = new Date();
myDate.setDate(myDate.getDate() + AddDaysHere);

It should be like

var newDate = new Date(date.setTime( date.getTime() + days * 86400000 ));

How can I use a JavaScript variable as a PHP variable?

You can do what you want, but not like that. What you need to do is make an AJAX request from JavaScript back to the server where a separate PHP script can do the database operation.

Linux delete file with size 0

For a non-recursive delete (using du and awk):

rm `du * | awk '$1 == "0" {print $2}'`

How to obtain the chat_id of a private Telegram channel?

The easiest way is to invite @get_id_bot in your chat and then type:

/my_id @get_id_bot

Inside your chat

Auto submit form on page load

This is the way it worked for me, because with other methods the form was sent empty:

<form name="yourform" id="yourform" method="POST" action="yourpage.html">
    <input type=hidden name="data" value="yourdata">
    <input type="submit" id="send" name="send" value="Send">
    document.addEventListener("DOMContentLoaded", function(event) {

RESTful Authentication via Spring

You might consider Digest Access Authentication. Essentially the protocol is as follows:

  1. Request is made from client
  2. Server responds with a unique nonce string
  3. Client supplies a username and password (and some other values) md5 hashed with the nonce; this hash is known as HA1
  4. Server is then able to verify client's identity and serve up the requested materials
  5. Communication with the nonce can continue until the server supplies a new nonce (a counter is used to eliminate replay attacks)

All of this communication is made through headers, which, as jmort253 points out, is generally more secure than communicating sensitive material in the url parameters.

Digest Access Authentication is supported by Spring Security. Notice that, although the docs say that you must have access to your client's plain-text password, you can successfully authenticate if you have the HA1 hash for your client.

PHPExcel set border and format for all sheets in spreadsheet

for ($s=65; $s<=90; $s++) {
    //echo chr($s);

How to check string length with JavaScript

As for the question which event you should use for this: use the input event, and fall back to keyup/keydown in older browsers.

Here’s an example, DOM0-style:

someElement.oninput = function() {
  this.onkeydown = null;
  // Your code goes here
someElement.onkeydown = function() {
  // Your code goes here

The other question is how to count the number of characters in the string. Depending on your definition of “character”, all answers posted so far are incorrect. The string.length answer is only reliable when you’re certain that only BMP Unicode symbols will be entered. For example, 'a'.length == 1, as you’d expect.

However, for supplementary (non-BMP) symbols, things are a bit different. For example, ''.length == 2, even though there’s only one Unicode symbol there. This is because JavaScript exposes UCS-2 code units as “characters”.

Luckily, it’s still possible to count the number of Unicode symbols in a JavaScript string through some hackery. You could use Punycode.js’s utility functions to convert between UCS-2 strings and Unicode code points for this:

// `String.length` replacement that only counts full Unicode characters
punycode.ucs2.decode('a').length; // 1
punycode.ucs2.decode('').length; // 1 (note that `''.length == 2`!)

P.S. I just noticed the counter script that Stack Overflow uses gets this wrong. Try entering , and you’ll see that it (incorrectly) counts as two characters.

Why am I getting an Exception with the message "Invalid setup on a non-virtual (overridable in VB) member..."?

Moq cannot mock non-virtual methods and sealed classes. While running a test using mock object, MOQ actually creates an in-memory proxy type which inherits from your "XmlCupboardAccess" and overrides the behaviors that you have set up in the "SetUp" method. And as you know in C#, you can override something only if it is marked as virtual which isn't the case with Java. Java assumes every non-static method to be virtual by default.

Another thing I believe you should consider is introducing an interface for your "CupboardAccess" and start mocking the interface instead. It would help you decouple your code and have benefits in the longer run.

Lastly, there are frameworks like : TypeMock and JustMock which work directly with the IL and hence can mock non-virtual methods. Both however, are commercial products.

Encoding an image file with base64

I'm not sure I understand your question. I assume you are doing something along the lines of:

import base64

with open("yourfile.ext", "rb") as image_file:
    encoded_string = base64.b64encode(

You have to open the file first of course, and read its contents - you cannot simply pass the path to the encode function.

Edit: Ok, here is an update after you have edited your original question.

First of all, remember to use raw strings (prefix the string with 'r') when using path delimiters on Windows, to prevent accidentally hitting an escape character. Second, PIL's either accepts a filename, or a file-like (that is, the object has to provide read, seek and tell methods).

That being said, you can use cStringIO to create such an object from a memory buffer:

import cStringIO
import PIL.Image

# assume data contains your decoded image
file_like = cStringIO.StringIO(data)

img =

Amazon S3 exception: "The specified key does not exist"

For me, the object definitely existed and was uploaded correctly, however, its s3 url still threw the same error:

<Message>The specified key does not exist.</Message>

I found out that the reason was because my filename contained a # symbol, and I guess certain characters or symbols will also cause this error.

Removing this character and generating the new s3 url resolved my issue.

What is the correct wget command syntax for HTTPS with username and password?

By specifying the option --user and --ask-password wget will ask for the credentials. Below is an example. Change the username and download link to your needs.

wget --user=username --ask-password

JavaScript - populate drop down list with array

<form id="myForm">
<select id="selectNumber">
    <option>Choose a number</option>
        var myArray = new Array("1", "2", "3", "4", "5" . . . . . "N");
        for(i=0; i<myArray.length; i++) {  
            document.write('<option value="' + myArray[i] +'">' + myArray[i] + '</option>');

How to convert text to binary code in JavaScript?

What you should do is convert every char using charCodeAt function to get the Ascii Code in decimal. Then you can convert it to Binary value using toString(2):


<input id="ti1" value ="TEST"/>
<input id="ti2"/>
<button onClick="convert();">Convert!</button>


function convert() {
  var output = document.getElementById("ti2");
  var input = document.getElementById("ti1").value;
  output.value = "";
  for (var i = 0; i < input.length; i++) {
      output.value += input[i].charCodeAt(0).toString(2) + " ";

And here's a fiddle:

Is there a way to crack the password on an Excel VBA Project?

Tom - I made a schoolboy error initially as I didn't watch the byte size and instead I copied and pasted from the "CMG" set up to the subsequent entry. This was two different text sizes between the two files, though, and I lost the VBA project just as Stewbob warned.

Using HxD, there is a counter tracking how much file you're selecting. Copy starting from CMG until the counter reads 8F (hex for 143) and likewise when pasting into the locked file - I ended up with twice the number of "..." at the end of the paste, which looked odd somehow and felt almost unnatural, but it worked.

I don't know if it is crucial, but I made sure I shut both the hex editor and excel down before reopening the file in Excel. I then had to go through the menus to open the VB Editor, into VBProject Properties and entered in the 'new' password to unlock the code.

I hope this helps.

memory error in python

you could try to create the same script that popups that error, dividing the script into several script by importing from external script. Example, expect an error Memory error, so i divide into several scripts all of them have to get into a folder "hellohello" into that folder create into init write import h,e,ll,o and then on ide you write import hellohello

How to ensure a <select> form field is submitted when it is disabled?

I`ve been looking for a solution for this, and since i didnt find a solution in this thread i did my own.

// With jQuery
$('#selectbox').focus(function(e) {

Simple, you just blur the field when you focus on it, something like disabling it, but you actually send its data.

Set default option in mat-select

Normally you are going to do this in your template with FormGroup, Reactive Forms, etc...

    this.myForm ={
      title: ['', Validators.required],
      description: ['', Validators.required],
      isPublished: ['false',Validators.required]

upgade python version using pip

Basically, pip comes with python itself.Therefore it carries no meaning for using pip itself to install or upgrade python. Thus,try to install python through installer itself,visit the site "" for more help. Thank you.

Enum "Inheritance"

The short answer is no. You can play a bit, if you want:

You can always do something like this:

private enum Base

private enum Consume
    A = Base.A,
    B = Base.B,
    C = Base.C,

But, it doesn't work all that great because Base.A != Consume.A

You can always do something like this, though:

public static class Extensions
    public static T As<T>(this Consume c) where T : struct
        return (T)System.Enum.Parse(typeof(T), c.ToString(), false);

In order to cross between Base and Consume...

You could also cast the values of the enums as ints, and compare them as ints instead of enum, but that kind of sucks too.

The extension method return should type cast it type T.

Python base64 data decode

import base64
coded_string = '''Q5YACgA...'''

worked for me. At the risk of pasting an offensively-long result, I got:

>>> base64.b64decode(coded_string)
2: 'C\x96\x00\n\x00\x00\x00\x00C\x96\x00\x1b\x00\x00\x00\x00C\x96\x00-\x00\x00\x00\x00C\x96\x00?\x00\x00\x00\x00C\x96\x07M\x00\x00\x00\x00C\x96\x07_\x00\x00\x00\x00C\x96\x07p\x00\x00\x00\x00C\x96\x07\x82\x00\x00\x00\x00C\x96\x07\x94\x00\x00\x00\x00C\x96\x07\xa6Cq\xf0\x7fC\x96\x07\xb8DJ\x81\xc7C\x96\x07\xcaD\xa5\x9dtC\x96\x07\xdcD\xb6\x97\x11C\x96\x07\xeeD\x8b\x8flC\x96\x07\xffD\x03\xd4\xaaC\x96\x08\x11B\x05&\xdcC\x96\x08#\x00\x00\x00\x00C\x96\x085C\x0c\xc9\xb7C\x96\x08GCy\xc0\xebC\x96\x08YC\x81\xa4xC\x96\x08kC\x0f@\x9bC\x96\x08}\x00\x00\x00\x00C\x96\x08\x8e\x00\x00\x00\x00C\x96\x08\xa0\x00\x00\x00\x00C\x96\x08\xb2\x00\x00\x00\x00C\x96\x86\xf9\x00\x00\x00\x00C\x96\x87\x0b\x00\x00\x00\x00C\x96\x87\x1d\x00\x00\x00\x00C\x96\x87/\x00\x00\x00\x00C\x96\x87AA\x0b\xe7PC\x96\x87SCI\xf5gC\x96\x87eC\xd4J\xeaC\x96\x87wD\r\x17EC\x96\x87\x89D\x00F6C\x96\x87\x9bC\x9cg\xdeC\x96\x87\xadB\xd56\x0cC\x96\x87\xbf\x00\x00\x00\x00C\x96\x87\xd1\x00\x00\x00\x00C\x96\x87\xe3\x00\x00\x00\x00C\x96\x87\xf5\x00\x00\x00\x00C\x9cY}\x00\x00\x00\x00C\x9cY\x90\x00\x00\x00\x00C\x9cY\xa4\x00\x00\x00\x00C\x9cY\xb7\x00\x00\x00\x00C\x9cY\xcbC\x1f\xbd\xa3C\x9cY\xdeCCz{C\x9cY\xf1CD\x02\xa7C\x9cZ\x05C+\x9d\x97C\x9cZ\x18C\x03R\xe3C\x9cZ,\x00\x00\x00\x00C\x9cZ?
[stuff omitted as it exceeded SO's body length limits]

What problem are you having, specifically?

hadoop copy a local file system folder to HDFS

In Short

hdfs dfs -put <localsrc> <dest>

In detail with example:

Checking source and target before placing files into HDFS

[cloudera@quickstart ~]$ ll files/
total 132
-rwxrwxr-x 1 cloudera cloudera  5387 Nov 14 06:33 cloudera-manager
-rwxrwxr-x 1 cloudera cloudera  9964 Nov 14 06:33
-rw-rw-r-- 1 cloudera cloudera   664 Nov 14 06:33 derby.log
-rw-rw-r-- 1 cloudera cloudera 53655 Nov 14 06:33 enterprise-deployment.json
-rw-rw-r-- 1 cloudera cloudera 50515 Nov 14 06:33 express-deployment.json

[cloudera@quickstart ~]$ hdfs dfs -ls
Found 1 items
drwxr-xr-x   - cloudera cloudera          0 2017-11-14 00:45 .sparkStaging

Copy files HDFS using -put or -copyFromLocal command

[cloudera@quickstart ~]$ hdfs dfs -put files/ files

Verify the result in HDFS

[cloudera@quickstart ~]$ hdfs dfs -ls
Found 2 items
drwxr-xr-x   - cloudera cloudera          0 2017-11-14 00:45 .sparkStaging
drwxr-xr-x   - cloudera cloudera          0 2017-11-14 06:34 files

[cloudera@quickstart ~]$ hdfs dfs -ls files
Found 5 items
-rw-r--r--   1 cloudera cloudera       5387 2017-11-14 06:34 files/cloudera-manager
-rw-r--r--   1 cloudera cloudera       9964 2017-11-14 06:34 files/
-rw-r--r--   1 cloudera cloudera        664 2017-11-14 06:34 files/derby.log
-rw-r--r--   1 cloudera cloudera      53655 2017-11-14 06:34 files/enterprise-deployment.json
-rw-r--r--   1 cloudera cloudera      50515 2017-11-14 06:34 files/express-deployment.json

rbind error: "names do not match previous names"

The names of the first dataframe do not match the names of the second one. Just as the error message says.

> identical(names(xd.small[[1]]), names(xd.small[[2]]) )

If you do not care about the names of the 3rd or 4th columns of the second df, you can coerce them to be the same:

> names(xd.small[[1]]) <- names(xd.small[[2]]) 
> identical(names(xd.small[[1]]), names(xd.small[[2]]) )
[1] TRUE

Then things should proceed happily.

Count Vowels in String Python


vowels = "aioue"
text = input("Please enter your text: ")
count = 0

for i in text:
    if i in vowels:
        count += 1

print("There are", count, "vowels in your text")


Difference between HashMap, LinkedHashMap and TreeMap

These are different implementations of the same interface. Each implementation has some advantages and some disadvantages (fast insert, slow search) or vice versa.

For details look at the javadoc of TreeMap, HashMap, LinkedHashMap.

Action Image MVC3 Razor

You can create an extension method for HtmlHelper to simplify the code in your CSHTML file. You could replace your tags with a method like this:

// Sample usage in CSHTML
@Html.ActionImage("Edit", new { id = MyId }, "~/Content/Images/Image.bmp", "Edit")

Here is a sample extension method for the code above:

// Extension method
public static MvcHtmlString ActionImage(this HtmlHelper html, string action, object routeValues, string imagePath, string alt)
    var url = new UrlHelper(html.ViewContext.RequestContext);

    // build the <img> tag
    var imgBuilder = new TagBuilder("img");
    imgBuilder.MergeAttribute("src", url.Content(imagePath));
    imgBuilder.MergeAttribute("alt", alt);
    string imgHtml = imgBuilder.ToString(TagRenderMode.SelfClosing);

    // build the <a> tag
    var anchorBuilder = new TagBuilder("a");
    anchorBuilder.MergeAttribute("href", url.Action(action, routeValues));
    anchorBuilder.InnerHtml = imgHtml; // include the <img> tag inside
    string anchorHtml = anchorBuilder.ToString(TagRenderMode.Normal);

    return MvcHtmlString.Create(anchorHtml);

Port 80 is being used by SYSTEM (PID 4), what is that?

I've found out that "SQL Server Reporting Services (MSSQLSERVER)" starts automatically and listens on port 80.

I hope this helps.


How do I enable C++11 in gcc?

If you are using sublime then this code may work if you add it in build as code for building system. You can use this link for more information.

    "shell_cmd": "g++ \"${file}\" -std=c++1y -o \"${file_path}/${file_base_name}\"",
    "file_regex": "^(..[^:]*):([0-9]+):?([0-9]+)?:? (.*)$",
    "working_dir": "${file_path}",
    "selector": "source.c, source.c++",

            "name": "Run",
            "shell_cmd": "g++ \"${file}\" -std=c++1y -o \"${file_path}/${file_base_name}\" && \"${file_path}/${file_base_name}\""

How to pass argument to Makefile from command line?

don't try to do this

$ make action value1 value2

instead create script:

#! /bin/sh
# rebuild if necessary
# do action with arguments
action "$@"

and do this:

$ ./ value1 value2

for more explanation why do this and caveats of makefile hackery read my answer to another very similar but seemingly not duplicate question: Passing arguments to "make run"

Concatenating strings doesn't work as expected

I would do this:

std::string a("Hello ");
std::string b("World");
std::string c = a + b;

Which compiles in VS2008.

Java Object Null Check for method

You simply compare your object to null using the == (or !=) operator. E.g.:

public static double calculateInventoryTotal(Book[] books) {
    // First null check - the entire array
    if (books == null) {
        return 0;

    double total = 0;

    for (int i = 0; i < books.length; i++) {
        // second null check - each individual element
        if (books[i] != null) {
            total += books[i].getPrice();

    return total;

How to center a WPF app on screen?

Put this in your window constructor

WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;

.NET FrameworkSupported in: 4, 3.5, 3.0

.NET Framework Client ProfileSupported in: 4, 3.5 SP1

How to enable php7 module in apache?

I found the solution on the following thread :

Im my case not only the php wasn't working but phpmyadmin aswell i did step by step like that

sudo apt install php libapache2-mod-php
sudo apt install php7.0-mbstring
sudo a2dismod mpm_event
sudo a2enmod mpm_prefork
service apache2 restart

And then to:

gksu gedit /etc/apache2/apache2.conf

In the last line I do add Include /etc/phpmyadmin/apache.conf

That make a deal with all problems


If it solves your problem, up vote this solution in the original post.

c# why can't a nullable int be assigned null as a value

The problem isn't that null cannot be assigned to an int?. The problem is that both values returned by the ternary operator must be the same type, or one must be implicitly convertible to the other. In this case, null cannot be implicitly converted to int nor vice-versus, so an explict cast is necessary. Try this instead:

int? accom = (accomStr == "noval" ? (int?)null : Convert.ToInt32(accomStr));

HRESULT: 0x80131040: The located assembly's manifest definition does not match the assembly reference

I recently had this issue and I ran 'depends.exe' on the dll in question. It showed me that the dll was compiled in x86 while some of the dependencys were compiled in x64.

If you are still having troubles I would recommend using depends.exe.

Establish a VPN connection in cmd

Is Powershell an option?

Start Powershell:


Create the VPN Connection: Add-VpnConnection

Add-VpnConnection [-Name] <string> [-ServerAddress] <string> [-TunnelType <string> {Pptp | L2tp | Sstp | Ikev2 | Automatic}] [-EncryptionLevel <string> {NoEncryption | Optional | Required | Maximum}] [-AuthenticationMethod <string[]> {Pap | Chap | MSChapv2 | Eap}] [-SplitTunneling] [-AllUserConnection] [-L2tpPsk <string>] [-RememberCredential] [-UseWinlogonCredential] [-EapConfigXmlStream <xml>] [-Force] [-PassThru] [-WhatIf] [-Confirm] 

Edit VPN connections: Set-VpnConnection

Set-VpnConnection [-Name] <string> [[-ServerAddress] <string>] [-TunnelType <string> {Pptp | L2tp | Sstp | Ikev2 | Automatic}] [-EncryptionLevel <string> {NoEncryption | Optional | Required | Maximum}] [-AuthenticationMethod <string[]> {Pap | Chap | MSChapv2 | Eap}] [-SplitTunneling <bool>] [-AllUserConnection] [-L2tpPsk <string>] [-RememberCredential <bool>] [-UseWinlogonCredential <bool>] [-EapConfigXmlStream <xml>] [-PassThru] [-Force] [-WhatIf] [-Confirm]

Lookup VPN Connections: Get-VpnConnection

Get-VpnConnection [[-Name] <string[]>] [-AllUserConnection]

Connect: rasdial [connectionName]

rasdial connectionname [username [password | \]] [/domain:domain*] [/phone:phonenumber] [/callback:callbacknumber] [/phonebook:phonebookpath] [/prefixsuffix**]

You can manage your VPN connections with the powershell commands above, and simply use the connection name to connect via rasdial.

The results of Get-VpnConnection can be a little verbose. This can be simplified with a simple Select-Object filter:

Get-VpnConnection | Select-Object -Property Name

More information can be found here:

Simple function to sort an array of objects

I modified @Geuis 's answer by using lambda and convert it upper case first:

people.sort((a, b) => a.toLocaleUpperCase() < b.toLocaleUpperCase() ? -1 : 1);

How can I specify the required Node.js version in package.json?

Add the following to package.json:

  "engines": {
    "node": ">=10.0.0",
    "npm": ">=6.0.0"

Add the following to .npmrc (same directory as package.json):


JS: iterating over result of getElementsByClassName using Array.forEach

Is the result of getElementsByClassName an Array?


If not, what is it?

As with all DOM methods that return multiple elements, it is a NodeList, see

Understanding unique keys for array children in React.js

var TableRowItem = React.createClass({
  render: function() {

    var td = function() {
        return, i) {
          return <td key={i}>{[c]}</td>;
        }, this);

    return (
      <tr>{ td(this.props.item) }</tr>

This will sove the problem.

How to create local notifications?

- (void)applicationDidEnterBackground:(UIApplication *)application
   UILocalNotification *notification = [[UILocalNotification alloc]init];
   notification.repeatInterval = NSDayCalendarUnit;
   [notification setAlertBody:@"Hello world"];
   [notification setFireDate:[NSDate dateWithTimeIntervalSinceNow:1]];
   [notification setTimeZone:[NSTimeZone  defaultTimeZone]];
   [application setScheduledLocalNotifications:[NSArray arrayWithObject:notification]];

This is worked, but in iOS 8.0 and later, your application must register for user notifications using -[UIApplication registerUserNotificationSettings:] before being able to schedule and present UILocalNotifications, do not forget this.

Missing .map resource?

I had similar expirience like yours. I have Denwer server. When I loaded my local site without using via script src jquery.min.js file at index.php in Chrome I got error 500 in console. I resolved this problem simply - I disabled extension Wunderlist in Chrome and voila - I never see this error more. Although, No, I found this error again - when Wunderlist have been on again. So, check your extensions and try to disable all of them or some of them or one by one. Good luck!

JQuery Calculate Day Difference in 2 date textboxes

1) Html

<input type="text" id="firstDate" name="firstDate"/>
<input type="text" id="secondDate" name="secondDate"/>

2) Jquery


    onSelect: function () {

function myfunc(){
    var start= $("#firstDate").datepicker("getDate");
    var end= $("#secondDate").datepicker("getDate");
    days = (end- start) / (1000 * 60 * 60 * 24);

Jsfiddle working example here

Plotting time-series with Date labels on x-axis

Your code has lots of errors.

  • You are mixing up dm$Day and dm$day. Probably not the same thing
  • Your column headings are Date and Visits. So you would access them (I'm guessing) as dm$Date and dm$Visits
  • In the date field you have %Y-%m-%d this should be %m/%d/%Y

The following code should plot what you want:

dm$newday = as.Date(dm$Date, "%m/%d/%Y")
plot(dm$newday, dm$Visits) Need Text Box to Only Accept Numbers

You can do this with the use of Ascii integers. Put this code in the Textbox's Keypress event. e.KeyChar represents the key that's pressed. And the the built-in function Asc() converts it into its Ascii integer.

Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress

    '97 - 122 = Ascii codes for simple letters
    '65 - 90  = Ascii codes for capital letters
    '48 - 57  = Ascii codes for numbers

    If Asc(e.KeyChar) <> 8 Then
        If Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 57 Then
            e.Handled = True
        End If
    End If

End Sub

SVN Repository Search

I started using this tool

It works fine just lacking a visual UI, but is fast and somewhat maintained

JRE installation directory in Windows

where java works for me to list all java exe but java -verbose tells you which rt.jar is used and thus which jre (full path):

[Opened C:\Program Files\Java\jre6\lib\rt.jar]

Edit: win7 and java:

java version "1.6.0_20"
Java(TM) SE Runtime Environment (build 1.6.0_20-b02)
Java HotSpot(TM) 64-Bit Server VM (build 16.3-b01, mixed mode)

how to get all child list from Firebase android

Saving and Retriving data to - from Firebase ( deprecated ver 2.4.2 )

Firebase fb_parent = new Firebase("YOUR-FIREBASE-URL/");
Firebase fb_to_read = fb_parent.child("students/names");
Firebase fb_put_child = fb_to_read.push(); // REMEMBER THIS FOR PUSH METHOD

fb_put_child.setValue("Zacharia"); //OR fb_put_child.setValue(YOUR MODEL) 
fb_put_child.setValue("Joseph"); //OR fb_put_child.setValue(YOUR MODEL) 
fb_put_child.setValue("bla blaaa"); //OR fb_put_child.setValue(YOUR MODEL) 

    public void onDataChange(DataSnapshot result){
        List<String> lst = new ArrayList<String>(); // Result will be holded Here
        for(DataSnapshot dsp : result.getChildren()){
            lst.add(String.valueOf(dsp.getKey())); //add result into array list

for(String data:lst){ 

How to empty a file using Python

Opening a file creates it and (unless append ('a') is set) overwrites it with emptyness, such as this:

open(filename, 'w').close()

Find files and tar them (with spaces)

The best solution seem to be to create a file list and then archive files because you can use other sources and do something else with the list.

For example this allows using the list to calculate size of the files being archived:


backupFileName="backup-big-$(date +"%Y%m%d-%H%M")"


# Make a list of files/directories to archive
echo "" > $listOfFilesPath
echo "${backupRoot}/uploads" >> $listOfFilesPath
echo "${backupRoot}/extra/user/data" >> $listOfFilesPath
find "${backupRoot}/drupal_root/sites/" -name "files" -type d >> $listOfFilesPath

# Size calculation
cat $listOfFilesPath | while read nextFile;do
    if [ ! -z "$nextFile" ]; then
        du -sb "$nextFile"
done | awk '{size+=$1} END {print size}'

# Archive with progress
## simple with dump of all files currently archived
#tar -czvf $archivePath -T $listOfFilesPath
## progress bar
echo -e "\nRunning backup [source files are $sizeForShow MiB]\n"
tar -cPp -T $listOfFilesPath | pv -s $sizeForProgress | gzip > $archivePath

How do I convert a Swift Array to a String?

If you question is something like this: tobeFormattedString = ["a", "b", "c"] Output = "abc"


Dynamically replace img src attribute with jQuery

You need to check out the attr method in the jQuery docs. You are misusing it. What you are doing within the if statements simply replaces all image tags src with the string specified in the 2nd parameter.

A better way to approach replacing a series of images source would be to loop through each and check it's source.


$('img').each(function () {
  var curSrc = $(this).attr('src');
  if ( curSrc === '' ) {
      $(this).attr('src', '');
  if ( curSrc === '' ) {
      $(this).attr('src', '');

Floating point exception

This should give you a really good idea. Since a modulus is, in its basic sense, division with a remainder, something % 0 IS division by zero and as such, will trigger a SIGFPE being thrown.

ant build.xml file doesn't exist

There may be two situations.

  1. No build.xml is present in the current directory
  2. Your ant configuration file has diffrent name.

Please see and confim the same. In the case one you have to find where your build file is located and in the case 2, You will have to run command ant -f <your build file name>.

React Native: Possible unhandled promise rejection

catch function in your api should either return some data which could be handled by Api call in React class or throw new error which should be caught using a catch function in your React class code. Latter approach should be something like:

return fetch(url)
  return response.json();
  return {
    temperature: kelvinToF(json.main.temp),
    description: _.capitalize([0].description)
.catch(function(error) {
console.log('There has been a problem with your fetch operation: ' + error.message);
 // ADD THIS THROW error
  throw error;

Then in your React Class:

Api(region.latitude, region.longitude)
  .then((data) => {
     console.log("Api call error");

How to connect to SQL Server from another computer?

I'll edit my previous answer based on further info supplied. You can clearely ping the remote computer as you can use terminal services.

I've a feeling that port 1433 is being blocked by a firewall, hence your trouble. See TCP Ports Needed for Communication to SQL Server Through a Firewall by Microsoft.

Try using this application to ping your servers ip address and port 1433.

tcping your.server.ip.address 1433

And see if you get a "Port is open" response from tcping.

Ok, next to try is to check SQL Server. RDP onto the SQL Server computer. Start SSMS. Connect to the database. In object explorer (usually docked on the left) right click on the server and click properties.

alt text

Goto the Connections settings and make sure "Allow remote connections to this server" is ticket.

alt text

Can anyone recommend a simple Java web-app framework?

Try this:

It could do with some more features and improvements, but it is simple and it works.

Guzzlehttp - How get the body of a response from Guzzle 6?

For get response in JSON format :

  1.$response = (string) $res->getBody();
      $response =json_decode($response); // Using this you can access any key like below
     $key_value = $response->key_name; //access key  

  2. $response = json_decode($res->getBody(),true);
     $key_value =   $response['key_name'];//access key

Reading Properties file in Java

Specify the path starting from src as below:


SQL Server "cannot perform an aggregate function on an expression containing an aggregate or a subquery", but Sybase can

One option is to put the subquery in a LEFT JOIN:

select sum ( t.graduates ) - t1.summedGraduates 
from table as t
    left join 
        select sum ( graduates ) summedGraduates, id
        from table  
        where group_code not in ('total', 'others' )
        group by id 
    ) t1 on =
where t.group_code = 'total'
group by t1.summedGraduates 

Perhaps a better option would be to use SUM with CASE:

select sum(case when group_code = 'total' then graduates end) -
    sum(case when group_code not in ('total','others') then graduates end)
from yourtable

SQL Fiddle Demo with both

Chrome violation : [Violation] Handler took 83ms of runtime

"Chrome violations" don't represent errors in either Chrome or your own web app. They are instead warnings to help you improve your app. In this case, Long running JavaScript and took 83ms of runtime are alerting you there's probably an opportunity to speed up your script.

("Violation" is not the best terminology; it's used here to imply the script "violates" a pre-defined guideline, but "warning" or similar would be clearer. These messages first appeared in Chrome in early 2017 and should ideally have a "More info" prompt to elaborate on the meaning and give suggested actions to the developer. Hopefully those will be added in the future.)

byte[] to file in Java

File f = new File(fileName);    
byte[] fileContent = msg.getByteSequenceContent();    

Path path = Paths.get(f.getAbsolutePath());
try {
    Files.write(path, fileContent);
} catch (IOException ex) {
    Logger.getLogger(Agent2.class.getName()).log(Level.SEVERE, null, ex);

illegal character in path

Your path includes " at the beginning and at the end. Drop the quotes, and it'll be ok.

The \" at the beginning and end of what you see in VS Debugger is what tells us that the quotes are literally in the string.

How to debug a bash script?

Use eclipse with the plugins shelled & basheclipse.

For shelled: Download the zip and import it into eclipse via help -> install new software : local archive For basheclipse: Copy the jars into dropins directory of eclipse

Follow the steps provides

enter image description here

I wrote a tutorial with many screenshots at

Using Gradle to build a jar with dependencies

Gradle 6.3, Java library. The code from "jar task" adds the dependencies to the "build/libs/xyz.jar" when running "gradle build" task.

plugins {
    id 'java-library'

jar {
    from {
        configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }

How to end C++ code

If the condition I'm testing for is really bad news, I do this:

*(int*) NULL= 0;

This gives me a nice coredump from where I can examine the situation.

Get Last Part of URL PHP

One of the most elegant solutions was here Get characters after last / in url

by DisgruntledGoat

$id = substr($url, strrpos($url, '/') + 1);

strrpos gets the position of the last occurrence of the slash; substr returns everything after that position.

PHP Redirect with POST data

I have another solution that makes this possible. It requires the client be running Javascript (which I think is a fair requirement these days).

Simply use an AJAX request on Page A to go and generate your invoice number and customer details in the background (your previous Page B), then once the request gets returned successfully with the correct information - simply complete the form submission over to your payment gateway (Page C).

This will achieve your result of the user only clicking one button and proceeding to the payment gateway. Below is some pseudocode


<form id="paymentForm" method="post" action="">
  <input type="hidden" id="customInvoiceId" .... />
  <input type="hidden" .... />

  <input type="submit" id="submitButton" />

JS (using jQuery for convenience but trivial to make pure Javascript):

$('#submitButton').click(function(e) {
  e.preventDefault(); //This will prevent form from submitting

  //Do some stuff like build a list of things being purchased and customer details

  $.getJSON('setupOrder.php', {listOfProducts: products, customerDetails: details }, function(data) {
  if (!data.error) {
    $('#paymentForm #customInvoiceID').val(;
    $('#paymentForm').submit();   //Send client to the payment processor

How to split a string literal across multiple lines in C / Objective-C?

GCC adds C++ multiline raw string literals as a C extension

C++11 has raw string literals as mentioned at:

However, GCC also adds them as a C extension, you just have to use -std=gnu99 instead of -std=c99. E.g.:


#include <assert.h>
#include <string.h>

int main(void) {
)", "\na\nb\n") == 0);

Compile and run:

gcc -o main -pedantic -std=gnu99 -Wall -Wextra main.c

This can be used for example to insert multiline inline assembly into C code: How to write multiline inline assembly code in GCC C++?

Now you just have to lay back, and wait for it to be standardized on C20XY.

C++ was asked at: C++ multiline string literal

Tested on Ubuntu 16.04, GCC 6.4.0, binutils 2.26.1.

Persist javascript variables across pages?

You could use the window’s name to store the information. This is known as JavaScript session. But it only works as long as the same window/tab is used.

Check if string contains only letters in javascript

try to add \S at your pattern


How to pass an object from one activity to another on Android

Create your own class Customer as following:

import import;
public class Customer implements Serializable
    private String name;
    private String city;

    public Customer()

    public Customer(String name, String city)
    { name;;
    public String getName() 
        return name;
    public void setName(String name) 
    { = name;
    public String getCity() 
        return city;
    public void setCity(String city) 
    { city;


In your onCreate() method

protected void onCreate(Bundle savedInstanceState) 

    Customer cust=new Customer();

    Intent intent=new Intent(abc.this,xyz.class);

In xyz activity class you need to use the following code:

Intent intent=getIntent();
Customer cust=(Customer)intent.getSerializableExtra("bundle");

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

Checkout this, This is from PHP MANUAL, This may help you.

If you're using PHP_CLI SAPI and getting error "Maximum execution time of N seconds exceeded" where N is an integer value, try to call set_time_limit(0) every M seconds or every iteration. For example:



$stmt = $db->query($sql);

while ($row = $stmt->fetchRow()) {
    // your code here


Count character occurrences in a string in C++

You name it... Lambda version... :)

using namespace boost::lambda;

std::string s = "a_b_c";
std::cout << std::count_if (s.begin(), s.end(), _1 == '_') << std::endl;

You need several includes... I leave you that as an exercise...

Change all files and folders permissions of a directory to 644/755

Do both in a single pass with:

find -type f ... -o -type d ...

As in, find type f OR type d, and do the first ... for files and the second ... for dirs. Specifically:

find -type f -exec chmod --changes 644 {} + -o -type d -exec chmod --changes 755 {} +

Leave off the --changes if you want it to work silently.

What does @@variable mean in Ruby?

@ and @@ in modules also work differently when a class extends or includes that module.

So given

module A
    @a = 'module'
    @@a = 'module'

    def get1

    def get2

    def set1(a) 
        @a = a      

    def set2(a) 
        @@a = a     

    def self.set1(a)
        @a = a      

    def self.set2(a)
        @@a = a     

Then you get the outputs below shown as comments

class X
    extend A

    puts get1.inspect # nil
    puts get2.inspect # "module"

    @a = 'class' 
    @@a = 'class' 

    puts get1.inspect # "class"
    puts get2.inspect # "module"


    puts get1.inspect # "set" 
    puts get2.inspect # "set" 


    puts get1.inspect # "set" 
    puts get2.inspect # "sset"

class Y
    include A

    def doit
        puts get1.inspect # nil
        puts get2.inspect # "module"

        @a = 'class'
        @@a = 'class'

        puts get1.inspect # "class"
        puts get2.inspect # "class"


        puts get1.inspect # "set"
        puts get2.inspect # "set"


        puts get1.inspect # "set"
        puts get2.inspect # "sset"

So use @@ in modules for variables you want common to all their uses, and use @ in modules for variables you want separate for every use context.

How to find the day, month and year with moment.js

I know this has already been answered, but I stumbled across this question and went down the path of using format, which works, but it returns them as strings when I wanted integers.

I just realized that moment comes with date, month and year methods that return the actual integers for each method.

moment().month()  // jan=0, dec=11

Remove characters before character "."

You can use the IndexOf method and the Substring method like so:

string output = input.Substring(input.IndexOf('.') + 1);

The above doesn't have error handling, so if a period doesn't exist in the input string, it will present problems.

Hibernate Group by Criteria Object

Please refer to this for the example .The main point is to use the groupProperty() , and the related aggregate functions provided by the Projections class.

For example :

SELECT column_name, max(column_name) , min (column_name) , count(column_name)
FROM table_name
WHERE column_name > xxxxx
GROUP BY column_name

Its equivalent criteria object is :

List result = session.createCriteria(SomeTable.class)       
                    .add("someColumn", xxxxx))      

Java output formatting for Strings

System.out.println(String.format("%-20s= %s" , "label", "content" ));
  • Where %s is a placeholder for you string.
  • The '-' makes the result left-justified.
  • 20 is the width of the first string

The output looks like this:

label               = content

As a reference I recommend Javadoc on formatter syntax

How to link to part of the same document in Markdown?

The pandoc manual explains how to link to your headers, using their identifier. I did not check support of this by other parsers, but it was reported that it does not work on github.

The identifier can be specified manually:

## my heading text {#mht}

Some normal text here,
including a [link to the header](#mht).

or you can use the auto-generated identifier (in this case #my-heading-text). Both are explained in detail in the pandoc manual.

NOTE: This only works when converting to HTML, LaTex, ConTeXt, Textile or AsciiDoc.

What does ellipsize mean in android?

for my experience, Ellipsis works only if below two attributes are set.


for the width of textview, wrap_content or match_parent should both be good.

Fastest way to remove first char in a String

I'd guess that Remove and Substring would tie for first place, since they both slurp up a fixed-size portion of the string, whereas TrimStart does a scan from the left with a test on each character and then has to perform exactly the same work as the other two methods. Seriously, though, this is splitting hairs.

Getting the location from an IP address

I wrote a bot using an API from, here's how you can get location for an IP address (e.g. in php :

Set header :

$opts = array('http'=>array('method'=>"GET", 'header'=>"User-Agent: mybot.v0.7.1"));
$context = stream_context_create($opts);

Get JSON response

echo file_get_contents('', false, $context);

of get a specific field (country, timezone etc.)

echo file_get_contents('', false, $context);

error: (-215) !empty() in function detectMultiScale

"\Anaconda3\Lib\site-packages\cv2\data\" I found the xml file in this path for Anaconda

jQuery check if <input> exists and has a value

You could do:

if($('.input1').length && $('.input1').val().length)

length evaluates to false in a condition, when the value is 0.

POST Multipart Form Data using Retrofit 2.0 including image

in kotlin its quite easy, using extensions methods of toMediaType, asRequestBody and toRequestBody here's an example:

here I am posting a couple of normal fields along with a pdf file and an image file using multipart

this is API declaration using retrofit:

    fun createLesson(
        @Part("userId") userId: RequestBody,
        @Part("LessonTitle") lessonTitle: RequestBody,
        @Part pdf: MultipartBody.Part,
        @Part imageFile: MultipartBody.Part
    ): Maybe<BaseResponse<String>>

and here is how to actually call it:


I lose my data when the container exits

You might want to look at docker volumes if you you want to persist the data in your container. Visit The docker documentation is a very good place to start

Mismatch Detected for 'RuntimeLibrary'

Issue can be solved by adding CRT of msvcrtd.lib in the linker library. Because cryptlib.lib used CRT version of debug.

How to make an HTTP request + basic auth in Swift

I had a similar problem trying to POST to MailGun for some automated emails I was implementing in an app.

I was able to get this working properly with a large HTTP response. I put the full path into Keys.plist so that I can upload my code to github and broke out some of the arguments into variables so I can have them programmatically set later down the road.

// Email the FBO with desired information
// Parse our Keys.plist so we can use our path
var keys: NSDictionary?

if let path = NSBundle.mainBundle().pathForResource("Keys", ofType: "plist") {
    keys = NSDictionary(contentsOfFile: path)

if let dict = keys {
    // variablize our https path with API key, recipient and message text
    let mailgunAPIPath = dict["mailgunAPIPath"] as? String
    let emailRecipient = "[email protected]"
    let emailMessage = "Testing%20email%20sender%20variables"

    // Create a session and fill it with our request
    let session = NSURLSession.sharedSession()
    let request = NSMutableURLRequest(URL: NSURL(string: mailgunAPIPath! + "from=FBOGo%20Reservation%20%3Cscheduler@<my domain>.com%3E&to=reservations@<my domain>.com&to=\(emailRecipient)&subject=A%20New%20Reservation%21&text=\(emailMessage)")!)

    // POST and report back with any errors and response codes
    request.HTTPMethod = "POST"
    let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
        if let error = error {

        if let response = response {
            print("url = \(response.URL!)")
            print("response = \(response)")
            let httpResponse = response as! NSHTTPURLResponse
            print("response code = \(httpResponse.statusCode)")

The Mailgun Path is in Keys.plist as a string called mailgunAPIPath with the value:

https://API:key-<my key><my domain>.com/messages?

Hope this helps offers a solution to someone trying to avoid using 3rd party code for their POST requests!

What is the Windows equivalent of the diff command?

There's also Powershell (which is part of Windows). It ain't quick but it's flexible, here's the basic command. People have written various cmdlets and scripts for it if you need better formatting.

PS C:\Users\Troll> Compare-Object (gc $file1) (gc $file2)

Not part of Windows, but if you are a developer with Visual Studio, it comes with WinDiff (graphical)

But my personal favorite is BeyondCompare, which costs $30.

Where does error CS0433 "Type 'X' already exists in both A.dll and B.dll " come from?

Removing the class files from the App_Code folder, and placing them directly under the website, solved this issue for me.

Callback after all asynchronous forEach callbacks are completed

My solution without Promise (this ensures that every action is ended before the next one begins):

Array.prototype.forEachAsync = function (callback, end) {_x000D_
        var self = this;_x000D_
        function task(index) {_x000D_
            var x = self[index];_x000D_
            if (index >= self.length) {_x000D_
            else {_x000D_
                callback(self[index], index, self, function () {_x000D_
                    task(index + 1);_x000D_
    var i = 0;_x000D_
    var myArray = Array.apply(null, Array(10)).map(function(item) { return i++; });_x000D_
    myArray.forEachAsync(function(item, index, arr, next){_x000D_
        $(".toto").append("<div>item index " + item + " done</div>");_x000D_
        console.log("action " + item + " done");_x000D_
      }, 300);_x000D_
    }, function(){_x000D_
        $(".toto").append("<div>ALL ACTIONS ARE DONE</div>");_x000D_
        console.log("ALL ACTIONS ARE DONE");_x000D_
<script src=""></script>_x000D_
<div class="toto">_x000D_

Facebook Access Token for Pages

See here if you want to grant a Facebook App permanent access to a page (even when you / the app owner are logged out):

"An App Access Token does not expire unless you refresh the application secret through your app settings."

SQL Query for Logins

Have a look in the syslogins or sysusers tables in the master schema. Not sure if this still still around in more recent MSSQL versions though. In MSSQL 2005 there are views called sys.syslogins and sys.sysusers.

How do I call a specific Java method on a click/submit event of a specific button in JSP?

Just give the individual button elements a unique name. When pressed, the button's name is available as a request parameter the usual way like as with input elements.

You only need to make sure that the button inputs have type="submit" as in <input type="submit"> and <button type="submit"> and not type="button", which only renders a "dead" button purely for onclick stuff and all.


<form action="${pageContext.request.contextPath}/myservlet" method="post">
    <input type="submit" name="button1" value="Button 1" />
    <input type="submit" name="button2" value="Button 2" />
    <input type="submit" name="button3" value="Button 3" />


public class MyServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        MyClass myClass = new MyClass();

        if (request.getParameter("button1") != null) {
        } else if (request.getParameter("button2") != null) {
        } else if (request.getParameter("button3") != null) {
        } else {
            // ???

        request.getRequestDispatcher("/WEB-INF/some-result.jsp").forward(request, response);


Alternatively, use <button type="submit"> instead of <input type="submit">, then you can give them all the same name, but an unique value. The value of the <button> won't be used as label, you can just specify that yourself as child.


<form action="${pageContext.request.contextPath}/myservlet" method="post">
    <button type="submit" name="button" value="button1">Button 1</button>
    <button type="submit" name="button" value="button2">Button 2</button>
    <button type="submit" name="button" value="button3">Button 3</button>


public class MyServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        MyClass myClass = new MyClass();
        String button = request.getParameter("button");

        if ("button1".equals(button)) {
        } else if ("button2".equals(button)) {
        } else if ("button3".equals(button)) {
        } else {
            // ???

        request.getRequestDispatcher("/WEB-INF/some-result.jsp").forward(request, response);


See also:

Resize background image in div using css

i would recommend using this:

  background-image: url(your file location here);
  background-size:cover;(will only work with css3)

hope it helps :D

And if this doesnt support your needs just say it: i can make a jquery for multibrowser support.

Usage of the backtick character (`) in JavaScript

You can make a template of templates too, and reach private variable.

var a= {e:10, gy:'sfdsad'}; //global object

console.log(`e is ${a.e} and gy is ${}`); 
//e is 10 and gy is sfdsad

var b = "e is ${a.e} and gy is ${}" // template string
console.log( `${b}` );
//e is ${a.e} and gy is ${}

console.log( eval(`\`${b}\``) ); // convert template string to template
//e is 10 and gy is sfdsad

backtick( b );   // use fonction's variable
//e is 20 and gy is fghj

function backtick( temp ) {
  var a= {e:20, gy:'fghj'}; // local object
  console.log( eval(`\`${temp}\``) );

show icon in actionbar/toolbar with AppCompat-v7 21


OR make a XML layout call the tool_bar.xml

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




Now in you main activity add this line

     layout="@layout/tool_bar" />

What is the difference between "JPG" / "JPEG" / "PNG" / "BMP" / "GIF" / "TIFF" Image?

The file extension tells you how the image is saved. Some of those formats just save the bits as they are, some compress the image in different ways, including lossless and lossy methods. The Web can tell you, although I know some of the patient responders will outline them here.

The web favors gif, jpg, and png, mostly. JPEG is the same (or very close) to jpg.

What integer hash function are good that accepts an integer hash key?

This page lists some simple hash functions that tend to decently in general, but any simple hash has pathological cases where it doesn't work well.

JQuery find first parent element with specific class prefix

Use .closest() with a selector:

var $div = $('#divid').closest('div[class^="div-a"]');

disable viewport zooming iOS 10+ safari?

In my particular case, I am using Babylon.js to create a 3D scene and my whole page consists of one full screen canvas. The 3D engine has its own zooming functionality but on iOS the pinch-to-zoom interferes with that. I updated the the @Joseph answer to overcome my problem. To disable it, I figured out that I need to pass the {passive: false} as an option to the event listener. The following code works for me:

    function(event) {
        if (event.scale !== 1) {
    { passive: false }

How to get folder path from file path with CMD

For the folder name and drive, you can use:

echo %~dp0

You can get a lot more information using different modifiers:

%~I         - expands %I removing any surrounding quotes (")
%~fI        - expands %I to a fully qualified path name
%~dI        - expands %I to a drive letter only
%~pI        - expands %I to a path only
%~nI        - expands %I to a file name only
%~xI        - expands %I to a file extension only
%~sI        - expanded path contains short names only
%~aI        - expands %I to file attributes of file
%~tI        - expands %I to date/time of file
%~zI        - expands %I to size of file

The modifiers can be combined to get compound results:
%~dpI       - expands %I to a drive letter and path only
%~nxI       - expands %I to a file name and extension only
%~fsI       - expands %I to a full path name with short names only

This is a copy paste from the "for /?" command on the prompt. Hope it helps.


Top 10 DOS Batch tips (Yes, DOS Batch...) shows batchparams.bat (link to source as a gist):

C:\Temp>batchparams.bat c:\windows\notepad.exe
%~1     =      c:\windows\notepad.exe
%~f1     =      c:\WINDOWS\NOTEPAD.EXE
%~d1     =      c:
%~p1     =      \WINDOWS\
%~n1     =      NOTEPAD
%~x1     =      .EXE
%~s1     =      c:\WINDOWS\NOTEPAD.EXE
%~a1     =      --a------
%~t1     =      08/25/2005 01:50 AM
%~z1     =      17920
%~$PATHATH:1     =
%~dp1     =      c:\WINDOWS\
%~nx1     =      NOTEPAD.EXE
%~dp$PATH:1     =      c:\WINDOWS\
%~ftza1     =      --a------ 08/25/2005 01:50 AM 17920 c:\WINDOWS\NOTEPAD.EXE

How to import JsonConvert in C# application?

If you are developing a .Net Core WebApi or WebSite you dont not need to install newtownsoft.json to perform json serialization/deserealization

Just make sure that your controller method returns a JsonResult and call return Json(<objectoToSerialize>); like this example

namespace WebApi.Controllers
    public class AccountsController : Controller
        // GET: api/Transaction
        public JsonResult Get()
            List<Account> lstAccounts;

            lstAccounts = AccountsFacade.GetAll();

            return Json(lstAccounts);

If you are developing a .Net Framework WebApi or WebSite you need to use NuGet to download and install the newtonsoft json package

"Project" -> "Manage NuGet packages" -> "Search for "newtonsoft json". -> click "install".

namespace WebApi.Controllers
    public class AccountsController : Controller
        // GET: api/Transaction
        public JsonResult Get()
            List<Account> lstAccounts;

            lstAccounts = AccountsFacade.GetAll();

            //This line is different !! 
            return new JsonConvert.SerializeObject(lstAccounts);

More details can be found here -

yii2 hidden input value

Hello World!
You see, the main question while using hidden input is what kind of data you want to pass? I will assume that you are trying to pass the user ID.
Which is not a really good idea to pass it here because field() method will generate input and the value will be shown to user as we can't hide html from the users browser. This if you really care about security of your website.

please check this link, and you will see that it's impossible to hide value attribute from users to see.

so what to do then?

See, this is the core of OOP in PHP. and I quote from Matt Zandstr in his great book PHP Objects, Patterns, and Practice fifth edition

I am still stuck with a great deal of unwanted flexibility, though. I rely on the client coder to change a ShopProduct object’s properties from their default values. This is problematic in two ways. First, it takes five lines to properly initialize a ShopProduct object, and no coder will thank you for that. Second, I have no way of ensuring that any of the properties are set when a ShopProduct object is initialized. What I need is a method that is called automatically when an object is instantiated from a class.

Please check this example of using __construct() method which is mentioned in his book too.

     class ShopProduct { 
       public $title;   
       public $producerMainName;  
       public $producerFirstName;  
       public $price = 0;
       public function __construct($title,$firstName,$mainName,$price) {
            $this->title = $title;
            $this->producerFirstName = $firstName;  
            $this->producerMainName = $mainName; 
            $this->price = $price;

And you can simply do this magic.

$product1 = new ShopProduct("My Antonia","Willa","Cather",5.99 );
print "author: {$product1->getProducer()}\n";

This produces the following:

author: Willa Cather

In your case it will be something semilar to this, every time you create an object just pass the user ID to the user_id property, and save yourself a lot of coding.

Class Car {
  private $user_id;
//.. your properties

  public function __construct($title,$firstName,$mainName,$price){
     $this->user_id = \Yii::$app->user->id;
    //..Your magic


Good luck! And Happy Coding!

Python develop vs install

Another thing that people may find useful when using the develop method is the --user option to install without sudo. Ex:

python develop --user

instead of

sudo python develop

jQuery toggle CSS?

I would use the toggleClass function in jQuery and define the CSS to the class e.g.

/* start of css */ {
    border-bottom-right-radius: 5px;
    border-bottom-left-radius: 5px;
    -webkit-border-bottom-right-radius: 5px; /* user-agent specific */
    -webkit-border-bottom-left-radius: 5px;
    -moz-border-radius-bottomright: 5px;
    -moz-border-radius-bottomleft: 5px; /* etc... */
/* start of js */
$('#user_button').click(function() {
    return false;

How do I use JDK 7 on Mac OSX?

Now, Use command

Update 2020: 04

To install Java7 with homebrew run:

brew tap homebrew/cask-versions
brew cask install java7

Hope this help.

How does lock work exactly?

The performance impact depends on the way you lock. You can find a good list of optimizations here:

Basically you should try to lock as little as possible, since it puts your waiting code to sleep. If you have some heavy calculations or long lasting code (e.g. file upload) in a lock it results in a huge performance loss.

Web scraping with Python

Make your life easier by using CSS Selectors

I know I have come late to party but I have a nice suggestion for you.

Using BeautifulSoup is already been suggested I would rather prefer using CSS Selectors to scrape data inside HTML

import urllib2
from bs4 import BeautifulSoup

main_url = ""

main_page_html  = tryAgain(main_url)
main_page_soup = BeautifulSoup(main_page_html)

# Scrape all TDs from TRs inside Table
for tr in"table.class_of_table"):
   for td in"td#id"):
       # For acnhors inside TD
       # Value of Href attribute

# This is method that scrape URL and if it doesnt get scraped, waits for 20 seconds and then tries again. (I use it because my internet connection sometimes get disconnects)
def tryAgain(passed_url):
        page  = requests.get(passed_url,headers = random.choice(header), timeout = timeout_time).text
        return page
    except Exception:
        while 1:
            print("Trying again the URL:")
                page  = requests.get(passed_url,headers = random.choice(header), timeout = timeout_time).text
                print("---- URL was successfully scraped ---")
                return page
            except Exception:

How do I print out the contents of an object in Rails for easy debugging?

I generally first try .inspect, if that doesn't give me what I want, I'll switch to .to_yaml.

class User
  attr_accessor :name, :age

user = = "John Smith"
user.age = 30

puts user.inspect
#=> #<User:0x423270c @name="John Smith", @age=30>
puts user.to_yaml
#=> --- !ruby/object:User
#=> age: 30
#=> name: John Smith

Hope that helps.

jQuery slide left and show

Don't forget the padding and margins...

jQuery.fn.slideLeftHide = function(speed, callback) { 
    width: "hide", 
    paddingLeft: "hide", 
    paddingRight: "hide", 
    marginLeft: "hide", 
    marginRight: "hide" 
  }, speed, callback);

jQuery.fn.slideLeftShow = function(speed, callback) { 
    width: "show", 
    paddingLeft: "show", 
    paddingRight: "show", 
    marginLeft: "show", 
    marginRight: "show" 
  }, speed, callback);

With the speed/callback arguments added, it's a complete drop-in replacement for slideUp() and slideDown().

Using Composer's Autoload

Every package should be responsible for autoloading itself, what are you trying to achieve with autoloading classes that are out of the package you define?

One workaround if it's for your application itself is to add a namespace to the loader instance, something like this:


$loader = require 'vendor/autoload.php';
$loader->add('AppName', __DIR__.'/../src/');

how to find host name from IP with out login to the host

In most cases, traceroute command works fine. nslookup and host commands may fail.

Removing Data From ElasticSearch

You have to send a DELETE request to


You can also delete a single document:


I suggest you to use elastichammer.

After deleting you can look up if the index still exists with the following URL: http://[your_host]:9200/_stats/

Good luck!

source of historical stock data

NASDAQ offers 10 years of historical EOD data for each symbol

You could automate the process of downloading this data.

Duplicate headers received from server

This ones a little old but was high in the google ranking so I thought I would throw in the answer I found from Chrome, pdf display, Duplicate headers received from the server

Basically my problem also was that the filename contained commas. Do a replace on commas to remove them and you should be fine. My function to make a valid filename is below.

    public static string MakeValidFileName(string name)
        string invalidChars = Regex.Escape(new string(System.IO.Path.GetInvalidFileNameChars()));
        string invalidReStr = string.Format(@"[{0}]+", invalidChars);
        string replace = Regex.Replace(name, invalidReStr, "_").Replace(";", "").Replace(",", "");
        return replace;

What should be the values of GOPATH and GOROOT?

If you are using the distro go, you should point to where the include files are, for example:

$ rpm -ql golang | grep include

(This is for Fedora 20)

Android Studio Gradle Configuration with name 'default' not found

I also faced the same issue and it resolved by changing one flag (gradle.ext.set("allowLocalEdits", true)) to false in settings.xml.

Difference between Node object and Element object?

Node :

The Node object represents a single node in the document tree. A node can be an element node, an attribute node, a text node, or any other of the node types explained in the Node Types chapter.

Element :

The Element object represents an element in an XML document. Elements may contain attributes, other elements, or text. If an element contains text, the text is represented in a text-node.

duplicate :

Redirecting unauthorized controller in ASP.NET MVC

This problem has hounded me for some days now, so on finding the answer that affirmatively works with tvanfosson's answer above, I thought it would be worthwhile to emphasize the core part of the answer, and address some related catch ya's.

The core answer is this, sweet and simple:

filterContext.Result = new HttpUnauthorizedResult();

In my case I inherit from a base controller, so in each controller that inherits from it I override OnAuthorize:

protected override void OnAuthorization(AuthorizationContext filterContext)
    YourAuth(filterContext); // do your own authorization logic here

The problem was that in 'YourAuth', I tried two things that I thought would not only work, but would also immediately terminate the request. Well, that is not how it works. So first, the two things that DO NOT work, unexpectedly:

filterContext.RequestContext.HttpContext.Response.Redirect("/Login"); // doesn't work!
FormsAuthentication.RedirectToLoginPage(); // doesn't work!

Not only do those not work, they don't end the request either. Which means the following:

if (!success) {
    filterContext.Result = new HttpUnauthorizedResult();

Well, even with the correct answer above, the flow of logic still continues! You will still hit DoMoreStuff... within OnAuthorize. So keep that in mind (DoMore... should be in an else therefore).

But with the correct answer, while OnAuthorize flow of logic continues till the end still, after that you really do get what you expect: a redirect to your login page (if you have one set in Forms auth in your webconfig).

But unexpectedly, 1) Response.Redirect("/Login") does not work: the Action method still gets called, and 2) FormsAuthentication.RedirectToLoginPage(); does the same thing: the Action method still gets called!

Which seems totally wrong to me, particularly with the latter: who would have thought that FormsAuthentication.RedirectToLoginPage does not end the request, or do the equivalant above of what filterContext.Result = new HttpUnauthorizedResult() does?

Is there a way to run Python on Android?

Yes! : Android Scripting Environment

An example via Matt Cutts via SL4A -- "here’s a barcode scanner written in six lines of Python code:

import android
droid = android.Android()
code = droid.scanBarcode()
isbn = int(code['result']['SCAN_RESULT'])
url = "" % isbn
droid.startActivity('android.intent.action.VIEW', url)

ViewPager and fragments — what's the right way to store fragment's state?

I came up with this simple and elegant solution. It assumes that the activity is responsible for creating the Fragments, and the Adapter just serves them.

This is the adapter's code (nothing weird here, except for the fact that mFragments is a list of fragments maintained by the Activity)

class MyFragmentPagerAdapter extends FragmentStatePagerAdapter {

    public MyFragmentPagerAdapter(FragmentManager fm) {

    public Fragment getItem(int position) {
        return mFragments.get(position);

    public int getCount() {
        return mFragments.size();

    public int getItemPosition(Object object) {
        return POSITION_NONE;

    public CharSequence getPageTitle(int position) {
        TabFragment fragment = (TabFragment)mFragments.get(position);
        return fragment.getTitle();

The whole problem of this thread is getting a reference of the "old" fragments, so I use this code in the Activity's onCreate.

    if (savedInstanceState!=null) {
        if (getSupportFragmentManager().getFragments()!=null) {
            for (Fragment fragment : getSupportFragmentManager().getFragments()) {

Of course you can further fine tune this code if needed, for example making sure the fragments are instances of a particular class.

Reading a date using DataReader

        /// <summary>
    /// Returns a new conContractorEntity instance filled with the DataReader's current record data
    /// </summary>
    protected virtual conContractorEntity GetContractorFromReader(IDataReader reader)
        return new conContractorEntity()
            ConId = reader["conId"].ToString().Length > 0 ? int.Parse(reader["conId"].ToString()) : 0,
            ConEmail = reader["conEmail"].ToString(),
            ConCopyAdr = reader["conCopyAdr"].ToString().Length > 0 ? bool.Parse(reader["conCopyAdr"].ToString()) : true,
            ConCreateTime = reader["conCreateTime"].ToString().Length > 0 ? DateTime.Parse(reader["conCreateTime"].ToString()) : DateTime.MinValue


        /// <summary>
    /// Returns a new conContractorEntity instance filled with the DataReader's current record data
    /// </summary>
    protected virtual conContractorEntity GetContractorFromReader(IDataReader reader)
        return new conContractorEntity()
            ConId = GetValue<int>(reader["conId"]),
            ConEmail = reader["conEmail"].ToString(),
            ConCopyAdr = GetValue<bool>(reader["conCopyAdr"], true),
            ConCreateTime = GetValue<DateTime>(reader["conCreateTime"])

// Base methods
        protected T GetValue<T>(object obj)
        if (typeof(DBNull) != obj.GetType())
            return (T)Convert.ChangeType(obj, typeof(T));
        return default(T);

    protected T GetValue<T>(object obj, object defaultValue)
        if (typeof(DBNull) != obj.GetType())
            return (T)Convert.ChangeType(obj, typeof(T));
        return (T)defaultValue;

How can you strip non-ASCII characters from a string? (in C#)

If you want not to strip, but to actually convert latin accented to non-accented characters, take a look at this question: How do I translate 8bit characters into 7bit characters? (i.e. Ü to U)

Get folder name of the file in Python

I'm using 2 ways to get the same response: one of them use:


due to errors that I found in my script I changed to:

Path = filename[:(len(filename)-len(os.path.basename(filename)))]

it's a workaround due to python's '\\'

Why use $_SERVER['PHP_SELF'] instead of ""

When you insert ANY variable into HTML, unless you want the browser to interpret the variable itself as HTML, it's best to use htmlspecialchars() on it. Among other things, it prevents hackers from inserting arbitrary HTML in your page.

The value of $_SERVER['PHP_SELF'] is taken directly from the URL entered in the browser. Therefore if you use it without htmlspecialchars(), you're allowing hackers to directly manipulate the output of your code.

For example, if I e-mail you a link to"><script>malicious_code_here()</script><span class=" and you have <form action="<?php echo $_SERVER['PHP_SELF'] ?>">, the output will be:

<form action=""><script>malicious_code_here()</script><span class="">

My script will run, and you will be none the wiser. If you were logged in, I may have stolen your cookies, or scraped confidential info from your page.

However, if you used <form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']) ?>">, the output would be:

<form action=";&gt;&lt;script&gt;cookie_stealing_code()&lt;/script&gt;&lt;span class=&quot;">

When you submitted the form, you'd have a weird URL, but at least my evil script did not run.

On the other hand, if you used <form action="">, then the output would be the same no matter what I added to my link. This is the option I would recommend.

Convert a String of Hex into ASCII in Java

Just use a for loop to go through each couple of characters in the string, convert them to a character and then whack the character on the end of a string builder:

String hex = "75546f7272656e745c436f6d706c657465645c6e667375635f6f73745f62795f6d757374616e675c50656e64756c756d2d392c303030204d696c65732e6d7033006d7033006d7033004472756d202620426173730050656e64756c756d00496e2053696c69636f00496e2053696c69636f2a3b2a0050656e64756c756d0050656e64756c756d496e2053696c69636f303038004472756d2026204261737350656e64756c756d496e2053696c69636f30303800392c303030204d696c6573203c4d757374616e673e50656e64756c756d496e2053696c69636f3030380050656e64756c756d50656e64756c756d496e2053696c69636f303038004d50330000";
StringBuilder output = new StringBuilder();
for (int i = 0; i < hex.length(); i+=2) {
    String str = hex.substring(i, i+2);
    output.append((char)Integer.parseInt(str, 16));

Or (Java 8+) if you're feeling particularly uncouth, use the infamous "fixed width string split" hack to enable you to do a one-liner with streams instead:

        .stream(hex.split("(?<=\\G..)")) //
        .map(s -> Character.toString((char)Integer.parseInt(s, 16)))

Either way, this gives a few lines starting with the following:

uTorrent\Completed\nfsuc_ost_by_mustang\Pendulum-9,000 Miles.mp3

Hmmm... :-)

how to include glyphicons in bootstrap 3

I think your particular problem isn't how to use Glyphicons but understanding how Bootstrap files work together.

Bootstrap requires a specific file structure to work. I see from your code you have this:

<link href="bootstrap.css" rel="stylesheet" media="screen">

Your Bootstrap.css is being loaded from the same location as your page, this would create a problem if you didn't adjust your file structure.

But first, let me recommend you setup your folder structure like so:

/css      <-- Bootstrap.css here
/fonts    <-- Bootstrap fonts here
/js       <-- Bootstrap JavaScript here

If you notice, this is also how Bootstrap structures its files in its download ZIP.

You then include your Bootstrap file like so:

<link href="css/bootstrap.css" rel="stylesheet" media="screen">
<link href="./css/bootstrap.css" rel="stylesheet" media="screen">
<link href="/css/bootstrap.css" rel="stylesheet" media="screen">

Depending on your server structure or what you're going for.

The first and second are relative to your file's current directory. The second one is just more explicit by saying "here" (./) first then css folder (/css).

The third is good if you're running a web server, and you can just use relative to root notation as the leading "/" will be always start at the root folder.

So, why do this?

Bootstrap.css has this specific line for Glyphfonts:

@font-face {
    font-family: 'Glyphicons Halflings';
    src: url('../fonts/glyphicons-halflings-regular.eot');
    src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');

What you can see is that that Glyphfonts are loaded by going up one directory ../ and then looking for a folder called /fonts and THEN loading the font file.

The URL address is relative to the location of the CSS file. So, if your CSS file is at the same location like this:


The CSS file is going one level deeper than looking for a /fonts folder.

So, let's say the actual location of these files are:


The CSS file would technically be looking for a folder at:


but your folder is actually in:


So see if that helps. You don't have to do anything 'special' to load Bootstrap Glyphicons, except make sure your folder structure is set up appropriately.

When you get that fixed, your HTML should simply be:

<span class="glyphicon glyphicon-comment"></span>

Note, you need both classes. The first class glyphicon sets up the basic styles while glyphicon-comment sets the specific image.


Add .* to s in your first line.


DELETE s.* FROM spawnlist s
INNER JOIN npc n ON s.npc_templateid = n.idTemplate
WHERE (n.type = "monster");

How to prevent form from being submitted?

Attach an event listener to the form using .addEventListener() and then call the .preventDefault() method on event:

const element = document.querySelector('form');_x000D_
element.addEventListener('submit', event => {_x000D_
  // actual logic, e.g. validate the form_x000D_
  console.log('Form submission cancelled.');_x000D_
  <button type="submit">Submit</button>_x000D_

I think it's a better solution than defining a submit event handler inline with the onsubmit attribute because it separates webpage logic and structure. It's much easier to maintain a project where logic is separated from HTML. See: Unobtrusive JavaScript.

Using the .onsubmit property of the form DOM object is not a good idea because it prevents you from attaching multiple submit callbacks to one element. See addEventListener vs onclick .

Make Adobe fonts work with CSS3 @font-face in IE9

Try this, add this lines in the web.config.

     <mimeMap fileExtension=".woff" mimeType="application/octet-stream" />

SQL 'like' vs '=' performance

First things first ,

they are not always equal

    select 'Hello' from dual where 'Hello  ' like 'Hello';

    select 'Hello' from dual where 'Hello  ' =  'Hello';

when things are not always equal , talking about their performance isn't that relevant.

If you are working on strings and only char variables , then you can talk about performance . But don't use like and "=" as being generally interchangeable .

As you would have seen in many posts ( above and other questions) , in cases when they are equal the performance of like is slower owing to pattern matching (collation)

org.hibernate.MappingException: Could not determine type for: java.util.List, at table: College, for columns: [org.hibernate.mapping.Column(students)]

Though I am new to hibernate but with little research (trial and error we can say) I found out that it is due to inconsistency in annotating the methods/fileds.

when you are annotating @ID on variable make sure all other annotations are also done on variable only and when you are annotating it on getter method same make sure you are annotating all other getter methods only and not their respective variables.

Regular Expression Match to test for a valid year

You need to add a start anchor ^ as:


Your regex \d{4}$ will match strings that end with 4 digits. So input like -1234 will be accepted.

By adding the start anchor you match only those strings that begin and end with 4 digits, which effectively means they must contain only 4 digits.

Is it possible to select the last n items with nth-child?

This will select the last two iems of a list:

li:nth-last-child(-n+2) {color:red;}

How schedule build in Jenkins?

In the job configuration one can define various build triggers. With periodically build you can schedule the build by defining the date or day of the week and the time to execute the build.

The format is as follows:

MINUTE (0-59), HOUR (0-23), DAY (1-31), MONTH (1-12), DAY OF THE WEEK (0-6)

The letter H, representing the word Hash can be inserted instead of any of the values, it will calculate the parameter based on the hash code of your project name, this is so that if you are building several projects on your build machine at the same time, lets say midnight each day, they do not all start there build execution at the same time, each project starts its execution at a different minute depending on its hash code. You can also specify the value to be between numbers, i.e. H(0,30) will return the hash code of the project where the possible hashes are 0-30


start build daily at 08:30 in the morning, Monday - Friday:

  • 30 08 * * 1-5

weekday daily build twice a day, at lunchtime 12:00 and midnight 00:00, Sunday to Thursday:

  • 00 0,12 * * 0-4

start build daily in the late afternoon between 4:00 p.m. - 4:59 p.m. or 16:00 -16:59 depending on the projects hash:

  • H 16 * * 1-5

start build at midnight:

  • @midnight

or start build at midnight, every Saturday:

  • 59 23 * * 6

every first of every month between 2:00 a.m. - 02:30 a.m. :

  • H(0-30) 02 01 * *

more on CRON expressions

How to drop a unique constraint from table column?

This works mostly.

drop index IX_dbo_YourTableName__YourColumnName on dbo.YourTableName

Installing mcrypt extension for PHP on OSX Mountain Lion

Nothing worked and finally got it working using resource @Here and Here; Just remember for OSX Mavericks (10.9) should use PHP 5.4.17 or Stable PHP 5.4.22 source to compile mcrypt. Php Source 5.4.22 here

Converting an object to a string

var o = {a:1, b:2};

  return 'a='+this.a+', b='+this.b;

console.log('Item: ' + o);

Since Javascript v1.0 works everywhere (even IE) this is a native approach and allows for a very costomised look of your object while debugging and in production

Usefull example

var Ship=function(n,x,y){ = n;
  this.x = x;
  this.y = y;
  return '"''" located at: x:'+this.x+' y:'+this.y;

alert([new Ship('Star Destroyer', 50.001, 53.201),
new Ship('Millennium Falcon', 123.987, 287.543),
new Ship('TIE fighter', 83.060, 102.523)].join('\n'));//now they can battle!
//"Star Destroyer" located at: x:50.001 y:53.201
//"Millennium Falcon" located at: x:123.987 y:287.543
//"TIE fighter" located at: x:83.06 y:102.523

Also, as a bonus

function ISO8601Date(){
  return this.getFullYear()+'-'+(this.getMonth()+1)+'-'+this.getDate();
var d=new Date();
d.toString=ISO8601Date;//demonstrates altering native object behaviour
//IE6   Fri Jul 29 04:21:26 UTC+1200 2016
//FF&GC Fri Jul 29 2016 04:21:26 GMT+1200 (New Zealand Standard Time)
//d.toString=ISO8601Date; 2016-7-29

Not unique table/alias

Your query contains columns which could be present with the same name in more than one table you are referencing, hence the not unique error. It's best if you make the references explicit and/or use table aliases when joining.


    SELECT pa.ProjectID, p.Project_Title, a.Account_ID, a.Username, a.Access_Type, c.First_Name, c.Last_Name
      FROM Project_Assigned pa
INNER JOIN Account a
        ON pa.AccountID = a.Account_ID
INNER JOIN Project p
        ON pa.ProjectID = p.Project_ID
INNER JOIN Clients c
        ON a.Account_ID = c.Account_ID
     WHERE a.Access_Type = 'Client';

Android app unable to start activity componentinfo

Your null pointer exception seems to be on this line:

String url = intent.getExtras().getString("userurl");

because intent.getExtras() returns null when the intent doesn't have any extras.

You have to realize that this piece of code:

Intent Main = new Intent(this, ToClass.class);
Main.putExtra("userurl", url);

doesn't start the activity you wrote in, it will attempt to start an activity called ToClass and if that doesn't exist, your app crashes.

Also, there is no such thing as "android.intent.action.start" so the manifest should look more like:

<activity android:name=".start" android:label="@string/app_name">
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
<activity android:name= ".Main">

I hope this fixes some of the issues you are encountering but I strongly suggest you check out some "getting started" tutorials for android development and build up from there.

Java FileWriter how to write to next Line

.newLine() is the best if your system property line.separator is proper . and sometime you don't want to change the property runtime . So alternative solution is appending \n

Python Inverse of a Matrix

Make sure you really need to invert the matrix. This is often unnecessary and can be numerically unstable. When most people ask how to invert a matrix, they really want to know how to solve Ax = b where A is a matrix and x and b are vectors. It's more efficient and more accurate to use code that solves the equation Ax = b for x directly than to calculate A inverse then multiply the inverse by B. Even if you need to solve Ax = b for many b values, it's not a good idea to invert A. If you have to solve the system for multiple b values, save the Cholesky factorization of A, but don't invert it.

See Don't invert that matrix.

Which browser has the best support for HTML 5 currently?

Seems that new browsers support most of the tags: <header>, <section> etc. For older browsers (IE, Fx2, Camino etc) then you can use this to allow styling of these tags:


Would make these older browsers allow CSS styling of a header tag, instead of just ignoring it.

This means that you can now use the new tags without any loss of functionality, which is a good start!

Oracle insert if not exists statement

    (SELECT 1 "one" FROM dual) 
    ( '[email protected]' and OPT.campaign_id= 100) 
INSERT (email, campaign_id)
VALUES ('[email protected]',100) 

ASP.NET MVC Conditional validation

I've been using this amazing nuget that does dynamic annotations ExpressiveAnnotations

You could validate any logic you can dream of:

public string Email { get; set; }
public string Phone { get; set; }
[RequiredIf("Email != null")]
[RequiredIf("Phone != null")]
[AssertThat("AgreeToContact == true")]
public bool? AgreeToContact { get; set; }

Java String - See if a string contains only numbers and not letters

If you'll be processing the number as text, then change:

if (text.contains("[a-zA-Z]+") == false && text.length() > 2){


if (text.matches("[0-9]+") && text.length() > 2) {

Instead of checking that the string doesn't contain alphabetic characters, check to be sure it contains only numerics.

If you actually want to use the numeric value, use Integer.parseInt() or Double.parseDouble() as others have explained below.

As a side note, it's generally considered bad practice to compare boolean values to true or false. Just use if (condition) or if (!condition).

Is it possible to create static classes in PHP (like in C#)?

final Class B{

    static $staticVar;
    static function getA(){
        self::$staticVar = New A;

the stucture of b is calld a singeton handler you can also do it in a

Class a{
    static $instance;
    static function getA(...){
            self::$staticVar = New A(...);
        return self::$staticVar;

this is the singleton use $a = a::getA(...);

How do I view the SQLite database on an Android device?

try facebook Stetho.

Stetho is a debug bridge for Android applications, enabling the powerful Chrome Developer Tools and much more.

HTML-encoding lost when attribute read from input field

Prototype has it built-in the String class. So if you are using/plan to use Prototype, it does something like:

'<div class="article">This is an article</div>'.escapeHTML();
// -> "&lt;div class="article"&gt;This is an article&lt;/div&gt;"

contenteditable change events

The onchange event doesn't fires when an element with the contentEditable attribute is changed, a suggested approach could be to add a button, to "save" the edition.

Check this plugin which handles the issue in that way:

How to get the Power of some Integer in Swift language?

Trying to combine the overloading, I tried to use generics but couldn't make it work. I finally figured to use NSNumber instead of trying to overload or use generics. This simplifies to the following:

typealias Dbl = Double // Shorter form
infix operator ** {associativity left precedence 160}
func ** (lhs: NSNumber, rhs: NSNumber) -> Dbl {return pow(Dbl(lhs), Dbl(rhs))}

The following code is the same function as above but implements error checking to see if the parameters can be converted to Doubles successfully.

func ** (lhs: NSNumber, rhs: NSNumber) -> Dbl {
    // Added (probably unnecessary) check that the numbers converted to Doubles
    if (Dbl(lhs) ?? Dbl.NaN) != Dbl.NaN && (Dbl(rhs) ?? Dbl.NaN) != Dbl.NaN {
        return pow(Dbl(lhs), Dbl(rhs))
    } else {
        return Double.NaN

How to use (install) dblink in PostgreSQL?

On linux, find dblink.sql, then execute in the postgresql console something like this to create all required functions:

\i /usr/share/postgresql/8.4/contrib/dblink.sql 

you might need to install the contrib packages: sudo apt-get install postgresql-contrib

Python Socket Receive Large Amount of Data

Most of the answers describe some sort of recvall() method. If your bottleneck when receiving data is creating the byte array in a for loop, I benchmarked three approaches of allocating the received data in the recvall() method:

Byte string method:

arr = b''
while len(arr) < msg_len:
    arr += sock.recv(max_msg_size)

List method:

fragments = []
while True: 
    chunk = sock.recv(max_msg_size)
    if not chunk: 
arr = b''.join(fragments)

Pre-allocated bytearray method:

arr = bytearray(msg_len)
pos = 0
while pos < msg_len:
    arr[pos:pos+max_msg_size] = sock.recv(max_msg_size)
    pos += max_msg_size


enter image description here

Inserting records into a MySQL table using Java

There is a mistake in your insert statement chage it to below and try : String sql = "insert into table_name values ('" + Col1 +"','" + Col2 + "','" + Col3 + "')";

React-Redux: Actions must be plain objects. Use custom middleware for async actions

Action Definition

const selectSlice = () => {
  return {
    type: 'SELECT_SLICE'

Action Dispatch


Make sure the object structure of action defined is same as action dispatched. In my case, while dispatching action, type was not assigned to property type.

regular expression for anything but an empty string

Create "regular expression to detect empty string", and then inverse it. Invesion of regular language is the regular language. I think regular expression library in what you leverage - should support it, but if not you always can write your own library.

grep --invert-match

Android - Launcher Icon Size

I had the same problem but then realized the arrangement of my icon graphic within the square allowed (512 x 512 in my case) was not maximized. So I rotated the image and was able to scale it up to fill the corners better. Then I right clicked on my res folder in my project in Android Studio, then choose New then Image Asset, it took me through a wizard where I got to select my image file to use. Then if you check the box that says "Trim surrounding blank space", it makes sure all edges, that are able, touch the sides of your square. These steps got it much bigger than the original.

What is the most efficient way to store a list in the Django models?

A simple way to store a list in Django is to just convert it into a JSON string, and then save that as Text in the model. You can then retrieve the list by converting the (JSON) string back into a python list. Here's how:

The "list" would be stored in your Django model like so:

class MyModel(models.Model):
    myList = models.TextField(null=True) # JSON-serialized (text) version of your list

In your view/controller code:

Storing the list in the database:

import simplejson as json # this would be just 'import json' in Python 2.7 and later

myModel = MyModel()
listIWantToStore = [1,2,3,4,5,'hello']
myModel.myList = json.dumps(listIWantToStore)

Retrieving the list from the database:

jsonDec = json.decoder.JSONDecoder()
myPythonList = jsonDec.decode(myModel.myList)

Conceptually, here's what's going on:

>>> myList = [1,2,3,4,5,'hello']
>>> import simplejson as json
>>> myJsonList = json.dumps(myList)
>>> myJsonList
'[1, 2, 3, 4, 5, "hello"]'
>>> myJsonList.__class__
<type 'str'>
>>> jsonDec = json.decoder.JSONDecoder()
>>> myPythonList = jsonDec.decode(myJsonList)
>>> myPythonList
[1, 2, 3, 4, 5, u'hello']
>>> myPythonList.__class__
<type 'list'>