Programs & Examples On #Machine code

Machine code is data that is directly fed into a microprocessor, being the only form that the processor is able to execute. It is the lowest possible level of abstraction, wherein all data is a raw binary stream. Machine code is barely readable by humans, which is why assembly is usually utilized instead.

How to Calculate Jump Target Address and Branch Target Address?

(In the diagrams and text below, PC is the address of the branch instruction itself. PC+4 is the end of the branch instruction itself, and the start of the branch delay slot. Except in the absolute jump diagram.)

1. Branch Address Calculation

In MIPS branch instruction has only 16 bits offset to determine next instruction. We need a register added to this 16 bit value to determine next instruction and this register is actually implied by architecture. It is PC register since PC gets updated (PC+4) during the fetch cycle so that it holds the address of the next instruction.

We also limit the branch distance to -2^15 to +2^15 - 1 instruction from the (instruction after the) branch instruction. However, this is not real issue since most branches are local anyway.

So step by step :

  • Sign extend the 16 bit offset value to preserve its value.
  • Multiply resulting value with 4. The reason behind this is that If we are going to branch some address, and PC is already word aligned, then the immediate value has to be word-aligned as well. However, it makes no sense to make the immediate word-aligned because we would be wasting low two bits by forcing them to be 00.
  • Now we have a 32 bit relative offset. Add this value to PC + 4 and that is your branch address.

Branch address calculation

2. Jump Address Calculation

For Jump instruction MIPS has only 26 bits to determine Jump location. Jumps are relative to PC in MIPS. Like branch, immediate jump value needs to be word-aligned; therefore, we need to multiply 26 bit address with four.

Again step by step:

  • Multiply 26 bit value with 4.
  • Since we are jumping relative to PC+4 value, concatenate first four bits of PC+4 value to left of our jump address.
  • Resulting address is the jump value.

In other words, replace the lower 28 bits of the PC + 4 with the lower 26 bits of the fetched instruction shifted left by 2 bits.

enter image description here

Jumps are region-relative to the branch-delay slot, not necessarily the branch itself. In the diagram above, PC has already advanced to the branch delay slot before the jump calculation. (In a classic-RISC 5 stage pipeline, the BD was fetched in the same cycle the jump is decoded, so that PC+4 next instruction address is already available for jumps as well as branches, and calculating relative to the jump's own address would have required extra work to save that address.)

Source: Bilkent University CS 224 Course Slides

Assembly code vs Machine code vs Object code?

Assembly code is discussed here.

"An assembly language is a low-level language for programming computers. It implements a symbolic representation of the numeric machine codes and other constants needed to program a particular CPU architecture."

Machine code is discussed here.

"Machine code or machine language is a system of instructions and data executed directly by a computer's central processing unit."

Basically, assembler code is the language and it is translated to object code (the native code that the CPU runs) by an assembler (analogous to a compiler).

assembly to compare two numbers

Compare two numbers. If it equals Yes "Y", it prints No "N" on the screen if it is not equal. I am using emu8086. You can use the SUB or CMP command.






enter image description here

How to use vim in the terminal?

Run vim from the terminal. For the basics, you're advised to run the command vimtutor.

# On your terminal command line:
$ vim

If you have a specific file to edit, pass it as an argument.

$ vim yourfile.cpp

Likewise, launch the tutorial

$ vimtutor

MySQL "ERROR 1005 (HY000): Can't create table 'foo.#sql-12c_4' (errno: 150)"

The referenced column must be an index of a single column or the first column in multi column index, and the same type and the same collation.

My two tables have the different collations. It can be shown by issuing show table status like table_name and collation can be changed by issuing alter table table_name convert to character set utf8.

How to create a Java cron job

If you are using unix, you need to write a shellscript to run you java batch first.

After that, in unix, you run this command "crontab -e" to edit crontab script. In order to configure crontab, please refer to this article

Save your crontab setting. Then wait for the time to come, program will run automatically.

Splitting dataframe into multiple dataframes

You can convert groupby object to tuples and then to dict:

df = pd.DataFrame({'Name':list('aabbef'),
                   'C':[1,3,5,7,1,0]}, columns = ['Name','A','B','C'])

print (df)
  Name  A  B  C
0    a  4  7  1
1    a  5  8  3
2    b  4  9  5
3    b  5  4  7
4    e  5  2  1
5    f  4  3  0

d = dict(tuple(df.groupby('Name')))
print (d)
{'b':   Name  A  B  C
2    b  4  9  5
3    b  5  4  7, 'e':   Name  A  B  C
4    e  5  2  1, 'a':   Name  A  B  C
0    a  4  7  1
1    a  5  8  3, 'f':   Name  A  B  C
5    f  4  3  0}

print (d['a'])
  Name  A  B  C
0    a  4  7  1
1    a  5  8  3

It is not recommended, but possible create DataFrames by groups:

for i, g in df.groupby('Name'):
    globals()['df_' + str(i)] =  g

print (df_a)
  Name  A  B  C
0    a  4  7  1
1    a  5  8  3

How to use continue in jQuery each() loop?

$('.submit').filter(':checked').each(function() {
    //This is same as 'continue'
        return true;
    //This is same as 'break'
        return false;

Difference between links and depends_on in docker_compose.yml

The post needs an update after the links option is deprecated.

Basically, links is no longer needed because its main purpose, making container reachable by another by adding environment variable, is included implicitly with network. When containers are placed in the same network, they are reachable by each other using their container name and other alias as host.

For docker run, --link is also deprecated and should be replaced by a custom network.

docker network create mynet
docker run -d --net mynet --name container1 my_image
docker run -it --net mynet --name container1 another_image

depends_on expresses start order (and implicitly image pulling order), which was a good side effect of links.

How to disable Google Chrome auto update?

To get rid of Chrome 44 and go back to 43 I downloaded a stand-alone version of chrome 43 which is an .exe file and I just double clicked on it and it was installed on my computer WITHOUT updating to Chrome 44, to find the link to Chrome 43 have a look to the bottom of this page Google Chrome 64-bit Offline Installer| 45.7 MB or go to enter link description here.

Have Fun :)

Check if a string contains a string in C++

This is a simple function

bool find(string line, string sWord)
    bool flag = false;
    int index = 0, i, helper = 0;
    for (i = 0; i < line.size(); i++)
        if ( ==
            if (flag == false)
                flag = true;
                helper = i;
            flag = false;
            index = 0;
        if (index == sWord.size())
    if ((i+1-helper) == index)
        return true;
    return false;

PostgreSQL, checking date relative to "today"

select * from mytable where mydate > now() - interval '1 year';

If you only care about the date and not the time, substitute current_date for now()

How do you add input from user into list in Python

shopList = [] 
maxLengthList = 6
while len(shopList) < maxLengthList:
    item = input("Enter your Item to the List: ")
    print shopList
print "That's your Shopping List"
print shopList

Extract names of objects from list

You can just use:

> names(LIST)
[1] "A" "B"

Obviously the names of the first element is just

> names(LIST)[1]
[1] "A"

Getting the array length of a 2D array in Java

public class Array_2D {
int arr[][];
public Array_2D() {
    Random r=new Random(10);
     arr = new int[5][10];
     for(int i=0;i<5;i++)
         for(int j=0;j<10;j++)
  public void display()
         for(int i=0;i<5;i++)

             for(int j=0;j<10;j++)
                 System.out.print(arr[i][j]+" "); 
     public static void main(String[] args) {
     Array_2D s=new Array_2D();

Pass Additional ViewData to a Strongly-Typed Partial View

This should also work.

this.ViewData.Add("index", index);


Mobile website "WhatsApp" button to send message to a specific number

On android, you can try


replace [countrycode_without_plus][number] with the number,

Selecting a row of pandas series/dataframe by integer index

You can take a look at the source code .

DataFrame has a private function _slice() to slice the DataFrame, and it allows the parameter axis to determine which axis to slice. The __getitem__() for DataFrame doesn't set the axis while invoking _slice(). So the _slice() slice it by default axis 0.

You can take a simple experiment, that might help you:

print df._slice(slice(0, 2))
print df._slice(slice(0, 2), 0)
print df._slice(slice(0, 2), 1)

Android - How to decode and decompile any APK file?

To decompile APK Use APKTool.
You can learn how APKTool works on or by reading the documentation.

Could not load type 'XXX.Global'

Deleting the existing global.asax file and adding a new one, clears out this error. This has worked for me many times.

How do I use arrays in cURL POST requests

You are just creating your array incorrectly. You could use http_build_query:

$fields = array(
            'username' => "annonymous",
            'api_key' => urlencode("1234"),
            'images' => array(
$fields_string = http_build_query($fields);

So, the entire code that you could use would be:

//extract data from the post

//set POST variables
$url = '';
$fields = array(
            'username' => "annonymous",
            'api_key' => urlencode("1234"),
            'images' => array(

//url-ify the data for the POST
$fields_string = http_build_query($fields);

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);

//execute post
$result = curl_exec($ch);
echo $result;

//close connection

disable all form elements inside div

Only text type

$(".form-edit-account :input[type=text]").attr("disabled", "disabled");

Only Password type

$(".form-edit-account :input[type=password]").attr("disabled", "disabled");

Only Email Type

$(".form-edit-account :input[type=email]").attr("disabled", "disabled");

Disable/Enable button in Excel/VBA

This is working for me (Excel 2016) with a new ActiveX button, assign a control to you button and you're all set.

Sub deactivate_buttons()

     ActiveSheet.Shapes.Item("CommandButton1").ControlFormat.Enabled = False

End Sub

It changes the "Enabled" property in the ActiveX button Properties box to False and the button becomes inactive and greyed out.

DisplayName attribute from Resources?

I got Gunders answer working with my App_GlobalResources by choosing the resources properties and switch "Custom Tool" to "PublicResXFileCodeGenerator" and build action to "Embedded Resource". Please observe Gunders comment below.

enter image description here

Works like a charm :)

How do I join two lines in vi?

Just replace the "\n" with "".

In vi/Vim for every line in the document:


If you want to confirm every replacement:


How to disable/enable a button with a checkbox if checked

Here is a clean way to disable and enable submit button:

<input type="submit" name="sendNewSms" class="inputButton" id="sendNewSms" value=" Send " />
<input type="checkbox" id="disableBtn" />

var submit = document.getElementById('sendNewSms'),
    checkbox = document.getElementById('disableBtn'),
    disableSubmit = function(e) {
        submit.disabled = this.checked

checkbox.addEventListener('change', disableSubmit);

Here is a fiddle of it in action:

Android Studio installation on Windows 7 fails, no JDK found

I had the same issue. I got resolved setting up correctly the environment variables in windows, for instance:

JAVA_HOME -> C:\Program Files\Java\jdk1.6.0_45
path -> C:\Program Files\Java\jdk1.6.0_45\bin

how to change any data type into a string in python

str(object) will do the trick.

If you want to alter the way object is stringified, define __str__(self) method for object's class. Such method has to return str or unicode object.

Why doesn't CSS ellipsis work in table cell?

I've tried many of the above solutions but none of them felt flexible or satisfying.

This little hack with max-width: 1px can be applied directly to the td element

.truncated-cell {
   max-width: 1px;
   white-space: nowrap;
   overflow: hidden;
   text-overflow: ellipsis;

How to scale a BufferedImage

AffineTransformOp offers the additional flexibility of choosing the interpolation type.

BufferedImage before = getBufferedImage(encoded);
int w = before.getWidth();
int h = before.getHeight();
BufferedImage after = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
AffineTransform at = new AffineTransform();
at.scale(2.0, 2.0);
AffineTransformOp scaleOp = 
   new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR);
after = scaleOp.filter(before, after);

The fragment shown illustrates resampling, not cropping; this related answer addresses the issue; some related examples are examined here.

Conditional WHERE clause in SQL Server

Often when you use conditional WHERE clauses you end upp with a vastly inefficient query, which is noticeable for large datasets where indexes are used. A great way to optimize the query for different values of your parameter is to make a different execution plan for each value of the parameter. You can achieve this using OPTION (RECOMPILE).

In this example it would probably not make much difference, but say the condition should only be used in one of two cases, then you could notice a big impact.

In this example:

    DateDropped = 0
    AND (
    (ISNULL(@JobsOnHold, 0) = 1 AND DateAppr >= 0) 
    (ISNULL(@JobsOnHold, 0) <> 1 AND DateAppr <> 0)

Source Parameter Sniffing, Embedding, and the RECOMPILE Options

Moving Git repository content to another repository preserving history

Perfectly described here

First, we have to fetch all of the remote branches and tags from the existing repository to our local index:

git fetch origin

We can check for any missing branches that we need to create a local copy of:

git branch -a

Let’s use the SSH-cloned URL of our new repository to create a new remote in our existing local repository:

git remote add new-origin [email protected]:manakor/manascope.git

Now we are ready to push all local branches and tags to the new remote named new-origin:

git push --all new-origin 
git push --tags new-origin

Let’s make new-origin the default remote:

git remote rm origin

Rename new-origin to just origin, so that it becomes the default remote:

git remote rename new-origin origin

Change some value inside the List<T>

You could use ForEach, but you have to convert the IEnumerable<T> to a List<T> first.

list.Where(w => w.Name == "height").ToList().ForEach(s => s.Value = 30);

Removing unwanted table cell borders with CSS

add some css:

td, th {

Cannot execute RUN mkdir in a Dockerfile

Apart from the previous use cases, you can also use Docker Compose to create directories in case you want to make new dummy folders on docker-compose up:

  - .:/ftp/
  - /ftp/node_modules
  - /ftp/files

VueJS conditionally add an attribute for an element


<input :required="test ? true : false">

Twitter Bootstrap button click to toggle expand/collapse text section above button

I wanted an "expand/collapse" container with a plus and minus button to open and close it. This uses the standard bootstrap event and has animation. This is BS3.

enter image description here


<button id="button" type="button" class="btn btn-primary" 
  data-toggle="collapse" data-target="#demo">
  <span class="glyphicon glyphicon-collapse-down"></span> Show

<div id="demo" class="collapse">
  <ol class="list-group">
      <li class="list-group-item">Warrior</li>
      <li class="list-group-item">Adventurer</li>
      <li class="list-group-item">Mage</li>


  $('#demo').on('', function () {
    $('#button').html('<span class="glyphicon glyphicon-collapse-down"></span> Show');
  $('#demo').on('', function () {
    $('#button').html('<span class="glyphicon glyphicon-collapse-up"></span> Hide');


Escape sequence \f - form feed - what exactly is it?

It's go to newline then add spaces to start second line at end of first line



Configure WAMP server to send email

I tried Test Mail Server Tool and while it worked great, you still need to open the email on some client.

I found Papercut:

For configuration it's easy as Test Mail Server Tool (pratically zero-conf), and it also serves as an email client, with views for the Message (great for HTML emails), Headers, Body (to inspect the HTML) and Raw (full unparsed email).

It also has a Sections view, to split up the different media types found in the email.

It has a super clean and friendly UI, a good log viewer and gives you notifications when you receive an email.

I find it perfect, so I just wanted to give my 2c and maybe help someone.

Create a data.frame with m columns and 2 rows

Does m really need to be a data.frame() or will a matrix() suffice?

m <- matrix(0, ncol = 30, nrow = 2)

You can wrap a data.frame() around that if you need to:

m <- data.frame(m)

or all in one line: m <- data.frame(matrix(0, ncol = 30, nrow = 2))

Changing Background Image with CSS3 Animations

Updated for 2020: Yes, it can be done! Here's how.

Snippet demo:

#mydiv{ animation: changeBg 1s infinite; width:143px; height:100px; }
@keyframes changeBg{
   0%,100%  {background-image: url("");}
   25% {background-image: url("");}
   50% {background-image: url("");}
   75% {background-image: url("");}
<div id='mydiv'></div>

Background image [isn't a property that can be animated][1] - you can't tween the property.

Original Answer: (still a good alternative) Instead, try laying out all the images on top of each other using position:absolute, then animate the opacity of all of them to 0 except the one you want repeatedly.

Change the "No file chosen":

Right, there is no way to remove this 'no file choosen', even if you have a list of pre-upload files.

Simplest solution I've found (and works on IE, FF, CR) is the following

  1. Hide your input and add a 'files' button
  2. then call the 'files' button and ask him to bind fileupload (I'm using JQuery in this example)

$('.addfiles').on('click', function() { $('#fileupload').click();return false;});
<button class="addfiles">Add Files</button>_x000D_
<input id="fileupload" type="file" name="files[]" multiple style='display: none;'>

It's done, works perfectly :)


Warning: mysql_connect(): Access denied for user 'root'@'localhost' (using password: YES)

try $conn = mysql_connect("localhost", "root") or $conn = mysql_connect("localhost", "root", "")

How to use the CSV MIME-type?

This code can be used to export any file, including csv

// application/octet-stream tells the browser not to try to interpret the file
header('Content-type: application/octet-stream');
header('Content-Length: ' . filesize($data));
header('Content-Disposition: attachment; filename="export.csv"');

Play sound file in a web-page in the background

<audio src="/music/good_enough.mp3" autoplay>
<p>If you are reading this, it is because your browser does not support the audio element.     </p>
<embed src="/music/good_enough.mp3" width="180" height="90" hidden="true" />

Works for me just fine.

Accessing last x characters of a string in Bash

Last three characters of string:

${string: -3}



(mind the space between : and -3 in the first form).

Please refer to the Shell Parameter Expansion in the reference manual:


Expands to up to length characters of parameter starting at the character
specified by offset. If length is omitted, expands to the substring of parameter
starting at the character specified by offset. length and offset are arithmetic
expressions (see Shell Arithmetic). This is referred to as Substring Expansion.

If offset evaluates to a number less than zero, the value is used as an offset
from the end of the value of parameter. If length evaluates to a number less than
zero, and parameter is not ‘@’ and not an indexed or associative array, it is
interpreted as an offset from the end of the value of parameter rather than a
number of characters, and the expansion is the characters between the two
offsets. If parameter is ‘@’, the result is length positional parameters
beginning at offset. If parameter is an indexed array name subscripted by ‘@’ or
‘*’, the result is the length members of the array beginning with
${parameter[offset]}. A negative offset is taken relative to one greater than the
maximum index of the specified array. Substring expansion applied to an
associative array produces undefined results.

Note that a negative offset must be separated from the colon by at least one
space to avoid being confused with the ‘:-’ expansion. Substring indexing is
zero-based unless the positional parameters are used, in which case the indexing
starts at 1 by default. If offset is 0, and the positional parameters are used,
$@ is prefixed to the list.

Since this answer gets a few regular views, let me add a possibility to address John Rix's comment; as he mentions, if your string has length less than 3, ${string: -3} expands to the empty string. If, in this case, you want the expansion of string, you may use:


This uses the ?: ternary if operator, that may be used in Shell Arithmetic; since as documented, the offset is an arithmetic expression, this is valid.

Update for a POSIX-compliant solution

The previous part gives the best option when using Bash. If you want to target POSIX shells, here's an option (that doesn't use pipes or external tools like cut):

# New variable with 3 last characters removed
# The new string is obtained by removing the prefix a from string

One of the main things to observe here is the use of quoting for prefix inside the parameter expansion. This is mentioned in the POSIX ref (at the end of the section):

The following four varieties of parameter expansion provide for substring processing. In each case, pattern matching notation (see Pattern Matching Notation), rather than regular expression notation, shall be used to evaluate the patterns. If parameter is '#', '*', or '@', the result of the expansion is unspecified. If parameter is unset and set -u is in effect, the expansion shall fail. Enclosing the full parameter expansion string in double-quotes shall not cause the following four varieties of pattern characters to be quoted, whereas quoting characters within the braces shall have this effect. In each variety, if word is omitted, the empty pattern shall be used.

This is important if your string contains special characters. E.g. (in dash),

$ string="hello*ext"
$ prefix=${string%???}
$ # Without quotes (WRONG)
$ echo "${string#$prefix}"
$ # With quotes (CORRECT)
$ echo "${string#"$prefix"}"

Of course, this is usable only when then number of characters is known in advance, as you have to hardcode the number of ? in the parameter expansion; but when it's the case, it's a good portable solution.

Maximize a window programmatically and prevent the user from changing the windows state

You were close... after your code of

WindowState = FormWindowState.Maximized;

THEN, set the form's min/max size capacity to the value once its sized out.

MinimumSize = this.Size;
MaximumSize = this.Size;

Can't access Tomcat using IP address

Thanks for all answers. For me it was a different issue. I had to set my wireless network to "private". I only need tomcat for network internal use. For some reason although firewall rule was set to allow for all, it does not allow access from within the same network if set to public.

Changing settings in server.xml were not needed in this usecase.

How to check if activity is in foreground or in visible background?

This is what is recommended as the right solution:

The right solution (credits go to Dan, CommonsWare and NeTeInStEiN) Track visibility of your application by yourself using Activity.onPause, Activity.onResume methods. Store "visibility" status in some other class. Good choices are your own implementation of the Application or a Service (there are also a few variations of this solution if you'd like to check activity visibility from the service).

Example Implement custom Application class (note the isActivityVisible() static method):

public class MyApplication extends Application {

  public static boolean isActivityVisible() {
    return activityVisible;

  public static void activityResumed() {
    activityVisible = true;

  public static void activityPaused() {
    activityVisible = false;

  private static boolean activityVisible;

Register your application class in AndroidManifest.xml:

    android:label="@string/app_name" >

Add onPause and onResume to every Activity in the project (you may create a common ancestor for your Activities if you'd like to, but if your activity is already extended from MapActivity/ListActivity etc. you still need to write the following by hand):

protected void onResume() {

protected void onPause() {

In your finish() method, you want to use isActivityVisible() to check if the activity is visible or not. There you can also check if the user has selected an option or not. Continue when both conditions are met.

The source also mentions two wrong avoid doing that.

Source: stackoverflow

Is it better to use C void arguments "void foo(void)" or not "void foo()"?

void foo(void);

That is the correct way to say "no parameters" in C, and it also works in C++.


void foo();

Means different things in C and C++! In C it means "could take any number of parameters of unknown types", and in C++ it means the same as foo(void).

Variable argument list functions are inherently un-typesafe and should be avoided where possible.

How to install Android Studio on Ubuntu?

I was having having an issue with umake being an outdated version. What fixed it was:

sudo apt remove --purge ubuntu-make
sudo add-apt-repository ppa:ubuntu-desktop/ubuntu-make
sudo apt update
sudo apt install ubuntu-make
umake android

No 'Access-Control-Allow-Origin' - Node / Apache Port Issue

All the other answers didn't work for me. (including cors package, or setting headers through middleware)

For 3^ this worked without any extra packages.

const express = require('express');
const app = express();

const server = require('http').createServer(app);
const io = require('')(server, {
    cors: {
        origin: "*",
        methods: ["GET", "POST"]

how to add super privileges to mysql database?

You can see the privileges here.enter image description here

Then you can edit the user

SQL/mysql - Select distinct/UNIQUE but return all columns?

It can be done by inner query

$query = "SELECT * 
            FROM (SELECT field
                FROM table
                ORDER BY id DESC) as rows               
            GROUP BY field";

How to Convert date into MM/DD/YY format in C#


Look at the docs for custom date and time format strings for more info.

(Oh, and I hope this app isn't destined for other cultures. That format could really confuse a lot of people... I've never understood the whole month/day/year thing, to be honest. It just seems weird to go "middle/low/high" in terms of scale like that.)

Sending emails with Javascript

The way I'm doing it now is basically like this:


<textarea id="myText">
    Lorem ipsum...
<button onclick="sendMail(); return false">Send</button>

The Javascript:

function sendMail() {
    var link = "mailto:[email protected]"
             + "[email protected]"
             + "&subject=" + encodeURIComponent("This is my subject")
             + "&body=" + encodeURIComponent(document.getElementById('myText').value)
    window.location.href = link;

This, surprisingly, works rather well. The only problem is that if the body is particularly long (somewhere over 2000 characters), then it just opens a new email but there's no information in it. I suspect that it'd be to do with the maximum length of the URL being exceeded.

How to save an HTML5 Canvas as an image on a server?

Here is an example of how to achieve what you need:

  1. Draw something (taken from canvas tutorial)

<canvas id="myCanvas" width="578" height="200"></canvas>
  var canvas = document.getElementById('myCanvas');
  var context = canvas.getContext('2d');

  // begin custom shape
  context.moveTo(170, 80);
  context.bezierCurveTo(130, 100, 130, 150, 230, 150);
  context.bezierCurveTo(250, 180, 320, 180, 340, 150);
  context.bezierCurveTo(420, 150, 420, 120, 390, 100);
  context.bezierCurveTo(430, 40, 370, 30, 340, 50);
  context.bezierCurveTo(320, 5, 250, 20, 250, 50);
  context.bezierCurveTo(200, 5, 150, 20, 170, 80);

  // complete custom shape
  context.lineWidth = 5;
  context.fillStyle = '#8ED6FF';
  context.strokeStyle = 'blue';

  1. Convert canvas image to URL format (base64)

    var dataURL = canvas.toDataURL();

  2. Send it to your server via Ajax

      type: "POST",
      url: "script.php",
      data: { 
         imgBase64: dataURL
    }).done(function(o) {
      // If you want the file to be visible in the browser 
      // - please modify the callback in javascript. All you
      // need is to return the url to the file, you just saved 
      // and than put the image in your browser.

  1. Save base64 on your server as an image (here is how to do this in PHP, the same ideas is in every language. Server side in PHP can be found here):

Check if string is neither empty nor space in shell script

For checking the empty string in shell

if [ "$str" == "" ];then
   echo NULL


if [ ! "$str" ];then
   echo NULL

Compile throws a "User-defined type not defined" error but does not go to the offending line of code

An different problem with the same symptom: I had a class implemented which was not defined. It was wrapped with a #if that I thought should have not allowed the compiler to see it, but not so. Remove the comment out the Implements statement and all is well. I assume importing the definition would also work...

Run text file as commands in Bash

You can use something like this:

for i in `cat foo.txt`
    sudo $i

Though if the commands have arguments (i.e. there is whitespace in the lines) you may have to monkey around with that a bit to protect the whitepace so that the whole string is seen by sudo as a command. But it gives you an idea on how to start.

Access to the requested object is only available from the local network phpmyadmin

open your http.conf file

vim /opt/lampp/etc/extra/httpd-xampp.conf

Comment "Deny from all" in the following section,

# New XAMPP security concept
<LocationMatch "^/(?i:(?:xampp|security|licenses|phpmyadmin|webalizer|server-status|server-info))">
        Order deny,allow
       #Deny from all
        Allow from ::1 \
                fc00::/7 \

        ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var

Try to add "Allow from all" before "ErrorDocument" line. Hope it helps.

.bashrc at ssh login

.bashrc is not sourced when you log in using SSH. You need to source it in your .bash_profile like this:

if [ -f ~/.bashrc ]; then
  . ~/.bashrc

Can I pass an array as arguments to a method with variable arguments in Java?

The underlying type of a variadic method function(Object... args) is function(Object[] args). Sun added varargs in this manner to preserve backwards compatibility.

So you should just be able to prepend extraVar to args and call String.format(format, args).

How to output oracle sql result into a file in windows?

just to make the Answer 2 much easier, you can also define the folder where you can put your saved file

    spool /home/admin/myoutputfile.txt
    select * from table_name;
    spool off;

after that only with nano or vi myoutputfile.txt, you will see all the sql track.

hope is that help :)

SQL Combine Two Columns in Select Statement

If you don't want to change your database schema (and I would not for this simple query) you can just combine them in the filter like this: WHERE (Address1 + Address2) LIKE '%searchstring%'

What are FTL files

Freemarker template files I believe.

How to do a PUT request with curl?

Quick Answer:

In a single line, the curl command would be:

a) If sending form data:

curl -X PUT -H "Content-Type: multipart/form-data;" -F "key1=val1" "YOUR_URI"

b) If sending raw data as json:

curl -X PUT -H "Content-Type: application/json" -d '{"key1":"value"}' "YOUR_URI"

c) If sending a file with a POST request:

curl -X POST "YOUR_URI" -F 'file=@/file-path.csv'

Alternative solution:

You can use the POSTMAN app from Chrome Store to get the equivalent cURL request. This is especially useful when writing more complicated requests.

For the request with other formats or for different clients like java, PHP, you can check out POSTMAN/comment below.

POSTMAN to get the request code

How to create a folder with name as current date in batch (.bat) files

for /F “tokens=1-4 delims=/ ” %%A in (‘date /t’) do (
    set DateDay=%%A
    set DateMonth=%%B
    set DateYear=%%C
set CurrentDate=%DateDay%-%DateMonth%-%DateYear%
md %CurrentDate%

This will give you a newly created folder with today’s date, in the format of DD-MM-YY

Sourced from: Ali's Knowledge Base

Fastest way to extract frames using ffmpeg?

This worked for me

ffmpeg -i file.mp4 -vf fps=1 %d.jpg

How to calculate an angle from three points?

      Atan2        output in degrees
       PI/2              +90
         |                | 
         |                |    
   PI ---.--- 0   +180 ---.--- 0       
         |                |
         |                |
       -PI/2             +270

public static double CalculateAngleFromHorizontal(double startX, double startY, double endX, double endY)
    var atan = Math.Atan2(endY - startY, endX - startX); // Angle in radians
    var angleDegrees = atan * (180 / Math.PI);  // Angle in degrees (can be +/-)
    if (angleDegrees < 0.0)
        angleDegrees = 360.0 + angleDegrees;
    return angleDegrees;

// Angle from point2 to point 3 counter clockwise
public static double CalculateAngle0To360(double centerX, double centerY, double x2, double y2, double x3, double y3)
    var angle2 = CalculateAngleFromHorizontal(centerX, centerY, x2, y2);
    var angle3 = CalculateAngleFromHorizontal(centerX, centerY, x3, y3);
    return (360.0 + angle3 - angle2)%360;

// Smaller angle from point2 to point 3
public static double CalculateAngle0To180(double centerX, double centerY, double x2, double y2, double x3, double y3)
    var angle = CalculateAngle0To360(centerX, centerY, x2, y2, x3, y3);
    if (angle > 180.0)
        angle = 360 - angle;
    return angle;


What is context in _.each(list, iterator, [context])?

The context parameter just sets the value of this in the iterator function.

var someOtherArray = ["name","patrick","d","w"];

_.each([1, 2, 3], function(num) { 
    // In here, "this" refers to the same Array as "someOtherArray"

    alert( this[num] ); // num is the value from the array being iterated
                        //    so this[num] gets the item at the "num" index of
                        //    someOtherArray.
}, someOtherArray);

Working Example:

It uses the number from each member of the Array being iterated to get the item at that index of someOtherArray, which is represented by this since we passed it as the context parameter.

If you do not set the context, then this will refer to the window object.

jQuery UI Dialog OnBeforeUnload

this works for me

$(window).bind('beforeunload', function() {
      return 'Do you really want to leave?' ;

How to compile C program on command line using MinGW?

I once had this kind of problem installing MinGW to work in Windows, even after I added the right System PATH in my Environment Variables.

After days of misery, I finally stumbled on a thread that recommended uninstalling the original MinGW compiler and deleting the C:\MinGW folder and installing TDM-GCC MinGW compiler which can be found here.

You have options of choosing a 64/32-bit installer from the download page, and it creates the environment path variables for you too.

How to set corner radius of imageView?

Swift 3, Xcode 8, iOS 10

DispatchQueue.main.async {
  self.mainImageView.layer.cornerRadius = self.mainImageView.bounds.size.width / 2.0
  self.mainImageView.clipsToBounds = true

C: Run a System Command and Get Output?

You want the "popen" function. Here's an example of running the command "ls /etc" and outputing to the console.

#include <stdio.h>
#include <stdlib.h>

int main( int argc, char *argv[] )

  FILE *fp;
  char path[1035];

  /* Open the command for reading. */
  fp = popen("/bin/ls /etc/", "r");
  if (fp == NULL) {
    printf("Failed to run command\n" );

  /* Read the output a line at a time - output it. */
  while (fgets(path, sizeof(path), fp) != NULL) {
    printf("%s", path);

  /* close */

  return 0;

how to use javascript Object.defineProperty

Object.defineProperty(Array.prototype, "last", {_x000D_
  get: function() {_x000D_
    if (this[this.length -1] == undefined) { return [] }_x000D_
    else { return this[this.length -1] }_x000D_
console.log([1,2,3,4].last) //returns 4

Align button at the bottom of div using CSS

You can use position:absolute; to absolutely position an element within a parent div. When using position:absolute; the element will be positioned absolutely from the first positioned parent div, if it can't find one it will position absolutely from the window so you will need to make sure the content div is positioned.

To make the content div positioned, all position values that aren't static will work, but relative is the easiest since it doesn't change the divs positioning by itself.

So add position:relative; to the content div, remove the float from the button and add the following css to the button:

position: absolute;
right:    0;
bottom:   0;

Onchange open URL via select - jQuery

**redirect on change option with jquery** 

 <select id="selectnav1" class="selectnav">
            <option value="#">Menu </option>
            <option value="">
            <option value="">


<script type="text/javascript">
   $(function () {

        $('#selectnav1').change( function() {
      location.href = $(this).val();

How do I parse a string to a float or int?

Pass your string to this function:

def string_to_number(str):
  if("." in str):
      res = float(str)
      res = str  
    res = int(str)
    res = str

It will return int, float or string depending on what was passed.

string that is an int

<class 'int'>

string that is a float

<class 'float'>

string that is a string

<class 'str'>

string that looks like a float

<class 'str'>

How to printf "unsigned long" in C?

For int %d

For long int %ld

For long long int %lld

For unsigned long long int %llu

Spring Boot + JPA : Column name annotation ignored

teteArg, thank you so much. Just an added information so, everyone bumping into this question will be able to understand why.

What teteArg said is indicated on the Spring Boot Common Properties:

Apparently, spring.jpa.hibernate.naming.strategy is not a supported property for Spring JPA implementation using Hibernate 5.

Spring Boot and multiple external configuration files

I had the same problem. I wanted to have the ability to overwrite an internal configuration file at startup with an external file, similar to the Spring Boot detection. In my case it's a file where my applications users are stored.

My requirements:

Load the file from the following locations (in this order)

  1. The classpath
  2. A /config subdir of the current directory.
  3. The current directory
  4. From directory or a file location given by a command line parameter at startup

I came up with the following solution:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;

import java.util.Properties;

import static;

public class PropertiesConfig {

    private static final Logger LOG = LoggerFactory.getLogger(PropertiesConfig.class);

    private final static String PROPERTIES_FILENAME = "";

    private String propertiesLocation;

    Properties userProperties() throws IOException {
        final Resource[] possiblePropertiesResources = {
                new ClassPathResource(PROPERTIES_FILENAME),
                new PathResource("config/" + PROPERTIES_FILENAME),
                new PathResource(PROPERTIES_FILENAME),
                new PathResource(getCustomPath())
        // Find the last existing properties location to emulate spring boot discovery
        final Resource propertiesResource = stream(possiblePropertiesResources)
                .reduce((previous, current) -> current)
        final Properties userProperties = new Properties();

        userProperties.load(propertiesResource.getInputStream());"Using {} as user resource", propertiesResource);

        return userProperties;

    private String getCustomPath() {
        return propertiesLocation.endsWith(".properties") ? propertiesLocation : propertiesLocation + PROPERTIES_FILENAME;


Now the application uses the classpath resource, but checks for a resource at the other given locations too. The last resource which exists will be picked and used. I'm able to start my app with java -jar myapp.jar --properties.location=/directory/ to use an properties location which floats my boat.

An important detail here: Use an empty String as default value for the properties.location in the @Value annotation to avoid errors when the property is not set.

The convention for a properties.location is: Use a directory or a path to a properties file as properties.location.

If you want to override only specific properties, a PropertiesFactoryBean with setIgnoreResourceNotFound(true) can be used with the resource array set as locations.

I'm sure that this solution can be extended to handle multiple files...


Here my solution for multiple files :) Like before, this can be combined with a PropertiesFactoryBean.

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Map;
import java.util.Properties;

import static;
import static;

class PropertiesConfig {

    private final static Logger LOG = LoggerFactory.getLogger(PropertiesConfig.class);
    private final static String[] PROPERTIES_FILENAMES = {"", "", ""};

    private String propertiesLocation;

    Map<String, Properties> myProperties() {
        return stream(PROPERTIES_FILENAMES)
                .collect(toMap(filename -> filename, this::loadProperties));

    private Properties loadProperties(final String filename) {
        final Resource[] possiblePropertiesResources = {
                new ClassPathResource(filename),
                new PathResource("config/" + filename),
                new PathResource(filename),
                new PathResource(getCustomPath(filename))
        final Resource resource = stream(possiblePropertiesResources)
                .reduce((previous, current) -> current)
        final Properties properties = new Properties();

        try {
        } catch(final IOException exception) {
            throw new RuntimeException(exception);
        }"Using {} as user resource", resource);

        return properties;

    private String getCustomPath(final String filename) {
        return propertiesLocation.endsWith(".properties") ? propertiesLocation : propertiesLocation + filename;


Git: How to rebase to a specific commit?

Adding to the answers using --onto:

I never learned it by heart, so I wrote this little helper script:
Git: Rebase a (sub)branch from one base to another, leaving the other base's commits.


moveBranch <branch> from <previous-base> to <new-base>

In short:

git rebase --onto "$3" "$2" "$1"

Besides that, one more solution usable for similar purposes, is cherry-picking a streak of commits:

git co <new-base> 
git cherry-pick <previous-base>..<branch>
git branch -f branch

Which has more less the same effect. Note that this syntax SKIPS the commit at <previous-branch> itself, so it cherry-picks the next and the following up to, including, the commit at <branch>.

HTML to PDF with Node.js

In addition to @Jozzhart Answer, you can make a local html; serve it with express; and use phantom to make PDF from it; something like this:

const exp = require('express');
const app = exp();
const pth = require("path");
const phantom = require('phantom');
const ip = require("ip");

const PORT = 3000;
const PDF_SOURCE = "index"; //index.html
const PDF_OUTPUT = "out"; //out.pdf

const source = pth.join(__dirname, "", `${PDF_SOURCE}.html`);
const output = pth.join(__dirname, "", `${PDF_OUTPUT}.pdf`);

app.use("/" + PDF_SOURCE, exp.static(source));
app.use("/" + PDF_OUTPUT, exp.static(output));


let makePDF = async (fn) => {
    let local = `http://${ip.address()}:${PORT}/${PDF_SOURCE}`;
    phantom.create().then((ph) => {
        ph.createPage().then((page) => {
                page.render(output).then(() => { ph.exit(); fn() })

makePDF(() => {
    console.log("PDF Created From Local File");
    console.log("PDF is downloadable from link:");

and index.html can be anything:

<h1>PDF HEAD</h1>
<a href="#">LINK</a>


enter image description here

jQuery adding 2 numbers from input fields

Ok so your code actually works but what you need to do is replace a and b in your click function with the jquery notation you used before the click. This will ensure you have the correct and most up to date values. so changing your click function to this should work:

$("submit").on("click", function(){
    var sum = $("#a").val().match(/\d+/) + $("#b").val().match(/\d+/);

or inlined to:

$("submit").on("click", function(){
    alert($("#a").val().match(/\d+/) + $("#b").val().match(/\d+/));         

Fill remaining vertical space with CSS using display:flex

Here is the codepen demo showing the solution:

Important highlights:

  • all containers from html, body, ... .container, should have the height set to 100%
  • introducing flex to ANY of the flex items will trigger calculation of the items sizes based on flex distribution:
    • if only one cell is set to flex, for example: flex: 1 then this flex item will occupy the remaining of the space
    • if there are more than one with the flex property, the calculation will be more complicated. For example, if the item 1 is set to flex: 1 and the item 2 is se to flex: 2 then the item 2 will take twice more of the remaining space
  • Main Size Property

How do I declare an array of undefined or no initial size?

One way I can imagine is to use a linked list to implement such a scenario, if you need all the numbers entered before the user enters something which indicates the loop termination. (posting as the first option, because have never done this for user input, it just seemed to be interesting. Wasteful but artistic)

Another way is to do buffered input. Allocate a buffer, fill it, re-allocate, if the loop continues (not elegant, but the most rational for the given use-case).

I don't consider the described to be elegant though. Probably, I would change the use-case (the most rational).

Find the most frequent number in a NumPy array

Expanding on this method, applied to finding the mode of the data where you may need the index of the actual array to see how far away the value is from the center of the distribution.

(_, idx, counts) = np.unique(a, return_index=True, return_counts=True)
index = idx[np.argmax(counts)]
mode = a[index]

Remember to discard the mode when len(np.argmax(counts)) > 1

XAMPP Port 80 in use by "Unable to open process" with PID 4

Simply set Apache to listen on a different port. This can be done by clicking on the "Config" button on the same line as the "Apache" module, select the "httpd.conf" file in the dropdown, then change the "Listen 80" line to "Listen 8080". Save the file and close it.

Now it avoids Port 80 and uses Port 8080 instead without issue. The only additional thing you need to do is make sure to put localhost:8080 in the browser so the browser knows to look on Port 8080. Otherwise it defaults to Port 80 and won't find your local site.

Angular2 get clicked element id

If you want to have access to the id attribute of the button you can leverage the srcElement property of the event:

import {Component} from 'angular2/core';

  selector: 'my-app',
  template: `
    <button (click)="onClick($event)" id="test">Click</button>
export class AppComponent {
  onClick(event) {
    var target = || event.srcElement || event.currentTarget;
    var idAttr =;
    var value = idAttr.nodeValue;

See this plunkr:

See this question:

Easiest way to detect Internet connection on iOS?

It is possible and it is really simple if you look at it when finishing the implementation, which is again - very simple, since the only items you need are two boolean variables: internet reachability and host reachability (you often need more than one of these). Once you assemble your helper class that can determine the connections status, you really don't care again of the implementation needed for knowing these procedures.


#import <Foundation/Foundation.h>

@class Reachability;

@interface ConnectionManager : NSObject {
    Reachability *internetReachable;
    Reachability *hostReachable;

@property BOOL internetActive;
@property BOOL hostActive;

- (void) checkNetworkStatus:(NSNotification *)notice;


And the .m file:

#import "ConnectionManager.h"
#import "Reachability.h"

@implementation ConnectionManager
@synthesize internetActive, hostActive;

-(id)init {
    self = [super init];
    if(self) {

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkNetworkStatus:) name:kReachabilityChangedNotification object:nil];

    internetReachable = [[Reachability reachabilityForInternetConnection] retain];
    [internetReachable startNotifier];

    hostReachable = [[Reachability reachabilityWithHostName:@""] retain];
    [hostReachable startNotifier];

    return self;

- (void) checkNetworkStatus:(NSNotification *)notice {
    NetworkStatus internetStatus = [internetReachable currentReachabilityStatus];
    switch (internetStatus)

        case NotReachable:
            NSLog(@"The internet is down.");
            self.internetActive = NO;


        case ReachableViaWiFi:
            NSLog(@"The internet is working via WIFI.");
            self.internetActive = YES;


        case ReachableViaWWAN:
            NSLog(@"The internet is working via WWAN.");
            self.internetActive = YES;



    NetworkStatus hostStatus = [hostReachable currentReachabilityStatus];
    switch (hostStatus)

        case NotReachable:
            NSLog(@"A gateway to the host server is down.");
            self.hostActive = NO;


        case ReachableViaWiFi:
            NSLog(@"A gateway to the host server is working via WIFI.");
            self.hostActive = YES;


        case ReachableViaWWAN:
            NSLog(@"A gateway to the host server is working via WWAN.");
            self.hostActive = YES;




// If lower than SDK 5 : Otherwise, remove the observer as pleased.

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [super dealloc];


ArrayIndexOutOfBoundsException when using the ArrayList's iterator

List<String> arrayList = new ArrayList<String>();
for (String s : arrayList) {
        //do something


for (int i = 0; i < arrayList.size(); i++) {
        //do something

But be carefull ArrayList can hold null values. So comparation should be


when you are sure that value is not null or you should check if given element is null.

How to convert IPython notebooks to PDF and HTML?

Other suggested approaches:

  1. Using the 'Print and then select save as pdf.' from your HTML file will result in loss of border edges, highlighting of syntax, trimming of plots etc.

  2. Some other libraries have shown to be broken when it comes to using obsolete versions.

Solution: A better, hassle-free option is to use an online converter which will convert the *.html version of your *.ipynb to *.pdf.


  1. First, from your Jupyter notebook interface, convert your *.ipynb to *.html using:

File > Download as > HTML(.html)

  1. Upload the newly created *.html file here and then select the option HTML to PDF.

  2. Your pdf file is now ready for download.

  3. You now have .ipynb, .html and .pdf files

c++ bool question

Yes that is correct. "Boolean variables only have two possible values: true (1) and false (0)." cpp tutorial on boolean values

Bash integer comparison

The zeroth parameter of a shell command is the command itself (or sometimes the shell itself). You should be using $1.

(("$#" < 1)) && ( (("$1" != 1)) ||  (("$1" -ne 0q)) )

Your boolean logic is also a bit confused:

(( "$#" < 1 && # If the number of arguments is less than one…
  "$1" != 1 || "$1" -ne 0)) # …how can the first argument possibly be 1 or 0?

This is probably what you want:

(( "$#" )) && (( $1 == 1 || $1 == 0 )) # If true, there is at least one argument and its value is 0 or 1

Key hash for Android-Facebook app

There are two methods available complex one and the easy one

Methods One :(little Complex)

first of all you have to download ssl 64bit or 32bit accordingly, remember to download the file with name containing e after version code OR not with the k after the version code,

and place in AndroidStudio/jre/bin directory, if you dont know where to place, you can find this directory by right clicking on the android studio shortcut as:

enter image description here

now you have managed two required things in one place, but still you have to find the path for your debug.keystore, that is always can be found in the "C:\Users\yourusernamehere\.android\debug.keystore",

NOTE If your app is published already, or about to publish then use your publishing signing keystore, if and only if your are testing in development mode than you can use debug,keysotre

As everything is setup, let arrange the command you wanted to execute for the hash key generation in base64 format, and you command will look like this

keytool.exe -exportcert -alias androiddebugkey -keystore "C:\Users\ayyaz talat\.android\debug.keystore" | "D:\Program Files\Android\Android Studio\jre\bin\openssl\bin\openssl.exe" sha1 -binary |"D:\Program Files\Android\Android Studio\jre\bin\openssl\bin\openssl.exe" base64

it will promt you to enter a password for the debug.keystore, which is android by default. if you are using your own key than the password will be also yours. the output will look like this if everything goes well as expected, hope it may help

enter image description here

Second Method (Respectively easy one)

if you dont want to go throught all the above procedure, then just use the following method to log the haskey:

 private void printKeyHash() {
        try {
            PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_SIGNATURES);
            for (Signature signature : info.signatures) {
                MessageDigest md = MessageDigest.getInstance("SHA1");
                Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
        } catch (PackageManager.NameNotFoundException e) {
            Log.e("KeyHash:", e.toString());
        } catch (NoSuchAlgorithmException e) {
            Log.e("KeyHash:", e.toString());


enter image description here

IOCTL Linux device driver

The ioctl function is useful for implementing a device driver to set the configuration on the device. e.g. a printer that has configuration options to check and set the font family, font size etc. ioctl could be used to get the current font as well as set the font to a new one. A user application uses ioctl to send a code to a printer telling it to return the current font or to set the font to a new one.

int ioctl(int fd, int request, ...)
  1. fd is file descriptor, the one returned by open;
  2. request is request code. e.g GETFONT will get the current font from the printer, SETFONT will set the font on the printer;
  3. the third argument is void *. Depending on the second argument, the third may or may not be present, e.g. if the second argument is SETFONT, the third argument can be the font name such as "Arial";

int request is not just a macro. A user application is required to generate a request code and the device driver module to determine which configuration on device must be played with. The application sends the request code using ioctl and then uses the request code in the device driver module to determine which action to perform.

A request code has 4 main parts

    1. A Magic number - 8 bits
    2. A sequence number - 8 bits
    3. Argument type (typically 14 bits), if any.
    4. Direction of data transfer (2 bits).  

If the request code is SETFONT to set font on a printer, the direction for data transfer will be from user application to device driver module (The user application sends the font name "Arial" to the printer). If the request code is GETFONT, direction is from printer to the user application.

In order to generate a request code, Linux provides some predefined function-like macros.

1._IO(MAGIC, SEQ_NO) both are 8 bits, 0 to 255, e.g. let us say we want to pause printer. This does not require a data transfer. So we would generate the request code as below

#define PRIN_MAGIC 'P'
#define NUM 0

and now use ioctl as

ret_val = ioctl(fd, PAUSE_PRIN);

The corresponding system call in the driver module will receive the code and pause the printer.

  1. __IOW(MAGIC, SEQ_NO, TYPE) MAGIC and SEQ_NO are the same as above, and TYPE gives the type of the next argument, recall the third argument of ioctl is void *. W in __IOW indicates that the data flow is from user application to driver module. As an example, suppose we want to set the printer font to "Arial".
#define PRIN_MAGIC 'S'
#define SEQ_NO 1
#define SETFONT __IOW(PRIN_MAGIC, SEQ_NO, unsigned long)


char *font = "Arial";
ret_val = ioctl(fd, SETFONT, font); 

Now font is a pointer, which means it is an address best represented as unsigned long, hence the third part of _IOW mentions type as such. Also, this address of font is passed to corresponding system call implemented in device driver module as unsigned long and we need to cast it to proper type before using it. Kernel space can access user space and hence this works. other two function-like macros are __IOR(MAGIC, SEQ_NO, TYPE) and __IORW(MAGIC, SEQ_NO, TYPE) where the data flow will be from kernel space to user space and both ways respectively.

Please let me know if this helps!

Count the number of commits on a Git branch

As the OP references Number of commits on branch in git I want to add that the given answers there also work with any other branch, at least since git version 2.17.1 (and seemingly more reliably than the answer by Peter van der Does):

working correctly:

git checkout current-development-branch
git rev-list --no-merges --count master..
git checkout -b testbranch_2
git rev-list --no-merges --count current-development-branch..

The last command gives zero commits as expected since I just created the branch. The command before gives me the real number of commits on my development-branch minus the merge-commit(s)

not working correctly:

git checkout current-development-branch
git rev-list --no-merges --count HEAD
git checkout -b testbranch_1
git rev-list --no-merges --count HEAD

In both cases I get the number of all commits in the development branch and master from which the branches (indirectly) descend.

How to pass a textbox value from view to a controller in MVC 4?

I'll just try to answer the question but my examples very simple because I'm new at mvc. Hope this help somebody.

    [HttpPost]  ///This function is in my controller class
    public ActionResult Delete(string txtDelete)
        int _id = Convert.ToInt32(txtDelete); // put your code           

This code is in my controller's cshtml

  >   @using (Html.BeginForm("Delete", "LibraryManagement"))
@Html.Label("Enter an ID number");
@Html.TextBox("txtDelete")  }  

Just make sure the textbox name and your controller's function input are the same name and type(string).This way, your function get the textbox input.

When to use 'npm start' and when to use 'ng serve'?

There are more than that. The executed executables are different.

npm run start

will run your projects local executable which is located in your node_modules/.bin.

ng serve

will run another executable which is global.

It means if you clone and install an Angular project which is created with angular-cli version 5 and your global cli version is 7, then you may have problems with ng build.

The following classes could not be instantiated: -

Another mistake that can have the same effect can be the wrong theme in the preview. For some reason I had selected some other theme here. After choosing my AppTheme it worked fine again:

layout options

Base64: java.lang.IllegalArgumentException: Illegal character

The Base64.Encoder.encodeToString method automatically uses the ISO-8859-1 character set.

For an encryption utility I am writing, I took the input string of cipher text and Base64 encoded it for transmission, then reversed the process. Relevant parts shown below. NOTE: My file.encoding property is set to ISO-8859-1 upon invocation of the JVM so that may also have a bearing.

static String getBase64EncodedCipherText(String cipherText) {
    byte[] cText = cipherText.getBytes();
    // return an ISO-8859-1 encoded String
    return Base64.getEncoder().encodeToString(cText);

static String getBase64DecodedCipherText(String encodedCipherText) throws IOException {
    return new String((Base64.getDecoder().decode(encodedCipherText)));

public static void main(String[] args) {
    try {
        String cText = getRawCipherText(null, "Hello World of Encryption...");

        System.out.println("Text to encrypt/encode: Hello World of Encryption...");
        // This output is a simple sanity check to display that the text
        // has indeed been converted to a cipher text which 
        // is unreadable by all but the most intelligent of programmers.
        // It is absolutely inhuman of me to do such a thing, but I am a
        // rebel and cannot be trusted in any way.  Please look away.
        System.out.println("RAW CIPHER TEXT: " + cText);
        cText = getBase64EncodedCipherText(cText);
        System.out.println("BASE64 ENCODED: " + cText);
        // There he goes again!!
        System.out.println("BASE64 DECODED:  " + getBase64DecodedCipherText(cText));
        System.out.println("DECODED CIPHER TEXT: " + decodeRawCipherText(null, getBase64DecodedCipherText(cText)));
    } catch (Exception e) {


The output looks like:

Text to encrypt/encode: Hello World of Encryption...
RAW CIPHER TEXT: q$;?C?l??<8??U???X[7l
BASE64 ENCODED: HnEPJDuhQ+qDbInUCzw4gx0VDqtVwef+WFs3bA==
BASE64 DECODED:  q$;?C?l??<8??U???X[7l``
DECODED CIPHER TEXT: Hello World of Encryption...

Delete all rows in table

You can rename the table in question, create a table with an identical schema, and then drop the original table at your leisure.

See the MySQL 5.1 Reference Manual for the [RENAME TABLE][1] and [CREATE TABLE][2] commands.

RENAME TABLE tbl TO tbl_old;

CREATE TABLE tbl LIKE tbl_old;

DROP TABLE tbl_old; -- at your leisure

This approach can help minimize application downtime.

Android: How do bluetooth UUIDs work?

The UUID stands for Universally Unique Identifier. UUID is an simple 128 bit digit which uniquely distributed across the world.

Bluetooth sends data over air and all nearby device can receive it. Let's suppose, sometimes you have to send some important files via Bluetooth and all near by devices can access it in range. So when you pair with the other devices, they simply share the UUID number and match before sharing the files. When you send any file then your device encrypt that file with appropriate device UUID and share over the network. Now all Bluetooth devices in the range can access the encrypt file but they required right UUID number. So Only right UUID devices have access to encrypt the file and others will reject cause of wrong UUID.

In short, you can use UUID as a secret password for sharing files between any two Bluetooth devices.

Splitting a C++ std::string using tokens, e.g. ";"

You could use a string stream and read the elements into the vector.

Here are many different examples...

A copy of one of the examples:

std::vector<std::string> split(const std::string& s, char seperator)
   std::vector<std::string> output;

    std::string::size_type prev_pos = 0, pos = 0;

    while((pos = s.find(seperator, pos)) != std::string::npos)
        std::string substring( s.substr(prev_pos, pos-prev_pos) );


        prev_pos = ++pos;

    output.push_back(s.substr(prev_pos, pos-prev_pos)); // Last word

    return output;

Appending to list in Python dictionary

dates_dict[key] = dates_dict.get(key, []).append(date) sets dates_dict[key] to None as list.append returns None.

In [5]: l = [1,2,3]

In [6]: var = l.append(3)

In [7]: print var

You should use collections.defaultdict

import collections
dates_dict = collections.defaultdict(list)

Android; Check if file exists without creating a new one

The methods in the Path class are syntactic, meaning that they operate on the Path instance. But eventually you must access the file system to verify that a particular Path exists

 File file = new File("FileName");
 System.out.println("file is already there");
 System.out.println("Not find file ");

HTML Agility pack - parsing tables

How about something like: Using HTML Agility Pack

HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(@"<html><body><p><table id=""foo""><tr><th>hello</th></tr><tr><td>world</td></tr></table></body></html>");
foreach (HtmlNode table in doc.DocumentNode.SelectNodes("//table")) {
    Console.WriteLine("Found: " + table.Id);
    foreach (HtmlNode row in table.SelectNodes("tr")) {
        foreach (HtmlNode cell in row.SelectNodes("th|td")) {
            Console.WriteLine("cell: " + cell.InnerText);

Note that you can make it prettier with LINQ-to-Objects if you want:

var query = from table in doc.DocumentNode.SelectNodes("//table").Cast<HtmlNode>()
            from row in table.SelectNodes("tr").Cast<HtmlNode>()
            from cell in row.SelectNodes("th|td").Cast<HtmlNode>()
            select new {Table = table.Id, CellText = cell.InnerText};

foreach(var cell in query) {
    Console.WriteLine("{0}: {1}", cell.Table, cell.CellText);

JavaScript array to CSV

If your data contains any newlines or commas, you will need to escape those first:

const escape = text =>
    text.replace(/\\/g, "\\\\")
        .replace(/\n/g, "\\n")
        .replace(/,/g, "\\,")

escaped_array = =>

Then simply do:

csv = => fields.join(","))

If you want to make it downloadable in-browser:

dl = "data:text/csv;charset=utf-8," + csv

Spring MVC - How to get all request params in a map in Spring controller?

Here is the simple example of getting request params in a Map.

 @RequestMapping(value="submitForm.html", method=RequestMethod.POST)
     public ModelAndView submitForm(@RequestParam Map<String, String> reqParam) 
          String name  = reqParam.get("studentName");
          String email = reqParam.get("studentEmail");

          ModelAndView model = new ModelAndView("AdmissionSuccess");
          model.addObject("msg", "Details submitted by you::
          Name: " + name + ", Email: " + email );

In this case, it will bind the value of studentName and studentEmail with name and email variables respectively.

Sql Server return the value of identity column after insert statement

Here goes a bunch of different ways to get the ID, including Scope_Identity:

What is CMake equivalent of 'configure --prefix=DIR && make all install '?

Regarding Bruce Adams answer:

Your answer creates dangerous confusion. DESTDIR is intended for installs out of the root tree. It allows one to see what would be installed in the root tree if one did not specify DESTDIR. PREFIX is the base directory upon which the real installation is based.

For example, PREFIX=/usr/local indicates that the final destination of a package is /usr/local. Using DESTDIR=$HOME will install the files as if $HOME was the root (/). If, say DESTDIR, was /tmp/destdir, one could see what 'make install' would affect. In that spirit, DESTDIR should never affect the built objects.

A makefile segment to explain it:

    cp program $DESTDIR$PREFIX/bin/program

Programs must assume that PREFIX is the base directory of the final (i.e. production) directory. The possibility of symlinking a program installed in DESTDIR=/something only means that the program does not access files based upon PREFIX as it would simply not work. cat(1) is a program that (in its simplest form) can run from anywhere. Here is an example that won't:

    sed -e "s/@prefix@/$PREFIX/" > prog.pseudo
    compile prog.pseudo

    cp prog $DESTDIR$PREFIX/bin/prog
    cp prog.db $DESTDIR$PREFIX/share/prog.db

If you tried to run prog from elsewhere than $PREFIX/bin/prog, prog.db would never be found as it is not in its expected location.

Finally, /etc/alternatives really does not work this way. There are symlinks to programs installed in the root tree (e.g. vi -> /usr/bin/nvi, vi -> /usr/bin/vim, etc.).

Remove end of line characters from Java string

Regex with replaceAll.

public class Main
    public static void main(final String[] argv) 
        String str;

        str = "hello\r\njava\r\nbook";
        str = str.replaceAll("(\\r|\\n)", "");

If you only want to remove \r\n when they are pairs (the above code removes either \r or \n) do this instead:

str = str.replaceAll("\\r\\n", "");

iOS 7 App Icons, Launch images And Naming Convention While Keeping iOS 6 Icons

In case you do not want to use Asset Catalog, you can add an iOS 7 icon for an old app by creating a 120x120 .png image. Name it Icon-120.png and drag in to the project.

Under TARGET > Your App > Info > Icon files, add one more entry in the Target Properties:

enter image description here

I tested on Xcode 5 and an app was submitted without the missing retina icon warning.

How to display and hide a div with CSS?

You need

.abc,.ab {
    display: none;

#f:hover ~ .ab {
    display: block;

#s:hover ~ .abc {
    display: block;

#s:hover ~ .a,
#f:hover ~ .a{
    display: none;

Updated demo at

The problem in your original CSS was that the , in css selectors starts a completely new selector. it is not combined.. so #f:hover ~ .abc,.a means #f:hover ~ .abc and .a. You set that to display:none so it was always set to be hidden for all .a elements.

Fixed position but relative to container

The magic is to take the screen width minus the container width and divide it by 2:

//1400px is according to container max-width (left can be also right)
.fixed {
  position: fixed;
  right: calc((100vw - 1400px)/2);

Note: css calc() function is almost, but not 100% supported. For most use-cases it is definitely supported enough. Click here for more details

Snippet (with a 300px container just to fit this website's widget):

.container {
  max-width: 300px;
  margin-left: auto;
  margin-right: auto;

.fixed {
  position: fixed;
  right: calc((100vw - 300px)/2);

@media screen and (max-width: 300px) {
  right: 0px;
<div style="height: 3000px">
    <div class="container">
        <button class="fixed">
            FIXED CONTENT
    Lorem ipsum dolor sit amet consectetur adipisicing elit. Laborum, eum? Animi quidem accusamus minima vel, dolorem suscipit quia accusantium minus harum modi commodi distinctio! Iste voluptatum earum quam voluptate culpa ad, ipsum dolorum recusandae quis atque eligendi necessitatibus magnam nisi dolores beatae qui? Perspiciatis natus cum nostrum in quod odio sapiente doloremque rerum quo dolore tenetur facere, quisquam atque accusamus fugiat eligendi, deleniti nisi minus recusandae distinctio dignissimos! Dicta quos ipsum qui pariatur at vel veritatis veniam quisquam minus modi et voluptas aliquam laborum, cumque in quo magnam sapiente. Expedita ut dolore laboriosam tempora reprehenderit vero eaque blanditiis, cumque voluptatibus, velit nemo, veniam tenetur quisquam numquam adipisci quae odio repellendus neque incidunt! Cum odio corporis soluta voluptate nesciunt, quasi nobis deleniti neque porro expedita fugiat placeat alias autem pariatur animi error, dicta veritatis atque perspiciatis inventore tempora dolor ad! Mollitia in dolorem ipsam eos porro magni perspiciatis possimus maiores, itaque facere ut. Eos culpa eum error quia incidunt repellendus quam possimus, asperiores earum ipsum molestias dicta sint fugit atque veniam dolorum illo? Officia harum sint incidunt totam, reiciendis illum eos maxime sequi neque repellat quis, expedita eum, corporis quaerat nemo qui soluta aspernatur animi. Sint ad rem numquam omnis sit.

jQuery: Check if special characters exists in string

You could also use the whitelist method -

var str = $('#Search').val();
var regex = /[^\w\s]/gi;

if(regex.test(str) == true) {
    alert('Your search string contains illegal characters.');

The regex in this example is digits, word characters, underscores (\w) and whitespace (\s). The caret (^) indicates that we are to look for everything that is not in our regex, so look for things that are not word characters, underscores, digits and whitespace.

Android. WebView and loadData

the answers above doesn't work in my case. You need to specify utf-8 in meta tag

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <!-- you content goes here -->

How to SFTP with PHP?

PHP has ssh2 stream wrappers (disabled by default), so you can use sftp connections with any function that supports stream wrappers by using ssh2.sftp:// for protocol, e.g.

file_get_contents('ssh2.sftp://user:[email protected]:22/path/to/filename');

or - when also using the ssh2 extension

$connection = ssh2_connect('', 22);
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);
$stream = fopen("ssh2.sftp://$sftp/path/to/file", 'r');


On a side note, there is also quite a bunch of questions about this topic already:

Colouring plot by factor in R

plot(data$Sepal.Length, data$Sepal.Width, col=data$Species)

should do it for you. But I prefer ggplot2 and would suggest that for better graphics in R.

How to fix "Only one expression can be specified in the select list when the subquery is not introduced with EXISTS" error?

Try this:

    (Select Count(*) 
        From LoginFails 
        Where username = '" + LoginModel.Username + "' And IP = '" + Request.ServerVariables["REMOTE_ADDR"] + "')
 From Users 
 Where username = '" + LoginModel.Username + "'

And I recommend you strongly to use parameters in your query to avoid security risks with sql injection attacks!

Hope that helps!

How to watch and reload ts-node when TypeScript files change

I've dumped nodemon and ts-node in favor of a much better alternative, ts-node-dev

Just run ts-node-dev src/index.ts

Force the origin to start at 0

In the latest version of ggplot2, this can be more easy.

p <- ggplot(mtcars, aes(wt, mpg))
p + geom_point()
p+ geom_point() + scale_x_continuous(expand = expansion(mult = c(0, 0))) + scale_y_continuous(expand = expansion(mult = c(0, 0)))

enter image description here

See ?expansion() for more details.

Unable to copy ~/.ssh/

The following is also working for me:

ssh <user>@<host>  "cat <filepath>"|pbcopy 

Simple Pivot Table to Count Unique Values

Excel 2013 can do Count distinct in pivots. If no access to 2013, and it's a smaller amount of data, I make two copies of the raw data, and in copy b, select both columns and remove duplicates. Then make the pivot and count your column b.

Convert Text to Uppercase while typing in Text box

Edit (for ASP.NET)

After you edited your question it's cler you're using ASP.NET. Things are pretty different there (because in that case a roundtrip to server is pretty discouraged). You can do same things with JavaScript (but to handle globalization with toUpperCase() may be a pain) or you can use CSS classes (relying on browsers implementation). Simply declare this CSS rule:

    text-transform: uppercase

And add upper-case class to your text-box:

<asp:TextBox ID="TextBox1" CssClass="upper-case" runat="server"/>

General (Old) Answer

but it capitalize characters after pressing Enter key.

It depends where you put that code. If you put it in, for example, TextChanged event it'll make upper case as you type.

You have a property that do exactly what you need: CharacterCasing:

TextBox1.CharacterCasing = CharacterCasing.Upper;

It works more or less but it doesn't handle locales very well. For example in German language ß is SS when converted in upper case (Institut für Deutsche Sprache) and this property doesn't handle that.

You may mimic CharacterCasing property adding this code in KeyPress event handler:

e.KeyChar = Char.ToUpper(e.KeyChar);

Unfortunately .NET framework doesn't handle this properly and upper case of sharp s character is returned unchanged. An upper case version of ß exists and it's ? and it may create some confusion, for example a word containing "ss" and another word containing "ß" can't be distinguished if you convert in upper case using "SS"). Don't forget that:

However, in 2010 the use of the capital sharp s became mandatory in official documentation when writing geographical names in all-caps.

There isn't much you can do unless you add proper code for support this (and others) subtle bugs in .NET localization. Best advice I can give you is to use a custom dictionary per each culture you need to support.

Finally don't forget that this transformation may be confusing for your users: in Turkey, for example, there are two different versions of i upper case letter.

If text processing is important in your application you can solve many issues using specialized DLLs for each locale you support like Word Processors do.

What I usually do is to do not use standard .NET functions for strings when I have to deal with culture specific issues (I keep them only for text in invariant culture). I create a Unicode class with static methods for everything I need (character counting, conversions, comparison) and many specialized derived classes for each supported language. At run-time that static methods will user current thread culture name to pick proper implementation from a dictionary and to delegate work to that. A skeleton may be something like this:

abstract class Unicode
    public static string ToUpper(string text)
        return GetConcreteClass().ToUpperCore(text);

    protected virtual string ToUpperCore(string text)
        // Default implementation, overridden in derived classes if needed
        return text.ToUpper();

    private Dictionary<string, Unicode> _implementations;

    private Unicode GetConcreteClass()
        string cultureName = Thread.Current.CurrentCulture.Name;

        // Check if concrete class has been loaded and put in dictionary

        return _implementations[cultureName];

I'll then have an implementation specific for German language:

sealed class German : Unicode
    protected override string ToUpperCore(string text)
        // Very naive implementation, just to provide an example
        return text.ToUpper().Replace("ß", "?");

True implementation may be pretty more complicate (not all OSes supports upper case ?) but take as a proof of concept. See also this post for other details about Unicode issues on .NET.

Android WebView, how to handle redirects in app instead of opening a browser

Create a class that implements webviewclient and add the following code that allows ovveriding the url string as shown below. You can see these [example][1]

public class myWebClient extends WebViewClient {

    public boolean shouldOverrideUrlLoading(WebView view, String url) {
         return true;

On your constructor, create a webview object as shown below.

   web = new WebView(this); web.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.FILL_PARENT)); 

Then add the following code to perform loading of urls inside your app

       WebSettings settings=web.getSettings(); 
    web.setWebViewClient(new myWebClient()); 
 web.setWebChromeClient(new WebChromeClient() {

Send array with Ajax to PHP script

If you have been trying to send a one dimentional array and jquery was converting it to comma separated values >:( then follow the code below and an actual array will be submitted to php and not all the comma separated bull**it.

Say you have to attach a single dimentional array named myvals.

jQuery('#someform').on('submit', function (e) {
    var data = $(this).serializeArray();

    var myvals = [21, 52, 13, 24, 75]; // This array could come from anywhere you choose 
    for (i = 0; i < myvals.length; i++) {
            name: "myvals[]", // These blank empty brackets are imp!
            value: myvals[i]

    type: "post",
    url: jQuery(this).attr('action'),
    dataType: "json",
    data: data, // You have to just pass our data variable plain and simple no Rube Goldberg sh*t.
    success: function (r) {

Now inside php when you do this


You will get ..

    [someinputinsidetheform] => 023
    [anotherforminput] => 111
    [myvals] => Array
            [0] => 21
            [1] => 52
            [2] => 13
            [3] => 24
            [4] => 75

Pardon my language, but there are hell lot of Rube-Goldberg solutions scattered all over the web and specially on SO, but none of them are elegant or solve the problem of actually posting a one dimensional array to php via ajax post. Don't forget to spread this solution.

Read file from aws s3 bucket using node fs

I couldn't figure why yet, but the createReadStream/pipe approach didn't work for me. I was trying to download a large CSV file (300MB+) and I got duplicated lines. It seemed a random issue. The final file size varied in each attempt to download it.

I ended up using another way, based on AWS JS SDK examples:

var s3 = new AWS.S3();
var params = {Bucket: 'myBucket', Key: 'myImageFile.jpg'};
var file = require('fs').createWriteStream('/path/to/file.jpg');

    on('httpData', function(chunk) { file.write(chunk); }).
    on('httpDone', function() { file.end(); }).

This way, it worked like a charm.

Spring MVC: Complex object as GET @RequestParam

You can absolutely do that, just remove the @RequestParam annotation, Spring will cleanly bind your request parameters to your class instance:

public @ResponseBody List<MyObject> myAction(
    @RequestParam(value = "page", required = false) int page,
    MyObject myObject)

Unable to generate an explicit migration in entity framework

I had the same problem. Apparently entity framework generates this error when it's unable to connect to the database. So make sure that you're able to access it before searching for other problems.

anaconda - path environment variable in windows

To export the exact set of paths used by Anaconda, use the command echo %PATH% in Anaconda Prompt. This is needed to avoid problems with certain libraries such as SSL.


How can I discover the "path" of an embedded resource?

I'm guessing that your class is in a different namespace. The canonical way to solve this would be to use the resources class and a strongly typed resource:


Use the IDE's resource manager to add resources.

Is there a way to automatically build the package.json file for Node.js projects

First off, run

npm init

...will ask you a few questions (read this first) about your project/package and then generate a package.json file for you.

Then, once you have a package.json file, use

npm install <pkg> --save


npm install <pkg> --save-dev install a dependency and automatically append it to your package.json's dependencies list.

(Note: You may need to manually tweak the version ranges for your dependencies.)

How to use su command over adb shell?

for my use case, i wanted to grab the SHA1 hash from the magisk config file. the below worked for me.

adb shell "su -c "cat /sbin/.magisk/config | grep SHA | awk -F= '{ print $2 }'""

Comment out HTML and PHP together

I found the following solution pretty effective if you need to comment a lot of nested HTML + PHP code.

Wrap all the content in this:


Here goes your PHP + HTML code


How get the base URL via context path in JSF?

JSTL 1.2 variation leveraged from BalusC answer

<c:set var="baseURL" value="${pageContext.request.requestURL.substring(0, pageContext.request.requestURL.length() - pageContext.request.requestURI.length())}${pageContext.request.contextPath}/" />

  <base href="${baseURL}" />

Hadoop: «ERROR : JAVA_HOME is not set»

I solved this in my env, without modify

You'd be better using /bin/bash as default shell not /bin/sh

Check these before:

  1. You have already config java and env (success echo $JAVA_HOME)
  2. right config hadoop

echo $SHELL in every node, check if print /bin/bash if not, vi /etc/passwd, add /bin/bash at tail of your username ref

Changing default shell in Linux

Switch android x86 screen resolution

In VirtualBox you should add custom resolution via the command:

VBoxManage setextradata "VM name" "CustomVideoMode1" "800x480x16"

instead of editing a .vbox file.

This solution works fine for me!

Capture keyboardinterrupt in Python without try-except

You can prevent printing a stack trace for KeyboardInterrupt, without try: ... except KeyboardInterrupt: pass (the most obvious and propably "best" solution, but you already know it and asked for something else) by replacing sys.excepthook. Something like

def custom_excepthook(type, value, traceback):
    if type is KeyboardInterrupt:
        return # do nothing
        sys.__excepthook__(type, value, traceback)

foreach loop in angularjs

The angular.forEach() will iterate through your json object.

First iteration,

key = 0, value = { "name" : "Thomas", "password" : "thomasTheKing"}

Second iteration,

key = 1, value = { "name" : "Linda", "password" : "lindatheQueen" }

To get the value of your name, you can use or value["name"]. Same with your password, you use value.password or value["password"].

The code below will give you what you want:

   angular.forEach(json, function (value, key)
                if (value.password == "thomasTheKing") {
                    console.log("username is thomas");

What is the difference between Scrum and Agile Development?

Agile and Scrum are terms used in project management. The Agile methodology employs incremental and iterative work beats that are also called sprints. Scrum, on the other hand is the type of agile approach that is used in software development.

Agile is the practice and Scrum is the process to following this practice same as eXtreme Programming (XP) and Kanban are the alternative process to following Agile development practice.

Regex to validate password strength

You should also consider changing some of your rules to:

  1. Add more special characters i.e. %, ^, (, ), -, _, +, and period. I'm adding all the special characters that you missed above the number signs in US keyboards. Escape the ones regex uses.
  2. Make the password 8 or more characters. Not just a static number 8.

With the above improvements, and for more flexibility and readability, I would modify the regex to.


Basic Explanation


Each rule block is shown by (?=(){}). The rule and number of occurrences can then be easily specified and tested separately, before getting combined

Detailed Explanation

^                               start anchor
(?=(.*[a-z]){3,})               lowercase letters. {3,} indicates that you want 3 of this group
(?=(.*[A-Z]){2,})               uppercase letters. {2,} indicates that you want 2 of this group
(?=(.*[0-9]){2,})               numbers. {2,} indicates that you want 2 of this group
(?=(.*[!@#$%^&*()\-__+.]){1,})  all the special characters in the [] fields. The ones used by regex are escaped by using the \ or the character itself. {1,} is redundant, but good practice, in case you change that to more than 1 in the future. Also keeps all the groups consistent
{8,}                            indicates that you want 8 or more
$                               end anchor

And lastly, for testing purposes here is a robulink with the above regex

how to save canvas as png image?

try this:

var c=document.getElementById("alpha");
var d=c.toDataURL("image/png");
var'about:blank','image from canvas');
w.document.write("<img src='"+d+"' alt='from canvas'/>");

This shows image from canvas on new page, but if you have open popup in new tab setting it shows about:blank in address bar.

EDIT:- though"<img src='"+ c.toDataURL('image/png') +"'/>") does not work in FF or Chrome, following works though rendering is somewhat different from what is shown on canvas, I think transparency is the issue:'image/png'));

How can I lookup a Java enum from its String value?

You can define your Enum as following code :

public enum Verbosity 
   private int value;

   public int getValue()
     return this.value;

   public static final Verbosity getVerbosityByValue(int value)
     for(Verbosity verbosity : Verbosity.values())
        if(verbosity.getValue() == value)
            return verbosity ;

     return ACTION_NOT_VALID;

   public String toString()
      return ((Integer)this.getValue()).toString();

See following link for more clarification

Location for session files in Apache/PHP

Another common default location besides /tmp/ is /var/lib/php5/

How can I move HEAD back to a previous location? (Detached head) & Undo commits

Today, I mistakenly checked out on a commit and started working on it, making some commits on a detach HEAD state. Then I pushed to the remote branch using the following command:

git push origin HEAD: <My-remote-branch>


git checkout <My-remote-branch>


git pull

I finally got my all changes in my branch that I made in detach HEAD.

How to make tesseract to recognize only numbers, when they are mixed with letters?

Recognizing only numbers is actually answered on the tesseract FAQ page. See that page for more info, but if you have the version 3 package, the config files are already set up. You just specify on the commandline:

tesseract image.tif outputbase nobatch digits

As for the threshold value, I'm not sure which you mean. If your input is an unusual font, perhaps you might retrain with a sample of your input. An alternative is to change tesseract's pruning threshold. Both options are also mentioned in the FAQ.

Format certain floating dataframe columns into percentage in pandas

You could also set the default format for float :

pd.options.display.float_format = '{:.2%}'.format

Use '{:.2%}' instead of '{:.2f}%' - The former converts 0.41 to 41.00% (correctly), the latter to 0.41% (incorrectly)

Force index use in Oracle

You can use optimizer hints

select /*+ INDEX(table_name index_name) */ from table etc...

More on using optimizer hints:

Can I exclude some concrete urls from <url-pattern> inside <filter-mapping>?

This approach works when you want to prevent a certain filter and all the following ones. It should work well if you eg. want to serve some content as static resources within your servlet container instead of letting your application logic (through a filter like GuiceFilter):

Map the folder with your static resource files to the default servlet. Create a servlet filter and put it before the GuiceFilter in your web.xml. In your created filter, you can separate between forwarding some requests to the GuiceFilter and others directly to the dispatcher. Example follows...






public class StaticResourceFilter implements Filter {

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

    private static final String RESOURCE_PATH = "/static/";
    public void init(final FilterConfig filterConfig) throws ServletException {"StaticResourceFilter initialized");

    public void doFilter(final ServletRequest request, final ServletResponse response,
                         final FilterChain chain) throws IOException, ServletException {

        String path = ((HttpServletRequest) request).getServletPath();
        if (path.toLowerCase().startsWith(RESOURCE_PATH)) {
            request.getRequestDispatcher(path).forward(request, response);
        } else {
            chain.doFilter(request, response);

    public void destroy() {"StaticResourceFilter destroyed");

Unfortunately if you just want to skip a single step in the filter chain while keeping those that follows, this will not work.

Resetting MySQL Root Password with XAMPP on Localhost

You want to edit this file: "\xampp\phpMyAdmin\"

change this line:

$cfg['Servers'][$i]['password'] = 'WhateverPassword';

to whatever your password is. If you don't remember your password, then run this command within the Shell:

mysqladmin.exe -u root password WhateverPassword

where WhateverPassword is your new password.

How to set specific window (frame) size in java swing?

Well, you are using both frame.setSize() and frame.pack().

You should use one of them at one time.

Using setSize() you can give the size of frame you want but if you use pack(), it will automatically change the size of the frames according to the size of components in it. It will not consider the size you have mentioned earlier.

Try removing frame.pack() from your code or putting it before setting size and then run it.

jQuery attr() change img src

You remove the original image here:

newImg.animate(css, SPEED, function() {
    (callback || function() {})();

And all that's left behind is newImg. Then you reset link references the image using #rocket:

$("#rocket").attr('src', ...

But your newImg doesn't have an id attribute let alone an id of rocket.

To fix this, you need to remove img and then set the id attribute of newImg to rocket:

newImg.animate(css, SPEED, function() {
    var old_id = img.attr('id');
    newImg.attr('id', old_id);
    (callback || function() {})();

And then you'll get the shiny black rocket back again:

UPDATE: A better approach (as noted by mellamokb) would be to hide the original image and then show it again when you hit the reset button. First, change the reset action to something like this:

    $("#wrapper").css('top', '250px');
    $('.throbber, .morpher').remove(); // Clear out the new stuff.
    $("#rocket").show();               // Bring the original back.

And in the newImg.load function, grab the images original size:

var orig = {
    width: img.width(),
    height: img.height()

And finally, the callback for finishing the morphing animation becomes this:

newImg.animate(css, SPEED, function() {
    (callback || function() {})();

New and improved:

The leaking of $('.throbber, .morpher') outside the plugin isn't the best thing ever but it isn't a big deal as long as it is documented.

How to merge a Series and DataFrame

Here's one way:


To break down what happens here...

pd.DataFrame(s).T creates a one-row DataFrame from s which looks like this:

   s1  s2
0   5   6

Next, join concatenates this new frame with df:

   a  b  s1  s2
0  1  3   5   6
1  2  4 NaN NaN

Lastly, the NaN values at index 1 are filled with the previous values in the column using fillna with the forward-fill (ffill) argument:

   a  b  s1  s2
0  1  3   5   6
1  2  4   5   6

To avoid using fillna, it's possible to use pd.concat to repeat the rows of the DataFrame constructed from s. In this case, the general solution is:

df.join(pd.concat([pd.DataFrame(s).T] * len(df), ignore_index=True))

Here's another solution to address the indexing challenge posed in the edited question:

df.join(pd.DataFrame(s.repeat(len(df)).values.reshape((len(df), -1), order='F'), 

s is transformed into a DataFrame by repeating the values and reshaping (specifying 'Fortran' order), and also passing in the appropriate column names and index. This new DataFrame is then joined to df.

Firing a Keyboard Event in Safari, using JavaScript

I am working on DOM Keyboard Event Level 3 polyfill . In latest browsers or with this polyfill you can do something like this:

element.addEventListener("keydown", function(e){ console.log(e.key, e.char, e.keyCode) })

var e = new KeyboardEvent("keydown", {bubbles : true, cancelable : true, key : "Q", char : "Q", shiftKey : true});

//If you need legacy property "keyCode"
// Note: In some browsers you can't overwrite "keyCode" property. (At least in Safari)
delete e.keyCode;
Object.defineProperty(e, "keyCode", {"value" : 666})


Now my polyfill supports legacy properties "keyCode", "charCode" and "which"

var e = new KeyboardEvent("keydown", {
    bubbles : true,
    cancelable : true,
    char : "Q",
    key : "q",
    shiftKey : true,
    keyCode : 81

Examples here

Additionally here is cross-browser initKeyboardEvent separately from my polyfill: (gist)

Polyfill demo

Recursion or Iteration?

I believe tail recursion in java is not currently optimized. The details are sprinkled throughout this discussion on LtU and the associated links. It may be a feature in the upcoming version 7, but apparently it presents certain difficulties when combined with Stack Inspection since certain frames would be missing. Stack Inspection has been used to implement their fine-grained security model since Java 2.

IllegalMonitorStateException on wait() call

Those who are using Java 7.0 or below version can refer the code which I used here and it works.

public class WaitTest {

    private final Lock lock = new ReentrantLock();
    private final Condition condition = lock.newCondition();

    public void waitHere(long waitTime) {
        System.out.println("wait started...");
        try {
            condition.await(waitTime, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
        System.out.println("wait ends here...");

    public static void main(String[] args) {
        //Your Code
        new WaitTest().waitHere(10);
        //Your Code


How to limit the maximum files chosen when using multiple file input

You could run some jQuery client-side validation to check:

        var $fileUpload = $("input[type='file']");
        if (parseInt($fileUpload.get(0).files.length)>2){
         alert("You can only upload a maximum of 2 files");

But remember to check on the server side too as client-side validation can be bypassed quite easily.

In Perl, how to remove ^M from a file?

Or a 1-liner:

perl -p -i -e 's/\r\n$/\n/g' file1.txt file2.txt ... filen.txt

Using Auto Layout in UITableView for dynamic cell layouts & variable row heights

Simply add these two functions in your viewcontroller it will solve your problem. Here, list is a string array which contain your string of every row.

 func tableView(_ tableView: UITableView, 
   estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
        tableView.rowHeight = self.calculateHeight(inString: list[indexPath.row])

    return (tableView.rowHeight) 

func calculateHeight(inString:String) -> CGFloat
    let messageString = input.text
    let attributes : [NSAttributedStringKey : Any] = [NSAttributedStringKey(rawValue: NSAttributedStringKey.font.rawValue) : UIFont.systemFont(ofSize: 15.0)]

    let attributedString : NSAttributedString = NSAttributedString(string: messageString!, attributes: attributes)

    let rect : CGRect = attributedString.boundingRect(with: CGSize(width: 222.0, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, context: nil)

    let requredSize:CGRect = rect
    return requredSize.height

What is the difference between for and foreach?

One important thing related with foreach is that , foreach iteration variable cannot be updated(or assign new value) in loop body.

for example :

List<string> myStrlist = new List<string>() { "Sachin", "Ganguly", "Dravid" };
              foreach(string item in myStrlist)


                  item += " cricket"; // ***Not Possible*** 


How can I write a heredoc to a file in Bash script?

Instead of using cat and I/O redirection it might be useful to use tee instead:

tee newfile <<EOF
line 1
line 2
line 3

It's more concise, plus unlike the redirect operator it can be combined with sudo if you need to write to files with root permissions.

jQuery find and replace string

Why you just don't add a class to the string container and then replace the inner text ? Just like in this example.


             <a class="swapText">lollipops</a>
        <span class="swapText">lollipops</span>
   <span class="lollipops">Hello, World!</span>
   <img src="/lollipops.jpg" alt="Cool image" />


$(document).ready(function() {

Set value of hidden field in a form using jQuery's ".val()" doesn't work

.val didnt work for me, because i'm grabbing the value attribute server side and the value wasn't always updated. so i used :

var counter = 0;

   $('#myInput').attr('value', counter);

Hope it helps someone.

How to set 00:00:00 using moment.js

var time = moment().toDate();  // This will return a copy of the Date that the moment uses


Xcode couldn't find any provisioning profiles matching

I am now able to successfully build. Not sure exactly which step "fixed" things, but this was the sequence:

  • Tried automatic signing again. No go, so reverted to manual.
  • After reverting, I had no Eligible Profiles, all were ineligible. Strange.
  • I created a new certificate and profile, imported both. This too was "ineligible".
  • Removed the iOS platform and re-added it. I had tried this previously without luck.
  • After doing this, Xcode on its own defaulted to automatic signing. And this worked! Success!

While I am not sure exactly which parts were necessary, I think the previous certificates were the problem. I hate Xcode :(

Thanks for help.

Where do I put my php files to have Xampp parse them?

in XAMPP the default root is "htdocs" inside the XAMPP folder, if you followed the instructions on the xampp homepage it would be "/opt/lampp/htdocs"

Hiding axis text in matplotlib plots

Instead of hiding each element, you can hide the whole axis:


Or, you can set the ticks to an empty list:


In this second option, you can still use plt.xlabel() and plt.ylabel() to add labels to the axes.

What is 'PermSize' in Java?

This blog post gives a nice explanation and some background. Basically, the "permanent generation" (whose size is given by PermSize) is used to store things that the JVM has to allocate space for, but which will not (normally) be garbage-collected (hence "permanent") (+). That means for example loaded classes and static fields.

There is also a FAQ on garbage collection directly from Sun, which answers some questions about the permanent generation. Finally, here's a blog post with a lot of technical detail.

(+) Actually parts of the permanent generation will be GCed, e.g. class objects will be removed when a class is unloaded. But that was uncommon when the permanent generation was introduced into the JVM, hence the name.

Response::json() - Laravel 5.1

although Response::json() is not getting popular of recent, that does not stop you and Me from using it. In fact you don't need any facade to use it,

instead of:

$response = Response::json($messages, 200);

Use this:

$response = \Response::json($messages, 200);

with the slash, you are sure good to go.

Remove a modified file from pull request

You would want to amend the commit and then do a force push which will update the branch with the PR.

Here's how I recommend you do this:

  1. Close the PR so that whomever is reviewing it doesn't pull it in until you've made your changes.
  2. Do a Soft reset to the commit before your unwanted change (if this is the last commit you can use git reset --soft HEAD^ or if it's a different commit, you would want to replace 'HEAD^' with the commit id)
  3. Discard (or undo) any changes to the file that you didn't intend to update
  4. Make a new commit git commit -a -c ORIG_HEAD
  5. Force Push to your branch
  6. Re-Open Pull Request

The now that your branch has been updated, the Pull Request will include your changes.

Here's a link to Gits documentation where they have a pretty good example under Undo a commit and redo.

How to change href of <a> tag on button click through javascript

<a href="#" id="a" onclick="ChangeHref()">1.Change 2.Go</a>

function ChangeHref(){
document.getElementById("a").setAttribute("onclick", "location.href=''");

Detect element content changes with jQuery

what about

  console.log($('body').width() + ' x '+$('body').height());

This event has been deprecated in favor of the Mutation Observer API

How do I turn off PHP Notices?

I found this trick out recently. Whack an @ at the start of a line that may produce an warning/error.

As if by magic, they dissapear.

Sorting 1 million 8-decimal-digit numbers with 1 MB of RAM

Sorting is a secondary problem here. As other said, just storing the integers is hard, and cannot work on all inputs, since 27 bits per number would be necessary.

My take on this is: store only the differences between the consecutive (sorted) integers, as they will be most likely small. Then use a compression scheme, e.g. with 2 additional bits per input number, to encode how many bits the number is stored on. Something like:

00 -> 5 bits
01 -> 11 bits
10 -> 19 bits
11 -> 27 bits

It should be possible to store a fair number of possible input lists within the given memory constraint. The maths of how to pick the compression scheme to have it work on the maximum number of inputs, are beyond me.

I hope you may be able to exploit domain-specific knowledge of your input to find a good enough integer compression scheme based on this.

Oh and then, you do an insertion sort on that sorted list as you receive data.

how can select from drop down menu and call javascript function

<select name="aa" onchange="report(this.value)"> 
  <option value="">Please select</option>
  <option value="daily">daily</option>
  <option value="monthly">monthly</option>


function report(period) {
  if (period=="") return; // please select - possibly you want something else here

  const report = "script/"+((period == "daily")?"d":"m")+"_report.php";

Unobtrusive version:

<select id="aa" name="aa"> 
  <option value="">Please select</option>
  <option value="daily">daily</option>
  <option value="monthly">monthly</option>


window.addEventListener("load",function() {
  document.getElementById("aa").addEventListener("change",function() {
    const period = this.value;
    if (period=="") return; // please select - possibly you want something else here

    const report = "script/"+((period == "daily")?"d":"m")+"_report.php";

jQuery version - same select with ID

$(function() {
  $("#aa").on("change",function() {
    const period = this.value;
    if (period=="") return; // please select - possibly you want something else here

    var report = "script/"+((period == "daily")?"d":"m")+"_report.php";

UIAlertController custom font, size, color

You can use an external library like PMAlertController without using workaround, where you can substitute Apple's uncustomizable UIAlertController with a super customizable alert.

Compatible with Xcode 8, Swift 3 and Objective-C

PMAlertController example


  • [x] Header View
  • [x] Header Image (Optional)
  • [x] Title
  • [x] Description message
  • [x] Customizations: fonts, colors, dimensions & more
  • [x] 1, 2 buttons (horizontally) or 3+ buttons (vertically)
  • [x] Closure when a button is pressed
  • [x] Text Fields support
  • [x] Similar implementation to UIAlertController
  • [x] Cocoapods
  • [x] Carthage
  • [x] Animation with UIKit Dynamics
  • [x] Objective-C compatibility
  • [x] Swift 2.3 & Swift 3 support

How to use componentWillMount() in React Hooks?

You cannot use any of the existing lifecycle methods (componentDidMount, componentDidUpdate, componentWillUnmount etc.) in a hook. They can only be used in class components. And with Hooks you can only use in functional components. The line below comes from the React doc:

If you’re familiar with React class lifecycle methods, you can think of useEffect Hook as componentDidMount, componentDidUpdate, and componentWillUnmount combined.

suggest is, you can mimic these lifecycle method from class component in a functional components.

Code inside componentDidMount run once when the component is mounted. useEffect hook equivalent for this behaviour is

useEffect(() => {
  // Your code here
}, []);

Notice the second parameter here (empty array). This will run only once.

Without the second parameter the useEffect hook will be called on every render of the component which can be dangerous.

useEffect(() => {
  // Your code here

componentWillUnmount is use for cleanup (like removing event listeners, cancel the timer etc). Say you are adding a event listener in componentDidMount and removing it in componentWillUnmount as below.

componentDidMount() {
  window.addEventListener('mousemove', () => {})

componentWillUnmount() {
  window.removeEventListener('mousemove', () => {})

Hook equivalent of above code will be as follows

useEffect(() => {
  window.addEventListener('mousemove', () => {});

  // returned function will be called on component unmount 
  return () => {
    window.removeEventListener('mousemove', () => {})
}, [])

Convert 24 Hour time to 12 Hour plus AM/PM indication Oracle SQL

For the 24-hour time, you need to use HH24 instead of HH.

For the 12-hour time, the AM/PM indicator is written as A.M. (if you want periods in the result) or AM (if you don't). For example:

SELECT invoice_date,
       TO_CHAR(invoice_date, 'DD-MM-YYYY HH24:MI:SS') "Date 24Hr",
       TO_CHAR(invoice_date, 'DD-MM-YYYY HH:MI:SS AM') "Date 12Hr"
  FROM invoices

For more information on the format models you can use with TO_CHAR on a date, see

Deciding between HttpClient and WebClient

HttpClient is the newer of the APIs and it has the benefits of

  • has a good async programming model
  • being worked on by Henrik F Nielson who is basically one of the inventors of HTTP, and he designed the API so it is easy for you to follow the HTTP standard, e.g. generating standards-compliant headers
  • is in the .Net framework 4.5, so it has some guaranteed level of support for the forseeable future
  • also has the xcopyable/portable-framework version of the library if you want to use it on other platforms - .Net 4.0, Windows Phone etc.

If you are writing a web service which is making REST calls to other web services, you should want to be using an async programming model for all your REST calls, so that you don't hit thread starvation. You probably also want to use the newest C# compiler which has async/await support.

Note: It isn't more performant AFAIK. It's probably somewhat similarly performant if you create a fair test.

Local Storage vs Cookies


  1. Introduced prior to HTML5.
  2. Has expiration date.
  3. Cleared by JS or by Clear Browsing Data of browser or after expiration date.
  4. Will sent to the server per each request.
  5. The capacity is 4KB.
  6. Only strings are able to store in cookies.
  7. There are two types of cookies: persistent and session.

Local Storage:

  1. Introduced with HTML5.
  2. Does not have expiration date.
  3. Cleared by JS or by Clear Browsing Data of the browser.
  4. You can select when the data must be sent to the server.
  5. The capacity is 5MB.
  6. Data is stored indefinitely, and must be a string.
  7. Only have one type.

Creating a PDF from a RDLC Report in the Background

The below code work fine with me of sure thanks for the above comments. You can add report viewer and change the visible=false and use the below code on submit button:

protected void Button1_Click(object sender, EventArgs e)
    Warning[] warnings;
    string[] streamIds;
    string mimeType = string.Empty;
    string encoding = string.Empty;
    string extension = string.Empty;
    string HIJRA_TODAY = "01/10/1435";
    ReportParameter[] param = new ReportParameter[3];
    param[0] = new ReportParameter("CUSTOMER_NUM", CUSTOMER_NUMTBX.Text);
    param[1] = new ReportParameter("REF_CD", REF_CDTB.Text);
    param[2] = new ReportParameter("HIJRA_TODAY", HIJRA_TODAY);

    byte[] bytes = ReportViewer1.LocalReport.Render(
        out mimeType, 
        out encoding, 
        out extension, 
        out streamIds, 
        out warnings);

    Response.Buffer = true;
    Response.ContentType = mimeType;
        "attachment; filename= filename" + "." + extension);
    Response.OutputStream.Write(bytes, 0, bytes.Length); // create the file  
    Response.Flush(); // send it to the client to download  

WCFTestClient The HTTP request is unauthorized with client authentication scheme 'Anonymous'

I had the same error today, after deploying our service calling an external service to the staging environment in azure. Local the service called the external service without errors, but after deployment it didn't.

In the end it turned out to be that the external service has a IP validation. The new environment in Azure has another IP and it was rejected.

So if you ever get this error calling external services

It might be an IP restriction.

Selenium using Python - Geckodriver executable needs to be in PATH

For Windows users

Use the original code as it's:

from selenium import webdriver
browser = webdriver.Firefox()

Then download the driver from: mozilla/geckodriver

Place it in a fixed path (permanently)... As an example, I put it in:


Then go to the environment variables of the system. In the grid of "System variables" look for the Path variable and add:


geckodriver, not geckodriver.exe.

Maximum packet size for a TCP connection

This is an excellent question and I run in to this a lot at work actually. There are a lot of "technically correct" answers such as 65k and 1500. I've done a lot of work writing network interfaces and using 65k is silly, and 1500 can also get you in to big trouble. My work goes on a lot of different hardware / platforms / routers, and to be honest the place I start is 1400 bytes. If you NEED more than 1400 you can start to inch your way up, you can probably go to 1450 and sometimes to 1480'ish? If you need more than that then of course you need to split in to 2 packets, of which there are several obvious ways of doing..

The problem is that you're talking about creating a data packet and writing it out via TCP, but of course there's header data tacked on and so forth, so you have "baggage" that puts you to 1500 or beyond.. and also a lot of hardware has lower limits.

If you "push it" you can get some really weird things going on. Truncated data, obviously, or dropped data I've seen rarely. Corrupted data also rarely but certainly does happen.

How to load property file from classpath?

final Properties properties = new Properties();
try (final InputStream stream =
           this.getClass().getResourceAsStream("")) {
    /* or properties.loadFromXML(...) */

How to convert a currency string to a double with jQuery or Javascript?

You can try this

var str = "$1,112.12";_x000D_
str = str.replace(",", "");_x000D_
str = str.replace("$", "");_x000D_

Calling Web API from MVC controller

well, you can do it a lot of ways... one of them is to create a HttpRequest. I would advise you against calling your own webapi from your own MVC (the idea is redundant...) but, here's a end to end tutorial.

How to use sha256 in php5.3.0

The first thing is to make a comparison of functions of SHA and opt for the safest algorithm that supports your programming language (PHP).

Then you can chew the official documentation to implement the hash() function that receives as argument the hashing algorithm you have chosen and the raw password.

sha256 => 64 bits sha384 => 96 bits sha512 => 128 bits

The more secure the hashing algorithm is, the higher the cost in terms of hashing and time to recover the original value from the server side.

$hashedPassword = hash('sha256', $password);

iOS Safari – How to disable overscroll but allow scrollable divs to scroll normally?

I had surprising luck with with simple:

body {
    height: 100vh;

It works great to disable overscroll for pop-ups or menus and it doesn't force browser bars to appear like when using position:fixed. BUT - you need to save scroll position before setting fixed height and restore it when hiding the pop-up, otherwise, browser will scroll to top.

Truncate number to two decimal places without rounding

Gumbo's second solution, with the regular expression, does work but is slow because of the regular expression. Gumbo's first solution fails in certain situations due to imprecision in floating points numbers. See the JSFiddle for a demonstration and a benchmark. The second solution takes about 1636 nanoseconds per call on my current system, Intel Core i5-2500 CPU at 3.30 GHz.

The solution I've written involves adding a small compensation to take care of floating point imprecision. It is basically instantaneous, i.e. on the order of nanoseconds. I clocked 2 nanoseconds per call but the JavaScript timers are not very precise or granular. Here is the JS Fiddle and the code.

function toFixedWithoutRounding (value, precision)
    var factorError = Math.pow(10, 14);
    var factorTruncate = Math.pow(10, 14 - precision);
    var factorDecimal = Math.pow(10, precision);
    return Math.floor(Math.floor(value * factorError + 1) / factorTruncate) / factorDecimal;

var values = [1.1299999999, 1.13, 1.139999999, 1.14, 1.14000000001, 1.13 * 100];

for (var i = 0; i < values.length; i++)
    var value = values[i];
    console.log(value + " --> " + toFixedWithoutRounding(value, 2));

for (var i = 0; i < values.length; i++)
    var value = values[i];
    console.log(value + " --> " + toFixedWithoutRounding(value, 4));

console.log("type of result is " + typeof toFixedWithoutRounding(1.13 * 100 / 100, 2));

// Benchmark
var value = 1.13 * 100;
var startTime = new Date();
var numRun = 1000000;
var nanosecondsPerMilliseconds = 1000000;

for (var run = 0; run < numRun; run++)
    toFixedWithoutRounding(value, 2);

var endTime = new Date();
var timeDiffNs = nanosecondsPerMilliseconds * (endTime - startTime);
var timePerCallNs = timeDiffNs / numRun;
console.log("Time per call (nanoseconds): " + timePerCallNs);

Class type check in TypeScript

You can use the instanceof operator for this. From MDN:

The instanceof operator tests whether the prototype property of a constructor appears anywhere in the prototype chain of an object.

If you don't know what prototypes and prototype chains are I highly recommend looking it up. Also here is a JS (TS works similar in this respect) example which might clarify the concept:

    class Animal {_x000D_
        constructor(name) {_x000D_
   = name;_x000D_
    const animal = new Animal('fluffy');_x000D_
    // true because Animal in on the prototype chain of animal_x000D_
    console.log(animal instanceof Animal); // true_x000D_
    // Proof that Animal is on the prototype chain_x000D_
    console.log(Object.getPrototypeOf(animal) === Animal.prototype); // true_x000D_
    // true because Object in on the prototype chain of animal_x000D_
    console.log(animal instanceof Object); _x000D_
    // Proof that Object is on the prototype chain_x000D_
    console.log(Object.getPrototypeOf(Animal.prototype) === Object.prototype); // true_x000D_
    console.log(animal instanceof Function); // false, Function not on prototype chain_x000D_

The prototype chain in this example is:

animal > Animal.prototype > Object.prototype


Java does not have this control structure.
It should be noted though, that other languages do.
Python for example, has the while-else construct.

In Java's case, you can mimic this behaviour as you have already shown:

if (rowIndex >= dataColLinker.size()) {
    do {
    } while(rowIndex >= dataColLinker.size());
} else {
    dataColLinker.set(rowIndex, value);

ASP.NET MVC Custom Error Handling Application_Error Global.asax?

Use Following code for redirecting on route page. Use exception.Message instide of exception. Coz exception query string gives error if it extends the querystring length.

routeData.Values.Add("error", exception.Message);
// clear error on server

Git says local branch is behind remote branch, but it's not

To diagnose it, follow this answer.

But to fix it, knowing you are the only one changing it, do:
1 - backup your project (I did only the files on git, ./src folder)
2 - git pull
3 - restore you backup over the many "messed" files (with merge indicators)

I tried git pull -s recursive -X ours but didnt work the way I wanted, it could be an option tho, but backup first!!!

Make sure the differences/changes (at git gui) are none. This is my case, there is nothing to merge at all, but github keeps saying I should merge...

Lightweight workflow engine for Java

I recently open sourced Piper ( a distributed and very light weight, Spring-based, workflow engine.

What is the correct way to start a mongod service on linux / OS X?

After installing mongodb through brew, run this to get it up and running:

mongod --dbpath /usr/local/var/mongodb

How to add an existing folder with files to SVN?

Let's try.. It is working for me..

svn add * --force

In Windows cmd, how do I prompt for user input and use the result in another command?

set /p choice= "Please Select one of the above options :" 
echo '%choice%'

The space after = is very important.

Call to undefined method mysqli_stmt::get_result

Please read the user notes for this method:

It requires the mysqlnd driver... if it isn't installed on your webspace you will have to work with BIND_RESULT & FETCH!

Combining "LIKE" and "IN" for SQL Server

No, you will have to use OR to combine your LIKE statements:

   column LIKE 'Text%' OR 
   column LIKE 'Link%' OR 
   column LIKE 'Hello%' OR
   column LIKE '%World%'

Have you looked at Full-Text Search?