Programs & Examples On #Bufferedwriter

Java class for writing text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings.

Java - how do I write a file to a specified directory

You should use the secondary constructor for File to specify the directory in which it is to be symbolically created. This is important because the answers that say to create a file by prepending the directory name to original name, are not as system independent as this method.

Sample code:

String dirName = /* something to pull specified dir from input */;

String fileName = "test.txt";
File dir = new File (dirName);
File actualFile = new File (dir, fileName);

/* rest is the same */

Hope it helps.

how to write an array to a file Java

If you're okay with Apache commons lib

outputWriter.write(ArrayUtils.join(array, ","));

What are database constraints?

Constraints can be used to enforce specific properties of data. A simple example is to limit an int column to values [0-100000]. This introduction looks good.

Adjusting HttpWebRequest Connection Timeout in C#

No matter what we tried we couldn't manage to get the timeout below 21 seconds when the server we were checking was down.

To work around this we combined a TcpClient check to see if the domain was alive followed by a separate check to see if the URL was active

public static bool IsUrlAlive(string aUrl, int aTimeoutSeconds)
{
    try
    {
        //check the domain first
        if (IsDomainAlive(new Uri(aUrl).Host, aTimeoutSeconds))
        {
            //only now check the url itself
            var request = System.Net.WebRequest.Create(aUrl);
            request.Method = "HEAD";
            request.Timeout = aTimeoutSeconds * 1000;
            var response = (HttpWebResponse)request.GetResponse();
            return response.StatusCode == HttpStatusCode.OK;
        }
    }
    catch
    {
    }
    return false;

}

private static bool IsDomainAlive(string aDomain, int aTimeoutSeconds)
{
    try
    {
        using (TcpClient client = new TcpClient())
        {
            var result = client.BeginConnect(aDomain, 80, null, null);

            var success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(aTimeoutSeconds));

            if (!success)
            {
                return false;
            }

            // we have connected
            client.EndConnect(result);
            return true;
        }
    }
    catch
    {
    }
    return false;
}

How to detect internet speed in JavaScript?

The image trick is cool but in my tests it was loading before some ajax calls I wanted to be complete.

The proper solution in 2017 is to use a worker (http://caniuse.com/#feat=webworkers).

The worker will look like:

/**
 * This function performs a synchronous request
 * and returns an object contain informations about the download
 * time and size
 */
function measure(filename) {
  var xhr = new XMLHttpRequest();
  var measure = {};
  xhr.open("GET", filename + '?' + (new Date()).getTime(), false);
  measure.start = (new Date()).getTime();
  xhr.send(null);
  measure.end = (new Date()).getTime();
  measure.len = parseInt(xhr.getResponseHeader('Content-Length') || 0);
  measure.delta = measure.end - measure.start;
  return measure;
}

/**
 * Requires that we pass a base url to the worker
 * The worker will measure the download time needed to get
 * a ~0KB and a 100KB.
 * It will return a string that serializes this informations as
 * pipe separated values
 */
onmessage = function(e) {
  measure0 = measure(e.data.base_url + '/test/0.bz2');
  measure100 = measure(e.data.base_url + '/test/100K.bz2');
  postMessage(
    measure0.delta + '|' +
    measure0.len + '|' +
    measure100.delta + '|' +
    measure100.len
  );
};

The js file that will invoke the Worker:

var base_url = PORTAL_URL + '/++plone++experimental.bwtools';
if (typeof(Worker) === 'undefined') {
  return; // unsupported
}
w = new Worker(base_url + "/scripts/worker.js");
w.postMessage({
  base_url: base_url
});
w.onmessage = function(event) {
  if (event.data) {
    set_cookie(event.data);
  }
};

Code taken from a Plone package I wrote:

Convert datetime to valid JavaScript date

Just use Date.parse() which returns a Number, then use new Date() to parse it:

var thedate = new Date(Date.parse("2011-07-14 11:23:00"));

CSS table column autowidth

You could specify the width of all but the last table cells and add a table-layout:fixed and a width to the table.

You could set

table tr ul.actions {margin: 0; white-space:nowrap;}

(or set this for the last TD as Sander suggested instead).

This forces the inline-LIs not to break. Unfortunately this does not lead to a new width calculation in the containing UL (and this parent TD), and therefore does not autosize the last TD.

This means: if an inline element has no given width, a TD's width is always computed automatically first (if not specified). Then its inline content with this calculated width gets rendered and the white-space-property is applied, stretching its content beyond the calculated boundaries.

So I guess it's not possible without having an element within the last TD with a specific width.

Byte Array and Int conversion in Java

Your methods should be (something like)

public static int byteArrayToInt(byte[] b) 
{
    return   b[3] & 0xFF |
            (b[2] & 0xFF) << 8 |
            (b[1] & 0xFF) << 16 |
            (b[0] & 0xFF) << 24;
}

public static byte[] intToByteArray(int a)
{
    return new byte[] {
        (byte) ((a >> 24) & 0xFF),
        (byte) ((a >> 16) & 0xFF),   
        (byte) ((a >> 8) & 0xFF),   
        (byte) (a & 0xFF)
    };
}

These methods were tested with the following code :

Random rand = new Random(System.currentTimeMillis());
byte[] b;
int a, v;
for (int i=0; i<10000000; i++) {
    a = rand.nextInt();
    b = intToByteArray(a);
    v = byteArrayToInt(b);
    if (a != v) {
        System.out.println("ERR! " + a + " != " + Arrays.toString(b) + " != " + v);
    }
}
System.out.println("Done!");

Can constructors throw exceptions in Java?

Yes, constructors can throw exceptions. Usually this means that the new object is immediately eligible for garbage collection (although it may not be collected for some time, of course). It's possible for the "half-constructed" object to stick around though, if it's made itself visible earlier in the constructor (e.g. by assigning a static field, or adding itself to a collection).

One thing to be careful of about throwing exceptions in the constructor: because the caller (usually) will have no way of using the new object, the constructor ought to be careful to avoid acquiring unmanaged resources (file handles etc) and then throwing an exception without releasing them. For example, if the constructor tries to open a FileInputStream and a FileOutputStream, and the first succeeds but the second fails, you should try to close the first stream. This becomes harder if it's a subclass constructor which throws the exception, of course... it all becomes a bit tricky. It's not a problem very often, but it's worth considering.

MySQL, update multiple tables with one query

When you say multiple queries do you mean multiple SQL statements as in:

UPDATE table1 SET a=b WHERE c;
UPDATE table2 SET a=b WHERE d;
UPDATE table3 SET a=b WHERE e;

Or multiple query function calls as in:

mySqlQuery(UPDATE table1 SET a=b WHERE c;)
mySqlQuery(UPDATE table2 SET a=b WHERE d;)
mySqlQuery(UPDATE table3 SET a=b WHERE e;)

The former can all be done using a single mySqlQuery call if that is what you wanted to achieve, simply call the mySqlQuery function in the following manner:

mySqlQuery(UPDATE table1 SET a=b WHERE c; UPDATE table2 SET a=b WHERE d; UPDATE table3 SET a=b WHERE e;)

This will execute all three queries with one mySqlQuery() call.

Difference between map, applymap and apply methods in Pandas

@jeremiahbuddha mentioned that apply works on row/columns, while applymap works element-wise. But it seems you can still use apply for element-wise computation....

frame.apply(np.sqrt)
Out[102]: 
               b         d         e
Utah         NaN  1.435159       NaN
Ohio    1.098164  0.510594  0.729748
Texas        NaN  0.456436  0.697337
Oregon  0.359079       NaN       NaN

frame.applymap(np.sqrt)
Out[103]: 
               b         d         e
Utah         NaN  1.435159       NaN
Ohio    1.098164  0.510594  0.729748
Texas        NaN  0.456436  0.697337
Oregon  0.359079       NaN       NaN

Angular EXCEPTION: No provider for Http

import { HttpModule } from '@angular/http'; package in your module.ts file and add it in your imports.

How to catch a unique constraint error in a PL/SQL block?

I suspect the condition you are looking for is DUP_VAL_ON_INDEX

EXCEPTION
    WHEN DUP_VAL_ON_INDEX THEN
        DBMS_OUTPUT.PUT_LINE('OH DEAR. I THINK IT IS TIME TO PANIC!')

JSON to PHP Array using file_get_contents

The JSON sample you provided is not valid. Check it online with this JSON Validator http://jsonlint.com/. You need to remove the extra comma on line 59.

One you have valid json you can use this code to convert it to an array.

json_decode($json, true);

Array
(
    [bpath] => http://www.sampledomain.com/
    [clist] => Array
        (
            [0] => Array
                (
                    [cid] => 11
                    [display_type] => grid
                    [ctitle] => abc
                    [acount] => 71
                    [alist] => Array
                        (
                            [0] => Array
                                (
                                    [aid] => 6865
                                    [adate] => 2 Hours ago
                                    [atitle] => test
                                    [adesc] => test desc
                                    [aimg] => 
                                    [aurl] => ?nid=6865
                                    [weburl] => news.php?nid=6865
                                    [cmtcount] => 0
                                )

                            [1] => Array
                                (
                                    [aid] => 6857
                                    [adate] => 20 Hours ago
                                    [atitle] => test1
                                    [adesc] => test desc1
                                    [aimg] => 
                                    [aurl] => ?nid=6857
                                    [weburl] => news.php?nid=6857
                                    [cmtcount] => 0
                                )

                        )

                )

            [1] => Array
                (
                    [cid] => 1
                    [display_type] => grid
                    [ctitle] => test1
                    [acount] => 2354
                    [alist] => Array
                        (
                            [0] => Array
                                (
                                    [aid] => 6851
                                    [adate] => 1 Days ago
                                    [atitle] => test123
                                    [adesc] => test123 desc
                                    [aimg] => 
                                    [aurl] => ?nid=6851
                                    [weburl] => news.php?nid=6851
                                    [cmtcount] => 7
                                )

                            [1] => Array
                                (
                                    [aid] => 6847
                                    [adate] => 2 Days ago
                                    [atitle] => test12345
                                    [adesc] => test12345 desc
                                    [aimg] => 
                                    [aurl] => ?nid=6847
                                    [weburl] => news.php?nid=6847
                                    [cmtcount] => 7
                                )

                        )

                )

        )

)

How to use java.String.format in Scala?

In Scala 2.10

val name = "Ivan"
val weather = "sunny"

s"Hello $name, it's $weather today!"

Should I use typescript? or I can just use ES6?

Decision tree between ES5, ES6 and TypeScript

Do you mind having a build step?

  • Yes - Use ES5
  • No - keep going

Do you want to use types?

  • Yes - Use TypeScript
  • No - Use ES6

More Details

ES5 is the JavaScript you know and use in the browser today it is what it is and does not require a build step to transform it into something that will run in today's browsers

ES6 (also called ES2015) is the next iteration of JavaScript, but it does not run in today's browsers. There are quite a few transpilers that will export ES5 for running in browsers. It is still a dynamic (read: untyped) language.

TypeScript provides an optional typing system while pulling in features from future versions of JavaScript (ES6 and ES7).

Note: a lot of the transpilers out there (i.e. babel, TypeScript) will allow you to use features from future versions of JavaScript today and exporting code that will still run in today's browsers.

In R, dealing with Error: ggplot2 doesn't know how to deal with data of class numeric

The error happens because of you are trying to map a numeric vector to data in geom_errorbar: GVW[1:64,3]. ggplot only works with data.frame.

In general, you shouldn't subset inside ggplot calls. You are doing so because your standard errors are stored in four separate objects. Add them to your original data.frame and you will be able to plot everything in one call.

Here with a dplyr solution to summarise the data and compute the standard error beforehand.

library(dplyr)
d <- GVW %>% group_by(Genotype,variable) %>%
    summarise(mean = mean(value),se = sd(value) / sqrt(n()))

ggplot(d, aes(x = variable, y = mean, fill = Genotype)) + 
  geom_bar(position = position_dodge(), stat = "identity", 
      colour="black", size=.3) +
  geom_errorbar(aes(ymin = mean - se, ymax = mean + se), 
      size=.3, width=.2, position=position_dodge(.9)) +
  xlab("Time") +
  ylab("Weight [g]") +
  scale_fill_hue(name = "Genotype", breaks = c("KO", "WT"), 
      labels = c("Knock-out", "Wild type")) +
  ggtitle("Effect of genotype on weight-gain") +
  scale_y_continuous(breaks = 0:20*4) +
  theme_bw()

Installing a plain plugin jar in Eclipse 3.5

in Eclipse 4.4.1

  1. copy jar in "C:\eclipse\plugins"
  2. edit file "C:\eclipse\configuration\org.eclipse.equinox.simpleconfigurator\bundles.info"
  3. add jar info. example: com.soft4soft.resort.jdt,2.4.4,file:plugins\com.soft4soft.resort.jdt_2.4.4.jar,4,false
  4. restart Eclipse.

How can I convert the "arguments" object to an array in JavaScript?

Here is benchmark of several methods converting arguments into array.

As for me, the best solution for small amount of arguments is:

function sortArgs (){
  var q = [];
  for (var k = 0, l = arguments.length; k < l; k++){
    q[k] = arguments[k];
  }
  return q.sort();
}

For other cases:

function sortArgs (){ return Array.apply(null, arguments).sort(); }

SQL Server datetime LIKE select?

Unfortunately, It is not possible to compare datetime towards varchar using 'LIKE' But the desired output is possible in another way.

    select * from record where datediff(dd,[record].[register_date],'2009-10-10')=0

How to use Checkbox inside Select Option

You cannot place checkbox inside select element but you can get the same functionality by using HTML, CSS and JavaScript. Here is a possible working solution. The explanation follows.

enter image description here


Code:

_x000D_
_x000D_
var expanded = false;_x000D_
_x000D_
function showCheckboxes() {_x000D_
  var checkboxes = document.getElementById("checkboxes");_x000D_
  if (!expanded) {_x000D_
    checkboxes.style.display = "block";_x000D_
    expanded = true;_x000D_
  } else {_x000D_
    checkboxes.style.display = "none";_x000D_
    expanded = false;_x000D_
  }_x000D_
}
_x000D_
.multiselect {_x000D_
  width: 200px;_x000D_
}_x000D_
_x000D_
.selectBox {_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.selectBox select {_x000D_
  width: 100%;_x000D_
  font-weight: bold;_x000D_
}_x000D_
_x000D_
.overSelect {_x000D_
  position: absolute;_x000D_
  left: 0;_x000D_
  right: 0;_x000D_
  top: 0;_x000D_
  bottom: 0;_x000D_
}_x000D_
_x000D_
#checkboxes {_x000D_
  display: none;_x000D_
  border: 1px #dadada solid;_x000D_
}_x000D_
_x000D_
#checkboxes label {_x000D_
  display: block;_x000D_
}_x000D_
_x000D_
#checkboxes label:hover {_x000D_
  background-color: #1e90ff;_x000D_
}
_x000D_
<form>_x000D_
  <div class="multiselect">_x000D_
    <div class="selectBox" onclick="showCheckboxes()">_x000D_
      <select>_x000D_
        <option>Select an option</option>_x000D_
      </select>_x000D_
      <div class="overSelect"></div>_x000D_
    </div>_x000D_
    <div id="checkboxes">_x000D_
      <label for="one">_x000D_
        <input type="checkbox" id="one" />First checkbox</label>_x000D_
      <label for="two">_x000D_
        <input type="checkbox" id="two" />Second checkbox</label>_x000D_
      <label for="three">_x000D_
        <input type="checkbox" id="three" />Third checkbox</label>_x000D_
    </div>_x000D_
  </div>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Explanation:

At first we create a select element that shows text "Select an option", and empty element that covers (overlaps) the select element (<div class="overSelect">). We do not want the user to click on the select element - it would show an empty options. To overlap the element with other element we use CSS position property with value relative | absolute.

To add the functionality we specify a JavaScript function that is called when the user clicks on the div that contains our select element (<div class="selectBox" onclick="showCheckboxes()">).

We also create div that contains our checkboxes and style it using CSS. The above mentioned JavaScript function just changes <div id="checkboxes"> value of CSS display property from "none" to "block" and vice versa.

The solution was tested in the following browsers: Internet Explorer 10, Firefox 34, Chrome 39. The browser needs to have JavaScript enabled.


More information:

CSS positioning

How to overlay one div over another div

http://www.w3schools.com/css/css_positioning.asp

CSS display property

http://www.w3schools.com/cssref/pr_class_display.asp

Raise an event whenever a property's value changed?

I use largely the same patterns as Aaronaught, but if you have a lot of properties it could be nice to use a little generic method magic to make your code a little more DRY

public class TheClass : INotifyPropertyChanged {
    private int _property1;
    private string _property2;
    private double _property3;

    protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) {
        PropertyChangedEventHandler handler = PropertyChanged;
        if(handler != null) {
            handler(this, e);
        }
    }

    protected void SetPropertyField<T>(string propertyName, ref T field, T newValue) {
        if(!EqualityComparer<T>.Default.Equals(field, newValue)) {
            field = newValue;
            OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
        }
    }

    public int Property1 {
        get { return _property1; }
        set { SetPropertyField("Property1", ref _property1, value); }
    }
    public string Property2 {
        get { return _property2; }
        set { SetPropertyField("Property2", ref _property2, value); }
    }
    public double Property3 {
        get { return _property3; }
        set { SetPropertyField("Property3", ref _property3, value); }
    }

    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;

    #endregion
}

Usually I also make the OnPropertyChanged method virtual to allow sub-classes to override it to catch property changes.

How to make a launcher

Just develop a normal app and then add a couple of lines to the app's manifest file.

First you need to add the following attribute to your activity:

            android:launchMode="singleTask"

Then add two categories to the intent filter :

            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.HOME" />

The result could look something like this:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.dummy.app"
        android:versionCode="1"
        android:versionName="1.0" >

        <uses-sdk
            android:minSdkVersion="11"
            android:targetSdkVersion="19" />

        <application
            android:allowBackup="true"
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name"
            android:theme="@style/AppTheme" >
            <activity
                android:name="com.dummy.app.MainActivity"
                android:launchMode="singleTask"
                android:label="@string/app_name" >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
                    <category android:name="android.intent.category.DEFAULT" />
                    <category android:name="android.intent.category.HOME" />
                </intent-filter>
            </activity>
        </application>

    </manifest>

It's that simple!

Transform DateTime into simple Date in Ruby on Rails

For old Ruby (1.8.x):

myDate = Date.parse(myDateTime.to_s)

Posting array from form

If you want everything in your post to be as $Variables you can use something like this:

foreach($_POST as $key => $value) { eval("$" . $key . " = " . $value"); }

jquery: get value of custom attribute

You can also do this by passing function with onclick event

<a onclick="getColor(this);" color="red">

<script type="text/javascript">

function getColor(el)
{
     color = $(el).attr('color');
     alert(color);
}

</script> 

Android 'Unable to add window -- token null is not for an application' exception

I'm guessing - are you trying to create Dialog with an application context? Something like this:

new Dialog(getApplicationContext());

This is wrong. You need to use an Activity context.

You have to try like:

new Dialog(YourActivity.this);

wait() or sleep() function in jquery?

That'd be .delay().

http://api.jquery.com/delay/

If you are doing AJAX stuff tho, you really shouldn't just auto write "done" you should really wait for a response and see if it's actually done.

Which browsers support <script async="async" />?

Just had a look at the DOM (document.scripts[1].attributes) of this page that uses google analytics. I can tell you that google is using async="".

[type="text/javascript", async="", src="http://www.google-analytics.com/ga.js"]

"Undefined reference to" template class constructor

This is a common question in C++ programming. There are two valid answers to this. There are advantages and disadvantages to both answers and your choice will depend on context. The common answer is to put all the implementation in the header file, but there's another approach will will be suitable in some cases. The choice is yours.

The code in a template is merely a 'pattern' known to the compiler. The compiler won't compile the constructors cola<float>::cola(...) and cola<string>::cola(...) until it is forced to do so. And we must ensure that this compilation happens for the constructors at least once in the entire compilation process, or we will get the 'undefined reference' error. (This applies to the other methods of cola<T> also.)

Understanding the problem

The problem is caused by the fact that main.cpp and cola.cpp will be compiled separately first. In main.cpp, the compiler will implicitly instantiate the template classes cola<float> and cola<string> because those particular instantiations are used in main.cpp. The bad news is that the implementations of those member functions are not in main.cpp, nor in any header file included in main.cpp, and therefore the compiler can't include complete versions of those functions in main.o. When compiling cola.cpp, the compiler won't compile those instantiations either, because there are no implicit or explicit instantiations of cola<float> or cola<string>. Remember, when compiling cola.cpp, the compiler has no clue which instantiations will be needed; and we can't expect it to compile for every type in order to ensure this problem never happens! (cola<int>, cola<char>, cola<ostream>, cola< cola<int> > ... and so on ...)

The two answers are:

  • Tell the compiler, at the end of cola.cpp, which particular template classes will be required, forcing it to compile cola<float> and cola<string>.
  • Put the implementation of the member functions in a header file that will be included every time any other 'translation unit' (such as main.cpp) uses the template class.

Answer 1: Explicitly instantiate the template, and its member definitions

At the end of cola.cpp, you should add lines explicitly instantiating all the relevant templates, such as

template class cola<float>;
template class cola<string>;

and you add the following two lines at the end of nodo_colaypila.cpp:

template class nodo_colaypila<float>;
template class nodo_colaypila<std :: string>;

This will ensure that, when the compiler is compiling cola.cpp that it will explicitly compile all the code for the cola<float> and cola<string> classes. Similarly, nodo_colaypila.cpp contains the implementations of the nodo_colaypila<...> classes.

In this approach, you should ensure that all the of the implementation is placed into one .cpp file (i.e. one translation unit) and that the explicit instantation is placed after the definition of all the functions (i.e. at the end of the file).

Answer 2: Copy the code into the relevant header file

The common answer is to move all the code from the implementation files cola.cpp and nodo_colaypila.cpp into cola.h and nodo_colaypila.h. In the long run, this is more flexible as it means you can use extra instantiations (e.g. cola<char>) without any more work. But it could mean the same functions are compiled many times, once in each translation unit. This is not a big problem, as the linker will correctly ignore the duplicate implementations. But it might slow down the compilation a little.

Summary

The default answer, used by the STL for example and in most of the code that any of us will write, is to put all the implementations in the header files. But in a more private project, you will have more knowledge and control of which particular template classes will be instantiated. In fact, this 'bug' might be seen as a feature, as it stops users of your code from accidentally using instantiations you have not tested for or planned for ("I know this works for cola<float> and cola<string>, if you want to use something else, tell me first and will can verify it works before enabling it.").

Finally, there are three other minor typos in the code in your question:

  • You are missing an #endif at the end of nodo_colaypila.h
  • in cola.h nodo_colaypila<T>* ult, pri; should be nodo_colaypila<T> *ult, *pri; - both are pointers.
  • nodo_colaypila.cpp: The default parameter should be in the header file nodo_colaypila.h, not in this implementation file.

jQuery - Appending a div to body, the body is the object?

jQuery methods returns the set they were applied on.

Use .appendTo:

var $div = $('<div />').appendTo('body');
$div.attr('id', 'holdy');

Drop multiple tables in one shot in MySQL

declare @sql1 nvarchar(max) 
SELECT @sql1 =
  STUFF(
         (
           select ' drop table dbo.[' + name + ']'

           FROM sys.sysobjects AS sobjects
           WHERE (xtype = 'U') AND (name LIKE 'GROUP_BASE_NEW_WORK_%')
           for xml path('')
        ),
     1, 1, '')

  execute sp_executesql @sql1

Media Player called in state 0, error (-38,0)

You need to call mediaPlayer.start() in the onPrepared method by using a listener. You are getting this error because you are calling mediaPlayer.start() before it has reached the prepared state.

Here is how you can do it :

mp.setDataSource(url); 
mp.setOnPreparedListener(this);
mp.prepareAsync();

public void onPrepared(MediaPlayer player) {
    player.start();
}

How can I embed a YouTube video on GitHub wiki pages?

It's not possible to embed videos directly, but you can put an image which links to a YouTube video:

[![IMAGE ALT TEXT HERE](https://img.youtube.com/vi/YOUTUBE_VIDEO_ID_HERE/0.jpg)](https://www.youtube.com/watch?v=YOUTUBE_VIDEO_ID_HERE)

Int division: Why is the result of 1/3 == 0?

Many others have failed to point out the real issue:

An operation on only integers casts the result of the operation to an integer.

This necessarily means that floating point results, that could be displayed as an integer, will be truncated (lop off the decimal part).

What is casting (typecasting / type conversion) you ask?

It varies on the implementation of the language, but Wikipedia has a fairly comprehensive view, and it does talk about coercion as well, which is a pivotal piece of information in answering your question.

http://en.wikipedia.org/wiki/Type_conversion

"Could not find acceptable representation" using spring-boot-starter-web

I had the same exception but the cause was different and I couldn't find any info on that so I will post it here. It was just a simple to overlook mistake.

Bad:

@RestController(value = "/api/connection")

Good:

@RestController
@RequestMapping(value = "/api/connection")

Cannot convert lambda expression to type 'string' because it is not a delegate type

My case it solved i was using

@Html.DropDownList(model => model.TypeId ...)  

using

@Html.DropDownListFor(model => model.TypeId ...) 

will solve it

How to fix "containing working copy admin area is missing" in SVN?

I tried svn rm --force /path/to/dir to no avail but ended up just running svn up and it fixed it for me.

How do I find out if the GPS of an Android device is enabled

yes GPS settings cannot be changed programatically any more as they are privacy settings and we have to check if they are switched on or not from the program and handle it if they are not switched on. you can notify the user that GPS is turned off and use something like this to show the settings screen to the user if you want.

Check if location providers are available

    String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
    if(provider != null){
        Log.v(TAG, " Location providers: "+provider);
        //Start searching for location and update the location text when update available
        startFetchingLocation();
    }else{
        // Notify users and show settings if they want to enable GPS
    }

If the user want to enable GPS you may show the settings screen in this way.

Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(intent, REQUEST_CODE);

And in your onActivityResult you can see if the user has enabled it or not

    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        if(requestCode == REQUEST_CODE && resultCode == 0){
            String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
            if(provider != null){
                Log.v(TAG, " Location providers: "+provider);
                //Start searching for location and update the location text when update available. 
// Do whatever you want
                startFetchingLocation();
            }else{
                //Users did not switch on the GPS
            }
        }
    }

Thats one way to do it and i hope it helps. Let me know if I am doing anything wrong.

How to center an element in the middle of the browser window?

This should work with any div or screen size:

_x000D_
_x000D_
.center-screen {_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
  justify-content: center;_x000D_
  align-items: center;_x000D_
  text-align: center;_x000D_
  min-height: 100vh;_x000D_
}
_x000D_
 <html>_x000D_
 <head>_x000D_
 </head>_x000D_
 <body>_x000D_
 <div class="center-screen">_x000D_
 I'm in the center_x000D_
 </div>_x000D_
 </body>_x000D_
 </html>
_x000D_
_x000D_
_x000D_

See more details about flex here. This should work on most of the browsers, see compatibility matrix here.

Select DISTINCT individual columns in django?

It's quite simple actually if you're using PostgreSQL, just use distinct(columns) (documentation).

Productorder.objects.all().distinct('category')

Note that this feature has been included in Django since 1.4

generate random double numbers in c++

This solution requires C++11 (or TR1).

#include <random>

int main()
{
   double lower_bound = 0;
   double upper_bound = 10000;
   std::uniform_real_distribution<double> unif(lower_bound,upper_bound);
   std::default_random_engine re;
   double a_random_double = unif(re);

   return 0;
}

For more details see John D. Cook's "Random number generation using C++ TR1".

See also Stroustrup's "Random number generation".

unix - count of columns in file

If you have python installed you could try:

python -c 'import sys;f=open(sys.argv[1]);print len(f.readline().split("|"))' \
    stores.dat

Is there a way to only install the mysql client (Linux)?

To install only mysql (client) you should execute

yum install mysql

To install mysql client and mysql server:

yum install mysql mysql-server

"This operation requires IIS integrated pipeline mode."

GitHub solution solved the problem for me by adding

  • Global.asax.cs: Set AntiForgeryConfig.SuppressXFrameOptionsHeader = true; in Application_Start:
  • Manually add the X-Frame-Options header in Application_BeginRequest

How can I clear previous output in Terminal in Mac OS X?

I couldn't get any of the previous answers to work (on macOS).

A combination worked for me -

IO.write "\e[H\e[2J\e[3J"

This clears the buffer and the screen.

PLS-00428: an INTO clause is expected in this SELECT statement

In PLSQL block, columns of select statements must be assigned to variables, which is not the case in SQL statements.

The second BEGIN's SQL statement doesn't have INTO clause and that caused the error.

DECLARE
   PROD_ROW_ID   VARCHAR (10) := NULL;
   VIS_ROW_ID    NUMBER;
   DSC           VARCHAR (512);
BEGIN
   SELECT ROW_ID
     INTO VIS_ROW_ID
     FROM SIEBEL.S_PROD_INT
    WHERE PART_NUM = 'S0146404';

   BEGIN
      SELECT    RTRIM (VIS.SERIAL_NUM)
             || ','
             || RTRIM (PLANID.DESC_TEXT)
             || ','
             || CASE
                   WHEN PLANID.HIGH = 'TEST123'
                   THEN
                      CASE
                         WHEN TO_DATE (PROD.START_DATE) + 30 > SYSDATE
                         THEN
                            'Y'
                         ELSE
                            'N'
                      END
                   ELSE
                      'N'
                END
             || ','
             || 'GB'
             || ','
             || RTRIM (TO_CHAR (PROD.START_DATE, 'YYYY-MM-DD'))
        INTO DSC
        FROM SIEBEL.S_LST_OF_VAL PLANID
             INNER JOIN SIEBEL.S_PROD_INT PROD
                ON PROD.PART_NUM = PLANID.VAL
             INNER JOIN SIEBEL.S_ASSET NETFLIX
                ON PROD.PROD_ID = PROD.ROW_ID
             INNER JOIN SIEBEL.S_ASSET VIS
                ON VIS.PROM_INTEG_ID = PROD.PROM_INTEG_ID
             INNER JOIN SIEBEL.S_PROD_INT VISPROD
                ON VIS.PROD_ID = VISPROD.ROW_ID
       WHERE     PLANID.TYPE = 'Test Plan'
             AND PLANID.ACTIVE_FLG = 'Y'
             AND VISPROD.PART_NUM = VIS_ROW_ID
             AND PROD.STATUS_CD = 'Active'
             AND VIS.SERIAL_NUM IS NOT NULL;
   END;
END;
/

References

http://docs.oracle.com/cd/E11882_01/appdev.112/e25519/static.htm#LNPLS00601 http://docs.oracle.com/cd/B19306_01/appdev.102/b14261/selectinto_statement.htm#CJAJAAIG http://pls-00428.ora-code.com/

Showing ValueError: shapes (1,3) and (1,3) not aligned: 3 (dim 1) != 1 (dim 0)

Unlike standard arithmetic, which desires matching dimensions, dot products require that the dimensions are one of:

  • (X..., A, B) dot (Y..., B, C) -> (X..., Y..., A, C), where ... means "0 or more different values
  • (B,) dot (B, C) -> (C,)
  • (A, B) dot (B,) -> (A,)
  • (B,) dot (B,) -> ()

Your problem is that you are using np.matrix, which is totally unnecessary in your code - the main purpose of np.matrix is to translate a * b into np.dot(a, b). As a general rule, np.matrix is probably not a good choice.

sys.stdin.readline() reads without prompt, returning 'nothing in between'

Simon's answer and Volcano's together explain what you're doing wrong, and Simon explains how you can fix it by redesigning your interface.

But if you really need to read 1 character, and then later read 1 line, you can do that. It's not trivial, and it's different on Windows vs. everything else.

There are actually three cases: a Unix tty, a Windows DOS prompt, or a regular file (redirected file/pipe) on either platform. And you have to handle them differently.

First, to check if stdin is a tty (both Windows and Unix varieties), you just call sys.stdin.isatty(). That part is cross-platform.

For the non-tty case, it's easy. It may actually just work. If it doesn't, you can just read from the unbuffered object underneath sys.stdin. In Python 3, this just means sys.stdin.buffer.raw.read(1) and sys.stdin.buffer.raw.readline(). However, this will get you encoded bytes, rather than strings, so you will need to call .decode(sys.stdin.decoding) on the results; you can wrap that all up in a function.

For the tty case on Windows, however, input will still be line buffered even on the raw buffer. The only way around this is to use the Console I/O functions instead of normal file I/O. So, instead of stdin.read(1), you do msvcrt.getwch().

For the tty case on Unix, you have to set the terminal to raw mode instead of the usual line-discipline mode. Once you do that, you can use the same sys.stdin.buffer.read(1), etc., and it will just work. If you're willing to do that permanently (until the end of your script), it's easy, with the tty.setraw function. If you want to return to line-discipline mode later, you'll need to use the termios module. This looks scary, but if you just stash the results of termios.tcgetattr(sys.stdin.fileno()) before calling setraw, then do termios.tcsetattr(sys.stdin.fileno(), TCSAFLUSH, stash), you don't have to learn what all those fiddly bits mean.

On both platforms, mixing console I/O and raw terminal mode is painful. You definitely can't use the sys.stdin buffer if you've ever done any console/raw reading; you can only use sys.stdin.buffer.raw. You could always replace readline by reading character by character until you get a newline… but if the user tries to edit his entry by using backspace, arrows, emacs-style command keys, etc., you're going to get all those as raw keypresses, which you don't want to deal with.

Why does jQuery or a DOM method such as getElementById not find the element?

The element you were trying to find wasn’t in the DOM when your script ran.

The position of your DOM-reliant script can have a profound effect upon its behavior. Browsers parse HTML documents from top to bottom. Elements are added to the DOM and scripts are (generally) executed as they're encountered. This means that order matters. Typically, scripts can't find elements which appear later in the markup because those elements have yet to be added to the DOM.

Consider the following markup; script #1 fails to find the <div> while script #2 succeeds:

_x000D_
_x000D_
<script>_x000D_
  console.log("script #1: %o", document.getElementById("test")); // null_x000D_
</script>_x000D_
<div id="test">test div</div>_x000D_
<script>_x000D_
  console.log("script #2: %o", document.getElementById("test")); // <div id="test" ..._x000D_
</script>
_x000D_
_x000D_
_x000D_

So, what should you do? You've got a few options:


Option 1: Move your script

Move your script further down the page, just before the closing body tag. Organized in this fashion, the rest of the document is parsed before your script is executed:

_x000D_
_x000D_
<body>_x000D_
  <button id="test">click me</button>_x000D_
  <script>_x000D_
    document.getElementById("test").addEventListener("click", function() {_x000D_
      console.log("clicked: %o", this);_x000D_
    });_x000D_
  </script>_x000D_
</body><!-- closing body tag -->
_x000D_
_x000D_
_x000D_

Note: Placing scripts at the bottom is generally considered a best practice.


Option 2: jQuery's ready()

Defer your script until the DOM has been completely parsed, using $(handler):

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script>_x000D_
  $(function() {_x000D_
    $("#test").click(function() {_x000D_
      console.log("clicked: %o", this);_x000D_
    });_x000D_
  });_x000D_
</script>_x000D_
<button id="test">click me</button>
_x000D_
_x000D_
_x000D_

Note: You could simply bind to DOMContentLoaded or window.onload but each has its caveats. jQuery's ready() delivers a hybrid solution.


Option 3: Event Delegation

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.

When an element raises an event (provided that it's a bubbling event and nothing stops its propagation), each parent in that element's ancestry receives the event as well. That allows us to attach a handler to an existing element and sample events as they bubble up from its descendants... even those added after the handler is attached. All we have to do is check the event to see whether it was raised by the desired element and, if so, run our code.

jQuery's on() performs that logic for us. We simply provide an event name, a selector for the desired descendant, and an event handler:

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script>_x000D_
  $(document).on("click", "#test", function(e) {_x000D_
    console.log("clicked: %o",  this);_x000D_
  });_x000D_
</script>_x000D_
<button id="test">click me</button>
_x000D_
_x000D_
_x000D_

Note: Typically, this pattern is reserved for elements which didn't exist at load-time or to avoid attaching a large amount of handlers. It's also worth pointing out that while I've attached a handler to document (for demonstrative purposes), you should select the nearest reliable ancestor.


Option 4: The defer attribute

Use the defer attribute of <script>.

[defer, a Boolean attribute,] is set to indicate to a browser that the script is meant to be executed after the document has been parsed, but before firing DOMContentLoaded.

_x000D_
_x000D_
<script src="https://gh-canon.github.io/misc-demos/log-test-click.js" defer></script>_x000D_
<button id="test">click me</button>
_x000D_
_x000D_
_x000D_

For reference, here's the code from that external script:

document.getElementById("test").addEventListener("click", function(e){
   console.log("clicked: %o", this); 
});

Note: The defer attribute certainly seems like a magic bullet but it's important to be aware of the caveats...
1. defer can only be used for external scripts, i.e.: those having a src attribute.
2. be aware of browser support, i.e.: buggy implementation in IE < 10

Quicksort: Choosing the pivot

I recommend using the middle index, as it can be calculated easily.

You can calculate it by rounding (array.length / 2).

Showing empty view when ListView is empty

It should be like this:

<TextView android:id="@android:id/empty"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="No Results" />

Note the id attribute.

Integer division with remainder in JavaScript?

If you need to calculate the remainder for very large integers, which the JS runtime cannot represent as such (any integer greater than 2^32 is represented as a float and so it loses precision), you need to do some trick.

This is especially important for checking many case of check digits which are present in many instances of our daily life (bank account numbers, credit cards, ...)

First of all you need your number as a string (otherwise you have already lost precision and the remainder does not make sense).

str = '123456789123456789123456789'

You now need to split your string in smaller parts, small enough so the concatenation of any remainder and a piece of string can fit in 9 digits.

digits = 9 - String(divisor).length

Prepare a regular expression to split the string

splitter = new RegExp(`.{1,${digits}}(?=(.{${digits}})+$)`, 'g')

For instance, if digits is 7, the regexp is

/.{1,7}(?=(.{7})+$)/g

It matches a nonempty substring of maximum length 7, which is followed ((?=...) is a positive lookahead) by a number of characters that is multiple of 7. The 'g' is to make the expression run through all string, not stopping at first match.

Now convert each part to integer, and calculate the remainders by reduce (adding back the previous remainder - or 0 - multiplied by the correct power of 10):

reducer = (rem, piece) => (rem * Math.pow(10, digits) + piece) % divisor

This will work because of the "subtraction" remainder algorithm:

n mod d = (n - kd) mod d

which allows to replace any 'initial part' of the decimal representation of a number with its remainder, without affecting the final remainder.

The final code would look like:

function remainder(num, div) {
  const digits = 9 - String(div).length;
  const splitter = new RegExp(`.{1,${digits}}(?=(.{${digits}})+$)`, 'g');
  const mult = Math.pow(10, digits);
  const reducer = (rem, piece) => (rem * mult + piece) % div;

  return str.match(splitter).map(Number).reduce(reducer, 0);
}

How do I add my bot to a channel?

Are you using the right chat_id and including your bot's token after "bot" in the address? (api.telegram.org/bottoken/sendMessage)

This page explains a few things about sending (down in "sendMessage" section) - basic stuff, but I often forget the basics.

To quote:

In order to use the sendMessage method we need to use the proper chat_id.

First things first let's send the /start command to our bot via a Telegram client.

After sent this command let's perform a getUpdates commands.

curl -s \
-X POST \ https://api.telegram.org/bot<token>/getUpdates \ | jq .

The response will be like the following

{   "result": [
     {
       "message": {
        "text": "/start",
         "date": 1435176541,
         "chat": {
           "username": "yourusername",
           "first_name": "yourfirstname",
           "id": 65535
         },
         "from": {
           "username": "yourusername",
           "first_name": "yourfirstname",
           "id": 65535
         },
         "message_id": 1
       },
       "update_id": 714636917
     }    ],   "ok": true }

We are interested in the property result.message[0].chat.id, save this information elsewhere.

Please note that this is only an example, you may want to set up some automatism to handle those informations Now how we can send a message ? It's simple let's check out this snippet.

curl -s \
-X POST \ https://api.telegram.org/bot<token>/sendMessage \
-d text="A message from your bot" \
-d chat_id=65535 \ | jq .

Where chat_id is the piece of information saved before.

I hope that helps.

HTML5 File API read as text and binary

Note in 2018: readAsBinaryString is outdated. For use cases where previously you'd have used it, these days you'd use readAsArrayBuffer (or in some cases, readAsDataURL) instead.


readAsBinaryString says that the data must be represented as a binary string, where:

...every byte is represented by an integer in the range [0..255].

JavaScript originally didn't have a "binary" type (until ECMAScript 5's WebGL support of Typed Array* (details below) -- it has been superseded by ECMAScript 2015's ArrayBuffer) and so they went with a String with the guarantee that no character stored in the String would be outside the range 0..255. (They could have gone with an array of Numbers instead, but they didn't; perhaps large Strings are more memory-efficient than large arrays of Numbers, since Numbers are floating-point.)

If you're reading a file that's mostly text in a western script (mostly English, for instance), then that string is going to look a lot like text. If you read a file with Unicode characters in it, you should notice a difference, since JavaScript strings are UTF-16** (details below) and so some characters will have values above 255, whereas a "binary string" according to the File API spec wouldn't have any values above 255 (you'd have two individual "characters" for the two bytes of the Unicode code point).

If you're reading a file that's not text at all (an image, perhaps), you'll probably still get a very similar result between readAsText and readAsBinaryString, but with readAsBinaryString you know that there won't be any attempt to interpret multi-byte sequences as characters. You don't know that if you use readAsText, because readAsText will use an encoding determination to try to figure out what the file's encoding is and then map it to JavaScript's UTF-16 strings.

You can see the effect if you create a file and store it in something other than ASCII or UTF-8. (In Windows you can do this via Notepad; the "Save As" as an encoding drop-down with "Unicode" on it, by which looking at the data they seem to mean UTF-16; I'm sure Mac OS and *nix editors have a similar feature.) Here's a page that dumps the result of reading a file both ways:

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Show File Data</title>
<style type='text/css'>
body {
    font-family: sans-serif;
}
</style>
<script type='text/javascript'>

    function loadFile() {
        var input, file, fr;

        if (typeof window.FileReader !== 'function') {
            bodyAppend("p", "The file API isn't supported on this browser yet.");
            return;
        }

        input = document.getElementById('fileinput');
        if (!input) {
            bodyAppend("p", "Um, couldn't find the fileinput element.");
        }
        else if (!input.files) {
            bodyAppend("p", "This browser doesn't seem to support the `files` property of file inputs.");
        }
        else if (!input.files[0]) {
            bodyAppend("p", "Please select a file before clicking 'Load'");
        }
        else {
            file = input.files[0];
            fr = new FileReader();
            fr.onload = receivedText;
            fr.readAsText(file);
        }

        function receivedText() {
            showResult(fr, "Text");

            fr = new FileReader();
            fr.onload = receivedBinary;
            fr.readAsBinaryString(file);
        }

        function receivedBinary() {
            showResult(fr, "Binary");
        }
    }

    function showResult(fr, label) {
        var markup, result, n, aByte, byteStr;

        markup = [];
        result = fr.result;
        for (n = 0; n < result.length; ++n) {
            aByte = result.charCodeAt(n);
            byteStr = aByte.toString(16);
            if (byteStr.length < 2) {
                byteStr = "0" + byteStr;
            }
            markup.push(byteStr);
        }
        bodyAppend("p", label + " (" + result.length + "):");
        bodyAppend("pre", markup.join(" "));
    }

    function bodyAppend(tagName, innerHTML) {
        var elm;

        elm = document.createElement(tagName);
        elm.innerHTML = innerHTML;
        document.body.appendChild(elm);
    }

</script>
</head>
<body>
<form action='#' onsubmit="return false;">
<input type='file' id='fileinput'>
<input type='button' id='btnLoad' value='Load' onclick='loadFile();'>
</form>
</body>
</html>

If I use that with a "Testing 1 2 3" file stored in UTF-16, here are the results I get:

Text (13):

54 65 73 74 69 6e 67 20 31 20 32 20 33

Binary (28):

ff fe 54 00 65 00 73 00 74 00 69 00 6e 00 67 00 20 00 31 00 20 00 32 00 20 00 33 00

As you can see, readAsText interpreted the characters and so I got 13 (the length of "Testing 1 2 3"), and readAsBinaryString didn't, and so I got 28 (the two-byte BOM plus two bytes for each character).


* XMLHttpRequest.response with responseType = "arraybuffer" is supported in HTML 5.

** "JavaScript strings are UTF-16" may seem like an odd statement; aren't they just Unicode? No, a JavaScript string is a series of UTF-16 code units; you see surrogate pairs as two individual JavaScript "characters" even though, in fact, the surrogate pair as a whole is just one character. See the link for details.

Resolve absolute path from relative path and/or file name

This is to help fill in the gaps in Adrien Plisson's answer (which should be upvoted as soon as he edits it ;-):

you can also get the fully qualified path of your first argument by using %~f1, but this gives a path according to the current path, which is obviously not what you want.

unfortunately, i don't know how to mix the 2 together...

One can handle %0 and %1 likewise:

  • %~dpnx0 for fully qualified drive+path+name+extension of the batchfile itself,
    %~f0 also suffices;
  • %~dpnx1 for fully qualified drive+path+name+extension of its first argument [if that's a filename at all],
    %~f1 also suffices;

%~f1 will work independent of how you did specify your first argument: with relative paths or with absolute paths (if you don't specify the file's extension when naming %1, it will not be added, even if you use %~dpnx1 -- however.

But how on earth would you name a file on a different drive anyway if you wouldn't give that full path info on the commandline in the first place?

However, %~p0, %~n0, %~nx0 and %~x0 may come in handy, should you be interested in path (without driveletter), filename (without extension), full filename with extension or filename's extension only. But note, while %~p1 and %~n1 will work to find out the path or name of the first argument, %~nx1 and %~x1 will not add+show the extension, unless you used it on the commandline already.

Create file path from variables

You can also use an object-oriented path with pathlib (available as a standard library as of Python 3.4):

from pathlib import Path

start_path = Path('/my/root/directory')
final_path = start_path / 'in' / 'here'

ggplot2 line chart gives "geom_path: Each group consist of only one observation. Do you need to adjust the group aesthetic?"

You get this error because one of your variables is actually a factor variable . Execute

str(df) 

to check this. Then do this double variable change to keep the year numbers instead of transforming into "1,2,3,4" level numbers:

df$year <- as.numeric(as.character(df$year))

EDIT: it appears that your data.frame has a variable of class "array" which might cause the pb. Try then:

df <- data.frame(apply(df, 2, unclass))

and plot again?

What’s the best way to check if a file exists in C++? (cross platform)

Use boost::filesystem:

#include <boost/filesystem.hpp>

if ( !boost::filesystem::exists( "myfile.txt" ) )
{
  std::cout << "Can't find my file!" << std::endl;
}

How to create a foreign key in phpmyadmin

When you create table than you can give like follows.

CREATE TABLE categories(
cat_id int not null auto_increment primary key,
cat_name varchar(255) not null,
cat_description text
) ENGINE=InnoDB;


CREATE TABLE products(
   prd_id int not null auto_increment primary key,
   prd_name varchar(355) not null,
   prd_price decimal,
   cat_id int not null,
   FOREIGN KEY fk_cat(cat_id)
   REFERENCES categories(cat_id)
   ON UPDATE CASCADE
   ON DELETE RESTRICT
)ENGINE=InnoDB;

and when after the table create like this

   ALTER table_name
    ADD CONSTRAINT constraint_name
    FOREIGN KEY foreign_key_name(columns)
    REFERENCES parent_table(columns)
    ON DELETE action
    ON UPDATE action;

Following on example for it.

CREATE TABLE vendors(
    vdr_id int not null auto_increment primary key,
    vdr_name varchar(255)
)ENGINE=InnoDB;

ALTER TABLE products 
ADD COLUMN vdr_id int not null AFTER cat_id;

To add a foreign key to the products table, you use the following statement:

ALTER TABLE products
ADD FOREIGN KEY fk_vendor(vdr_id)
REFERENCES vendors(vdr_id)
ON DELETE NO ACTION
ON UPDATE CASCADE;

For drop the key

ALTER TABLE table_name 
DROP FOREIGN KEY constraint_name;

Hope this help to learn FOREIGN keys works

Call to getLayoutInflater() in places not in activity

Or ...

LayoutInflater inflater = LayoutInflater.from(context);

Retrieve a single file from a repository

If there is web interface deployed (like gitweb, cgit, Gitorious, ginatra), you can use it to download single file ('raw' or 'plain' view).

If other side enabled it, you can use git archive's '--remote=<URL>' option (and possibly limit it to a directory given file resides in), for example:

$ git archive [email protected]:foo/bar.git --prefix=path/to/ HEAD:path/to/ |  tar xvf -

adding 1 day to a DATETIME format value

I suggest start using Zend_Date classes from Zend Framework. I know, its a bit offtopic, but I'll like this way :-)

$date = new Zend_Date();
$date->add('24:00:00', Zend_Date::TIMES);
print $date->get();

how to run vibrate continuously in iphone?

Read the Apple Human Interaction Guidelines for iPhone. I believe this is not approved behavior in an app.

How to reset AUTO_INCREMENT in MySQL?

As of MySQL 5.6 the approach below works faster due to online DDL (note algorithm=inplace):

alter table tablename auto_increment=1, algorithm=inplace;

Amazon Linux: apt-get: command not found

You need to manually download the apt deb package. Then run dpkg and it should install.

WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'. Please add a ScriptResourceMapping named jquery(case-sensitive)

You need a web.config key to enable the pre 4.5 validation mode.

More Info on ValidationSettings:UnobtrusiveValidationMode:

Specifies how ASP.NET globally enables the built-in validator controls to use unobtrusive JavaScript for client-side validation logic.

Type: UnobtrusiveValidationMode

Default value: None

Remarks: If this key value is set to "None" [default], the ASP.NET application will use the pre-4.5 behavior (JavaScript inline in the pages) for client-side validation logic. If this key value is set to "WebForms", ASP.NET uses HTML5 data-attributes and late bound JavaScript from an added script reference for client-side validation logic.

Example:

    <appSettings>
      <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
    </appSettings>

Failed to install *.apk on device 'emulator-5554': EOF

you could try this:

   1. Open the "Android Virtual device Manager"
   2. Select from one the listed devices there and run it.
   3. Right click your Android App -> Run As -> Android Application

It worked for me. I tried this on an emulator in eclipse. It takes a while before the app is run. For me it took 33 seconds. Wait until the message in the console says "Success!"

Insert data into hive table

You can insert new data into table by two ways.

  1. Load the data of a file into table using load command.

    LOAD DATA [LOCAL] INPATH 'filepath' [OVERWRITE] INTO TABLE tablename.
    
  2. You can insert new data into table by using select query.

    INSERT INTO table tablename1 select columnlist FROM secondtable;
    

Trying to use fetch and pass in mode: no-cors

Very easy solution (2 min to config) is to use local-ssl-proxy package from npm

The usage is straight pretty forward:
1. Install the package: npm install -g local-ssl-proxy
2. While running your local-server mask it with the local-ssl-proxy --source 9001 --target 9000

P.S: Replace --target 9000 with the -- "number of your port" and --source 9001 with --source "number of your port +1"

Trust Store vs Key Store - creating with keytool

The terminology is a bit confusing indeed, but both javax.net.ssl.keyStore and javax.net.ssl.trustStore are used to specify which keystores to use, for two different purposes. Keystores come in various formats and are not even necessarily files (see this question), and keytool is just a tool to perform various operations on them (import/export/list/...).

The javax.net.ssl.keyStore and javax.net.ssl.trustStore parameters are the default parameters used to build KeyManagers and TrustManagers (respectively), then used to build an SSLContext which essentially contains the SSL/TLS settings to use when making an SSL/TLS connection via an SSLSocketFactory or an SSLEngine. These system properties are just where the default values come from, which is then used by SSLContext.getDefault(), itself used by SSLSocketFactory.getDefault() for example. (All of this can be customized via the API in a number of places, if you don't want to use the default values and that specific SSLContexts for a given purpose.)

The difference between the KeyManager and TrustManager (and thus between javax.net.ssl.keyStore and javax.net.ssl.trustStore) is as follows (quoted from the JSSE ref guide):

TrustManager: Determines whether the remote authentication credentials (and thus the connection) should be trusted.

KeyManager: Determines which authentication credentials to send to the remote host.

(Other parameters are available and their default values are described in the JSSE ref guide. Note that while there is a default value for the trust store, there isn't one for the key store.)

Essentially, the keystore in javax.net.ssl.keyStore is meant to contain your private keys and certificates, whereas the javax.net.ssl.trustStore is meant to contain the CA certificates you're willing to trust when a remote party presents its certificate. In some cases, they can be one and the same store, although it's often better practice to use distinct stores (especially when they're file-based).

How to monitor Java memory usage?

If you want to really look at what is going on in the VM memory you should use a good tool like VisualVM. This is Free Software and it's a great way to see what is going on.

Nothing is really "wrong" with explicit gc() calls. However, remember that when you call gc() you are "suggesting" that the garbage collector run. There is no guarantee that it will run at the exact time you run that command.

Adding blur effect to background in swift

Found another way.. I use apple's UIImage+ImageEffects.

 UIImage *effectImage = [image applyExtraLightEffect];                        
 self.imageView.image = effectImage;

pthread_join() and pthread_exit()

The typical use is

void* ret = NULL;
pthread_t tid = something; /// change it suitably
if (pthread_join (tid, &ret)) 
   handle_error();
// do something with the return value ret

What is a "method" in Python?

In Python, a method is a function that is available for a given object because of the object's type.

For example, if you create my_list = [1, 2, 3], the append method can be applied to my_list because it's a Python list: my_list.append(4). All lists have an append method simply because they are lists.

As another example, if you create my_string = 'some lowercase text', the upper method can be applied to my_string simply because it's a Python string: my_string.upper().

Lists don't have an upper method, and strings don't have an append method. Why? Because methods only exist for a particular object if they have been explicitly defined for that type of object, and Python's developers have (so far) decided that those particular methods are not needed for those particular objects.

To call a method, the format is object_name.method_name(), and any arguments to the method are listed within the parentheses. The method implicitly acts on the object being named, and thus some methods don't have any stated arguments since the object itself is the only necessary argument. For example, my_string.upper() doesn't have any listed arguments because the only required argument is the object itself, my_string.

One common point of confusion regards the following:

import math
math.sqrt(81)

Is sqrt a method of the math object? No. This is how you call the sqrt function from the math module. The format being used is module_name.function_name(), instead of object_name.method_name(). In general, the only way to distinguish between the two formats (visually) is to look in the rest of the code and see if the part before the period (math, my_list, my_string) is defined as an object or a module.

CSS3 background image transition

If you can use jQuery, you can try BgSwitcher plugin to switch the background-image with effects, it's very easy to use.

For example :

$('.bgSwitch').bgswitcher({
        images: ["style/img/bg0.jpg","style/img/bg1.jpg","style/img/bg2.jpg"],
        effect: "fade",
        interval: 10000
});

And add your own effect, see adding an effect types

Unable to launch the IIS Express Web server

Had been messing around with IISExpress and Project to try and get it listening on a different URL than localhost, when reverting back I had this error and after following all the answers here, none of them worked.

Eventually noticed that in the projects Porperties -> Web I had 'Start URL' checked under Start Action, but the input box was empty. Changing this to 'Current Page' fixed my issue.

What is the different between RESTful and RESTless

REST stands for REpresentational State Transfer and goes a little something like this:

We have a bunch of uniquely addressable 'entities' that we want made available via a web application. Those entities each have some identifier and can be accessed in various formats. REST defines a bunch of stuff about what GET, POST, etc mean for these purposes.

the basic idea with REST is that you can attach a bunch of 'renderers' to different entities so that they can be available in different formats easily using the same HTTP verbs and url formats.

For more clarification on what RESTful means and how it is used google rails. Rails is a RESTful framework so there's loads of good information available in its docs and associated blog posts. Worth a read even if you arent keen to use the framework. For example: http://www.sitepoint.com/restful-rails-part-i/

RESTless means not restful. If you have a web app that does not adhere to RESTful principles then it is not RESTful

How to install gdb (debugger) in Mac OSX El Capitan?

On my Mac OS X El Capitan, I use homebrew to install gdb:

brew install gdb

Then I follow the instruction here: https://sourceware.org/gdb/wiki/BuildingOnDarwin, in the section 2.1. Method for Mac OS X 10.5 (Leopard) and later.

How do I configure git to ignore some files locally?

You can simply add a .gitignore file to your home directory, i.e. $HOME/.gitignore or ~/.gitignore. Then tell git to use that file with the command:

git config --global core.excludesfile ~/.gitignore

This is a normal .gitignore file which git references when deciding what to ignore. Since it's in your home directory, it applies only to you and doesn't pollute any project .gitignore files.

I've been using this approach for years with great results.

How to get response status code from jQuery.ajax?

jqxhr is a json object:

complete returns:
The jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string categorizing the status of the request ("success", "notmodified", "error", "timeout", "abort", or "parsererror").

see: jQuery ajax

so you would do:

jqxhr.status to get the status

Does Hive have a String split function?

There does exist a split function based on regular expressions. It's not listed in the tutorial, but it is listed on the language manual on the wiki:

split(string str, string pat)
   Split str around pat (pat is a regular expression) 

In your case, the delimiter "|" has a special meaning as a regular expression, so it should be referred to as "\\|".

Why, Fatal error: Class 'PHPUnit_Framework_TestCase' not found in ...?

You may get this error because you namespaced the file. If so you will need to specify that PHPUnit_Framework_TestCase is in the global namespace by preceding it with a backslash:

namespace AcmeInc\MyApplication\Tests
class StackTest extends \PHPUnit_Framework_TestCase {}

I submitted a crude PR to start conversation for correcting the documentation.

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

xargs is fast:

#!/usr/bin/bash
echo "while loop:"
n=0; time while (( n++ < 10000 )); do /usr/bin/true ; done

echo -e "\nfor loop:"
time for ((n=0;n<10000;n++)); do /usr/bin/true ; done

echo -e "\nseq,xargs:"
time seq 10000 | xargs -I{} -P1 -n1 /usr/bin/true

echo -e "\nyes,xargs:"
time yes x | head -n10000 |  xargs -I{} -P1 -n1 /usr/bin/true

echo -e "\nparallel:"
time parallel --will-cite -j1 -N0 /usr/bin/true ::: {1..10000}

On a modern 64-bit Linux, gives:

while loop:

real    0m2.282s
user    0m0.177s
sys     0m0.413s

for loop:

real    0m2.559s
user    0m0.393s
sys     0m0.500s

seq,xargs:

real    0m1.728s
user    0m0.013s
sys     0m0.217s

yes,xargs:

real    0m1.723s
user    0m0.013s
sys     0m0.223s

parallel:

real    0m26.271s
user    0m4.943s
sys     0m3.533s

This makes sense, as the xargs command is a single native process that spawns the /usr/bin/true command multiple time, instead of the for and while loops that are all interpreted in Bash. Of course this only works for a single command; if you need to do multiple commands in each iteration the loop, it will be just as fast, or maybe faster, than passing sh -c 'command1; command2; ...' to xargs

The -P1 could also be changed to, say, -P8 to spawn 8 processes in parallel to get another big boost in speed.

I don't know why GNU parallel is so slow. I would have thought it would be comparable to xargs.

HTTP POST with URL query parameters -- good idea or not?

The REST camp have some guiding principles that we can use to standardize the way we use HTTP verbs. This is helpful when building RESTful API's as you are doing.

In a nutshell: GET should be Read Only i.e. have no effect on server state. POST is used to create a resource on the server. PUT is used to update or create a resource. DELETE is used to delete a resource.

In other words, if your API action changes the server state, REST advises us to use POST/PUT/DELETE, but not GET.

User agents usually understand that doing multiple POSTs is bad and will warn against it, because the intent of POST is to alter server state (eg. pay for goods at checkout), and you probably don't want to do that twice!

Compare to a GET which you can do an often as you like (idempotent).

Get data from JSON file with PHP

Use json_decode to transform your JSON into a PHP array. Example:

$json = '{"a":"b"}';
$array = json_decode($json, true);
echo $array['a']; // b

How to change the JDK for a Jenkins job?

Here is my experience with Jenkins version 1.636: as long as I have only one "Install automatically" JDK configured in Jenkins JDK section, I don't see "JDK" dropdown in Job=>Configure section, but as soon as I added second JDK in Jenkins config, JDK dropdown appeared in Job=>Configure section with 3 options [(System), JDK1, JDK2]

Design Android EditText to show error message as described by google

TextInputLayout til = (TextInputLayout)editText.getParent();
til.setErrorEnabled(true);
til.setError("some error..");

Parsing JSON objects for HTML table

I spent a lot of time developing various reports. So, now I have an idea - create a web framework for building web reports. I have started here:

https://github.com/ColdSIce/ReportUI

Now it is an angular 4 module. You can pass your json data to TableLayoutComponent and get a HTML table as result. Table already has fixed header. Also you can fix some your columns by default or by click. More there, you can customize table properties like background-color, font-color, row-height etc.

If you are interested you can join me in this project and help.

first-child and last-child with IE8

If your table is only 2 columns across, you can easily reach the second td with the adjacent sibling selector, which IE8 does support along with :first-child:

.editor td:first-child
{
    width: 150px; 
}

.editor td:first-child + td input,
.editor td:first-child + td textarea
{
    width: 500px;
    padding: 3px 5px 5px 5px;
    border: 1px solid #CCC; 
}

Otherwise, you'll have to use a JS selector library like jQuery, or manually add a class to the last td, as suggested by James Allardice.

month name to month number and vice versa in python

If you don't want to import the calendar library, and need something that is a bit more robust -- you can make your code a little bit more dynamic to inconsistent text input than some of the other solutions provided. You can:

  1. Create a month_to_number dictionary
  2. loop through the .items() of that dictionary and check if the lowercase of a string s is in a lowercase key k.

month_to_number = {
'January' : 1,         
'February' : 2,         
'March' : 3,           
'April' : 4,              
'May' : 5, 
'June' : 6,
'July' : 7, 
'August' : 8, 
'September' : 9, 
'October' : 10, 
'November' : 11, 
'December' : 12}

s = 'jun'
[v for k, v in month_to_number.items() if s.lower() in k.lower()][0]

Out[1]: 6

Likewise, if you have a list l instead of a string, you can add another for to loop through the list. The list I have created has inconsistent values, but the output is still what would be desired for the correct month number:

l = ['January', 'february', 'mar', 'Apr', 'MAY', 'JUne', 'july']
[v for k, v in month_to_number.items() for m in l if m.lower() in k.lower()]

Out[2]: [1, 2, 3, 4, 5, 6, 7]

The use case for me here is that I am using Selenium to scrape data from a website by automatically selecting a dropdown value based off of some conditions. Anyway, this requires me relying on some data that I believe our vendor is manually entering to title each month, and I don't want to come back to my code if they format something slightly differently than they have done historically.

getOutputStream() has already been called for this response

I didn't use JSP but I had similar error when I was setting response to return JSON object by calling PrintWriter's flush() method or return statement. Previous answer i.e wrapping return-statement into a try-block worked kind of: the error disappeared because return-statement makes method to ignore all code below try-catch, specifically in my case, line redirectStrategy.sendRedirect(request, response, destination_addr_string) which seem to modify the already committed response that causes the error. The simpler solution in my case was just to remove the line and let client app to take care of the redirection.

React-Native: Application has not been registered error

I had the same problem. I was using Windows for creating a react native app for android and was having the same error. Here's what worked.

  • Navigate to the folder ANDROID in your root.
  • Create a file with name : local.properties
  • Open it in editor and write :

sdk.dir = C:\Users\ USERNAME \AppData\Local\Android\sdk

  • Replace USERNAME with the name of your machine.

Save and run the app normally. That worked for me.

How to obtain values of request variables using Python and Flask

Adding more to Jason's more generalized way of retrieving the POST data or GET data

from flask_restful import reqparse

def parse_arg_from_requests(arg, **kwargs):
    parse = reqparse.RequestParser()
    parse.add_argument(arg, **kwargs)
    args = parse.parse_args()
    return args[arg]

form_field_value = parse_arg_from_requests('FormFieldValue')

How can I run multiple npm scripts in parallel?

If you're using an UNIX-like environment, just use & as the separator:

"dev": "npm run start-watch & npm run wp-server"

Otherwise if you're interested on a cross-platform solution, you could use npm-run-all module:

"dev": "npm-run-all --parallel start-watch wp-server"

CURRENT_TIMESTAMP in milliseconds

In Mysql 5.7+ you can execute

select current_timestamp(6)

for more details

https://dev.mysql.com/doc/refman/5.7/en/fractional-seconds.html

Cross browser method to fit a child div to its parent's width

The solution is to simply not declare width: 100%.

The default is width: auto, which for block-level elements (such as div), will take the "full space" available anyway (different to how width: 100% does it).

See: http://jsfiddle.net/U7PhY/2/

Just in case it's not already clear from my answer: just don't set a width on the child div.

You might instead be interested in box-sizing: border-box.

How to change the opacity (alpha, transparency) of an element in a canvas element after it has been drawn?

Some simpler example code for using globalAlpha:

ctx.save();
ctx.globalAlpha = 0.4;
ctx.drawImage(img, x, y);
ctx.restore();

If you need img to be loaded:

var img = new Image();
img.onload = function() {
    ctx.save();
    ctx.globalAlpha = 0.4;
    ctx.drawImage(img, x, y);
    ctx.restore()
};
img.src = "http://...";

Notes:

  • Set the 'src' last, to guarantee that your onload handler is called on all platforms, even if the image is already in the cache.

  • Wrap changes to stuff like globalAlpha between a save and restore (in fact use them lots), to make sure you don't clobber settings from elsewhere, particularly when bits of drawing code are going to be called from events.

How to get single value of List<object>

You can access the fields by indexing the object array:

foreach (object[] item in selectedValues)
{
  idTextBox.Text = item[0];
  titleTextBox.Text = item[1];
  contentTextBox.Text = item[2];
}

That said, you'd be better off storing the fields in a small class of your own if the number of items is not dynamic:

public class MyObject
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }
}

Then you can do:

foreach (MyObject item in selectedValues)
{
  idTextBox.Text = item.Id;
  titleTextBox.Text = item.Title;
  contentTextBox.Text = item.Content;
}

How to print a string multiple times?

If you want to print something = '@' 2 times in a line, you can write this:

print(something * 2)

If you want to print 4 lines of something, you can use a for loop:

for i in range(4):
     print(something)

How to add/subtract time (hours, minutes, etc.) from a Pandas DataFrame.Index whos objects are of type datetime.time?

Liam's link looks great, but also check out pandas.Timedelta - looks like it plays nicely with NumPy's and Python's time deltas.

https://pandas.pydata.org/pandas-docs/stable/timedeltas.html

pd.date_range('2014-01-01', periods=10) + pd.Timedelta(days=1)

JUnit test for System.out.println()

Slightly off topic, but in case some people (like me, when I first found this thread) might be interested in capturing log output via SLF4J, commons-testing's JUnit @Rule might help:

public class FooTest {
    @Rule
    public final ExpectedLogs logs = new ExpectedLogs() {{
        captureFor(Foo.class, LogLevel.WARN);
    }};

    @Test
    public void barShouldLogWarning() {
        assertThat(logs.isEmpty(), is(true)); // Nothing captured yet.

        // Logic using the class you are capturing logs for:
        Foo foo = new Foo();
        assertThat(foo.bar(), is(not(nullValue())));

        // Assert content of the captured logs:
        assertThat(logs.isEmpty(), is(false));
        assertThat(logs.contains("Your warning message here"), is(true));
    }
}

Disclaimer:

  • I developed this library since I could not find any suitable solution for my own needs.
  • Only bindings for log4j, log4j2 and logback are available at the moment, but I am happy to add more.

JavaScript string and number conversion

Step (1) Concatenate "1", "2", "3" into "123"

 "1" + "2" + "3"

or

 ["1", "2", "3"].join("")

The join method concatenates the items of an array into a string, putting the specified delimiter between items. In this case, the "delimiter" is an empty string ("").


Step (2) Convert "123" into 123

 parseInt("123")

Prior to ECMAScript 5, it was necessary to pass the radix for base 10: parseInt("123", 10)


Step (3) Add 123 + 100 = 223

 123 + 100


Step (4) Covert 223 into "223"

 (223).toString() 


Put It All Togther

 (parseInt("1" + "2" + "3") + 100).toString()

or

 (parseInt(["1", "2", "3"].join("")) + 100).toString()

How to capture multiple repeated groups?

I think you need something like this....

b="HELLO,THERE,WORLD"
re.findall('[\w]+',b)

Which in Python3 will return

['HELLO', 'THERE', 'WORLD']

How to download Javadoc to read offline?

You can use something called Dash: Offline API Documentation for Mac. For Windows and Linux you have an alternative called Zeal.

Both of them are very similar. And you can get offline documentation for most of the APIs out there like Java, android, Angular, HTML5 etc .. almost everything.

I have also written a post on How to install Zeal on Ubuntu 14.04

How to fix "Your Ruby version is 2.3.0, but your Gemfile specified 2.2.5" while server starting

Two steps worked for me:

gem install bundler

bundle install --redownload # Forces a redownload of all gems on the gemfile, assigning them to the new bundler

download file using an ajax request

You actually don't need ajax at all for this. If you just set "download.php" as the href on the button, or, if it's not a link use:

window.location = 'download.php';

The browser should recognise the binary download and not load the actual page but just serve the file as a download.

.NET Excel Library that can read/write .xls files

You may consider 3rd party tool that called Excel Jetcell .NET component for read/write excel files:

C# sample

// Create New Excel Workbook
ExcelWorkbook Wbook = new ExcelWorkbook();
ExcelCellCollection Cells = Wbook.Worksheets.Add("Sheet1").Cells;

Cells["A1"].Value = "Excel writer example (C#)";
Cells["A1"].Style.Font.Bold = true;
Cells["B1"].Value = "=550 + 5";

// Write Excel XLS file
Wbook.WriteXLS("excel_net.xls");

VB.NET sample

' Create New Excel Workbook
Dim Wbook As ExcelWorkbook = New ExcelWorkbook()
Dim Cells As ExcelCellCollection = Wbook.Worksheets.Add("Sheet1").Cells

Cells("A1").Value = "Excel writer example (C#)"
Cells("A1").Style.Font.Bold = True
Cells("B1").Value = "=550 + 5"

' Write Excel XLS file
Wbook.WriteXLS("excel_net.xls")

what is the difference between json and xml

They are both data formats for hierarchical data, so while the syntax is quite different, the structure is similar. Example:

JSON:

{
  "persons": [
    {
      "name": "Ford Prefect",
      "gender": "male"
    },
    {
      "name": "Arthur Dent",
      "gender": "male"
    },
    {
      "name": "Tricia McMillan",
      "gender": "female"
    }
  ]
}

XML:

<persons>
  <person>
    <name>Ford Prefect</name>
    <gender>male</gender>
  </person>
  <person>
    <name>Arthur Dent</name>
    <gender>male</gender>
  </person>
  <person>
    <name>Tricia McMillan</name>
    <gender>female</gender>
  </person>
</persons>

The XML format is more advanced than shown by the example, though. You can for example add attributes to each element, and you can use namespaces to partition elements. There are also standards for defining the format of an XML file, the XPATH language to query XML data, and XSLT for transforming XML into presentation data.

The XML format has been around for some time, so there is a lot of software developed for it. The JSON format is quite new, so there is a lot less support for it.

While XML was developed as an independent data format, JSON was developed specifically for use with Javascript and AJAX, so the format is exactly the same as a Javascript literal object (that is, it's a subset of the Javascript code, as it for example can't contain expressions to determine values).

Process list on Linux via Python

from psutil import process_iter
from termcolor import colored

names = []
ids = []

x = 0
z = 0
k = 0
for proc in process_iter():
    name = proc.name()
    y = len(name)
    if y>x:
        x = y
    if y<x:
        k = y
    id = proc.pid
    names.insert(z, name)
    ids.insert(z, id)
    z += 1

print(colored("Process Name", 'yellow'), (x-k-5)*" ", colored("Process Id", 'magenta'))
for b in range(len(names)-1):
    z = x
    print(colored(names[b], 'cyan'),(x-len(names[b]))*" ",colored(ids[b], 'white'))

git rm - fatal: pathspec did not match any files

This chains work in my case:

  1. git rm -r WebApplication/packages

There was a confirmation git-dialog. You should choose "y" option.

  1. git commit -m "blabla"
  2. git push -f origin <ur_branch>

Delete duplicate records from a SQL table without a primary key

You could create a temporary table #tempemployee containing a select distinct of your employee table. Then delete from employee. Then insert into employee select from #tempemployee.

Like Josh said - even if you know the duplicates, deleting them will be impossile since you cannot actually refer to a specific record if it is an exact duplicate of another record.

SQL update from one Table to another based on a ID match

it works with postgresql

UPDATE application
SET omts_received_date = (
    SELECT
        date_created
    FROM
        application_history
    WHERE
        application.id = application_history.application_id
    AND application_history.application_status_id = 8
);

Centering text in a table in Twitter Bootstrap

I think who the best mix for html & Css for quick and clean mod is :

<table class="table text-center">
<thead>
        <tr>                    
        <th class="text-center">Uno</th>
        <th class="text-center">Due</th>
        <th class="text-center">Tre</th>
        <th class="text-center">Quattro</th>
    </tr>
</thead>
<tbody>
    <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
    </tr>
</tbody>
</table>

close the <table> init tag then copy where you want :) I hope it can be useful Have a good day w stackoverflow

p.s. Bootstrap v3.2.0

How to get min, seconds and milliseconds from datetime.now() in python?

Another similar solution:

>>> a=datetime.now()
>>> "%s:%s.%s" % (a.hour, a.minute, a.microsecond)
'14:28.971209'

Yes, I know I didn't get the string formatting perfect.

Php, wait 5 seconds before executing an action

i use this

    $i = 1;
    $last_time = $_SERVER['REQUEST_TIME'];
    while($i > 0){
        $total = $_SERVER['REQUEST_TIME'] - $last_time;
        if($total >= 2){
            // Code Here
            $i = -1;
        }
    }

you can use

function WaitForSec($sec){
    $i = 1;
    $last_time = $_SERVER['REQUEST_TIME'];
    while($i > 0){
        $total = $_SERVER['REQUEST_TIME'] - $last_time;
        if($total >= 2){
            return 1;
            $i = -1;
        }
    }
}

and run code =>

WaitForSec(your_sec);

Example :

WaitForSec(5);

OR you can use sleep

Example :

sleep(5);

Understanding the Rails Authenticity Token

Methods Where authenticity_token is required

authenticity_token is required in case of idempotent methods like post, put and delete, Because Idempotent methods are affecting to data.

Why It is Required

It is required to prevent from evil actions. authenticity_token is stored in session, whenever a form is created on web pages for creating or updating to resources then a authenticity token is stored in hidden field and it sent with form on server. Before executing action user sent authenticity_token is cross checked with authenticity_token stored in session. If authenticity_token is same then process is continue otherwise it does not perform actions.

When to Redis? When to MongoDB?

I just noticed that this question is quite old. Nevertheless, I consider the following aspects to be worth adding:

  • Use MongoDB if you don't know yet how you're going to query your data.

    MongoDB is suited for Hackathons, startups or every time you don't know how you'll query the data you inserted. MongoDB does not make any assumptions on your underlying schema. While MongoDB is schemaless and non-relational, this does not mean that there is no schema at all. It simply means that your schema needs to be defined in your app (e.g. using Mongoose). Besides that, MongoDB is great for prototyping or trying things out. Its performance is not that great and can't be compared to Redis.

  • Use Redis in order to speed up your existing application.

    Redis can be easily integrated as a LRU cache. It is very uncommon to use Redis as a standalone database system (some people prefer referring to it as a "key-value"-store). Websites like Craigslist use Redis next to their primary database. Antirez (developer of Redis) demonstrated using Lamernews that it is indeed possible to use Redis as a stand alone database system.

  • Redis does not make any assumptions based on your data.

    Redis provides a bunch of useful data structures (e.g. Sets, Hashes, Lists), but you have to explicitly define how you want to store you data. To put it in a nutshell, Redis and MongoDB can be used in order to achieve similar things. Redis is simply faster, but not suited for prototyping. That's one use case where you would typically prefer MongoDB. Besides that, Redis is really flexible. The underlying data structures it provides are the building blocks of high-performance DB systems.

When to use Redis?

  • Caching

    Caching using MongoDB simply doesn't make a lot of sense. It would be too slow.

  • If you have enough time to think about your DB design.

    You can't simply throw in your documents into Redis. You have to think of the way you in which you want to store and organize your data. One example are hashes in Redis. They are quite different from "traditional", nested objects, which means you'll have to rethink the way you store nested documents. One solution would be to store a reference inside the hash to another hash (something like key: [id of second hash]). Another idea would be to store it as JSON, which seems counter-intuitive to most people with a *SQL-background.

  • If you need really high performance.

    Beating the performance Redis provides is nearly impossible. Imagine you database being as fast as your cache. That's what it feels like using Redis as a real database.

  • If you don't care that much about scaling.

    Scaling Redis is not as hard as it used to be. For instance, you could use a kind of proxy server in order to distribute the data among multiple Redis instances. Master-slave replication is not that complicated, but distributing you keys among multiple Redis-instances needs to be done on the application site (e.g. using a hash-function, Modulo etc.). Scaling MongoDB by comparison is much simpler.

When to use MongoDB

  • Prototyping, Startups, Hackathons

    MongoDB is perfectly suited for rapid prototyping. Nevertheless, performance isn't that good. Also keep in mind that you'll most likely have to define some sort of schema in your application.

  • When you need to change your schema quickly.

    Because there is no schema! Altering tables in traditional, relational DBMS is painfully expensive and slow. MongoDB solves this problem by not making a lot of assumptions on your underlying data. Nevertheless, it tries to optimize as far as possible without requiring you to define a schema.

TL;DR - Use Redis if performance is important and you are willing to spend time optimizing and organizing your data. - Use MongoDB if you need to build a prototype without worrying too much about your DB.

Further reading:

How can I selectively escape percent (%) in Python strings?

You can't selectively escape %, as % always has a special meaning depending on the following character.

In the documentation of Python, at the bottem of the second table in that section, it states:

'%'        No argument is converted, results in a '%' character in the result.

Therefore you should use:

selectiveEscape = "Print percent %% in sentence and not %s" % (test, )

(please note the expicit change to tuple as argument to %)

Without knowing about the above, I would have done:

selectiveEscape = "Print percent %s in sentence and not %s" % ('%', test)

with the knowledge you obviously already had.

Access to file download dialog in Firefox

In addition you can add

      profile.setPreference("browser.download.panel.shown",false);

To remove the downloaded file list that gets shown by default and covers up part of the web page.

My total settings are:

        DesiredCapabilities dc = DesiredCapabilities.firefox();
        dc.merge(capabillities);
        FirefoxProfile profile = new FirefoxProfile();
        profile.setAcceptUntrustedCertificates(true);
        profile.setPreference("browser.download.folderList", 4);
        profile.setPreference("browser.download.dir", TestConstants.downloadDir.getAbsolutePath());
        profile.setPreference("browser.download.manager.alertOnEXEOpen", false);
        profile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/msword, application/csv, application/ris, text/csv, data:image/png, image/png, application/pdf, text/html, text/plain, application/zip, application/x-zip, application/x-zip-compressed, application/download, application/octet-stream");
        profile.setPreference("browser.download.manager.showWhenStarting", false);
        profile.setPreference("browser.download.manager.focusWhenStarting", false);
        profile.setPreference("browser.download.useDownloadDir", true);
        profile.setPreference("browser.helperApps.alwaysAsk.force", false);
        profile.setPreference("browser.download.manager.alertOnEXEOpen", false);
        profile.setPreference("browser.download.manager.closeWhenDone", true);
        profile.setPreference("browser.download.manager.showAlertOnComplete", false);
        profile.setPreference("browser.download.manager.useWindow", false);
        profile.setPreference("browser.download.panel.shown",false);
        dc.setCapability(FirefoxDriver.PROFILE, profile);
        this.driver = new FirefoxDriver(dc);

Java socket API: How to tell if a connection has been closed?

Thats how I handle it

 while(true) {
        if((receiveMessage = receiveRead.readLine()) != null ) {  

        System.out.println("first message same :"+receiveMessage);
        System.out.println(receiveMessage);      

        }
        else if(receiveRead.readLine()==null)
        {

        System.out.println("Client has disconected: "+sock.isClosed()); 
        System.exit(1);
         }    } 

if the result.code == null

Posting JSON Data to ASP.NET MVC

You can try these. 1. stringify your JSON Object before calling the server action via ajax 2. deserialize the string in the action then use the data as a dictionary.

Javascript sample below (sending the JSON Object

$.ajax(
   {
       type: 'POST',
       url: 'TheAction',
       data: { 'data': JSON.stringify(theJSONObject) 
   }
})

Action (C#) sample below

[HttpPost]
public JsonResult TheAction(string data) {

       string _jsonObject = data.Replace(@"\", string.Empty);
       var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();           
        Dictionary<string, string> jsonObject = serializer.Deserialize<Dictionary<string, string>>(_jsonObject);


        return Json(new object{status = true});

    }

How to send POST in angularjs with multiple params?

It depends on what is your backend technology. If your backend technology accepting JSON data. data:{id:1,name:'name',...}

otherwise, you need to convert your data best way to do that creating Factory to convert your data to id=1&name=name&...

then on $http define content-type. you can find full article @https://www.bennadel.com/blog/2615-posting-form-data-with-http-in-angularjs.htm

$http({
    method: 'POST',
    url: url,
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    transformRequest: function(obj) {
        var str = [];
        for(var p in obj)
        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
        return str.join("&");
    },
    data: {username: $scope.userName, password: $scope.password}
}).success(function () {});

ref:How do I POST urlencoded form data with $http in AngularJS?

!important about encodeURIComponent(obj[p]) will transfer object the way implicit. like a date value will be converted to a string like=>'Fri Feb 03 2017 09:56:57 GMT-0700 (US Mountain Standard Time)' which I don't have any clue how you can parse it at least in back-end C# code. (I mean code that doesn't need more than 2-line) you can use (angular.isDate, value.toJSON) in date case to convert it to more meaningful format for your back-end code.

I'm using this function to comunicating to my backend webservices...

 this.SendUpdateRequest = (url, data) => {
            return $http({
                method: 'POST',
                url: url,
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                transformRequest: function (obj) { return jsontoqs(obj); },
                data: { jsonstring: JSON.stringify(data) }
            });
        }; 

and bellow code to use it...

webrequest.SendUpdateRequest(
  '/Services/ServeicNameWebService.asmx/Update',
  $scope.updatedto)
  .then(
      (res) => { /*/TODO/*/ },
      (err) => { /*/TODO/*/ }
);

in backend C# I'm using newtonsoft for deserializing the data.

How to encode text to base64 in python

It turns out that this is important enough to get it's own module...

import base64
base64.b64encode(b'your name')  # b'eW91ciBuYW1l'
base64.b64encode('your name'.encode('ascii'))  # b'eW91ciBuYW1l'

how to get 2 digits after decimal point in tsql?

Try this one -

DECLARE @i FLOAT = 6.677756

SELECT 
      ROUND(@i, 2)
    , FORMAT(@i, 'N2')
    , CAST(@i AS DECIMAL(18,2))
    , SUBSTRING(PARSENAME(CAST(@i AS VARCHAR(10)), 1), PATINDEX('%.%', CAST(@i AS VARCHAR(10))) - 1, 2)
    , FLOOR((@i - FLOOR(@i)) * 100)

Output:

----------------------
6,68
6.68
6.68
67
67

Dynamic type languages versus static type languages

Well, both are very, very very very misunderstood and also two completely different things. that aren't mutually exclusive.

Static types are a restriction of the grammar of the language. Statically typed languages strictly could be said to not be context free. The simple truth is that it becomes inconvenient to express a language sanely in context free grammars that doesn't treat all its data simply as bit vectors. Static type systems are part of the grammar of the language if any, they simply restrict it more than a context free grammar could, grammatical checks thus happen in two passes over the source really. Static types correspond to the mathematical notion of type theory, type theory in mathematics simply restricts the legality of some expressions. Like, I can't say 3 + [4,7] in maths, this is because of the type theory of it.

Static types are thus not a way to 'prevent errors' from a theoretical perspective, they are a limitation of the grammar. Indeed, provided that +, 3 and intervals have the usual set theoretical definitions, if we remove the type system 3 + [4,7]has a pretty well defined result that's a set. 'runtime type errors' theoretically do not exist, the type system's practical use is to prevent operations that to human beings would make no sense. Operations are still just the shifting and manipulation of bits of course.

The catch to this is that a type system can't decide if such operations are going to occur or not if it would be allowed to run. As in, exactly partition the set of all possible programs in those that are going to have a 'type error', and those that aren't. It can do only two things:

1: prove that type errors are going to occur in a program
2: prove that they aren't going to occur in a program

This might seem like I'm contradicting myself. But what a C or Java type checker does is it rejects a program as 'ungrammatical', or as it calls it 'type error' if it can't succeed at 2. It can't prove they aren't going to occur, that doesn't mean that they aren't going to occur, it just means it can't prove it. It might very well be that a program which will not have a type error is rejected simply because it can't be proven by the compiler. A simple example being if(1) a = 3; else a = "string";, surely since it's always true, the else-branch will never be executed in the program, and no type error shall occur. But it can't prove these cases in a general way, so it's rejected. This is the major weakness of a lot of statically typed languages, in protecting you against yourself, you're necessarily also protected in cases you don't need it.

But, contrary to popular believe, there are also statically typed languages that work by principle 1. They simply reject all programs of which they can prove it's going to cause a type error, and pass all programs of which they can't. So it's possible they allow programs which have type errors in them, a good example being Typed Racket, it's hybrid between dynamic and static typing. And some would argue that you get the best of both worlds in this system.

Another advantage of static typing is that types are known at compile time, and thus the compiler can use this. If we in Java do "string" + "string" or 3 + 3, both + tokens in text in the end represent a completely different operation and datum, the compiler knows which to choose from the types alone.

Now, I'm going to make a very controversial statement here but bear with me: 'dynamic typing' does not exist.

Sounds very controversial, but it's true, dynamically typed languages are from a theoretical perspective untyped. They are just statically typed languages with only one type. Or simply put, they are languages that are indeed grammatically generated by a context free grammar in practice.

Why don't they have types? Because every operation is defined and allowed on every operant, what's a 'runtime type error' exactly? It's from a theoretical example purely a side-effect. If doing print("string") which prints a string is an operation, then so is length(3), the former has the side effect of writing string to the standard output, the latter simply error: function 'length' expects array as argument., that's it. There is from a theoretical perspective no such thing as a dynamically typed language. They are untyped

All right, the obvious advantage of 'dynamically typed' language is expressive power, a type system is nothing but a limitation of expressive power. And in general, languages with a type system indeed would have a defined result for all those operations that are not allowed if the type system was just ignored, the results would just not make sense to humans. Many languages lose their Turing completeness after applying a type system.

The obvious disadvantage is the fact that operations can occur which would produce results which are nonsensical to humans. To guard against this, dynamically typed languages typically redefine those operations, rather than producing that nonsensical result they redefine it to having the side effect of writing out an error, and possibly halting the program altogether. This is not an 'error' at all, in fact, the language specification usually implies this, this is as much behaviour of the language as printing a string from a theoretical perspective. Type systems thus force the programmer to reason about the flow of the code to make sure that this doesn't happen. Or indeed, reason so that it does happen can also be handy in some points for debugging, showing that it's not an 'error' at all but a well defined property of the language. In effect, the single remnant of 'dynamic typing' that most languages have is guarding against a division by zero. This is what dynamic typing is, there are no types, there are no more types than that zero is a different type than all the other numbers. What people call a 'type' is just another property of a datum, like the length of an array, or the first character of a string. And many dynamically typed languages also allow you to write out things like "error: the first character of this string should be a 'z'".

Another thing is that dynamically typed languages have the type available at runtime and usually can check it and deal with it and decide from it. Of course, in theory it's no different than accessing the first char of an array and seeing what it is. In fact, you can make your own dynamic C, just use only one type like long long int and use the first 8 bits of it to store your 'type' in and write functions accordingly that check for it and perform float or integer addition. You have a statically typed language with one type, or a dynamic language.

In practise this all shows, statically typed languages are generally used in the context of writing commercial software, whereas dynamically typed languages tend to be used in the context of solving some problems and automating some tasks. Writing code in statically typed languages simply takes long and is cumbersome because you can't do things which you know are going to turn out okay but the type system still protects you against yourself for errors you don't make. Many coders don't even realize that they do this because it's in their system but when you code in static languages, you often work around the fact that the type system won't let you do things that can't go wrong, because it can't prove it won't go wrong.

As I noted, 'statically typed' in general means case 2, guilty until proven innocent. But some languages, which do not derive their type system from type theory at all use rule 1: Innocent until proven guilty, which might be the ideal hybrid. So, maybe Typed Racket is for you.

Also, well, for a more absurd and extreme example, I'm currently implementing a language where 'types' are truly the first character of an array, they are data, data of the 'type', 'type', which is itself a type and datum, the only datum which has itself as a type. Types are not finite or bounded statically but new types may be generated based on runtime information.

How do I move a file (or folder) from one folder to another in TortoiseSVN?

In Windows Explorer, with the right-mouse button, click and drag the file from where it is to where you want it. Upon releasing the right-mouse button, you will see a context menu with options such as "SVN Move versioned file here".

http://tortoisesvn.net/most-forgotten-feature

jQuery table sort

I love this accepted answer, however, rarely do you get requirements to sort html and not have to add icons indicating the sorting direction. I took the accept answer's usage example and fixed that quickly by simply adding bootstrap to my project, and adding the following code:

<div></div>

inside each <th> so that you have a place to set the icon.

setIcon(this, inverse);

from the accepted answer's Usage, below the line:

th.click(function () {

and by adding the setIcon method:

function setIcon(element, inverse) {

        var iconSpan = $(element).find('div');

        if (inverse == false) {
            $(iconSpan).removeClass();
            $(iconSpan).addClass('icon-white icon-arrow-up');
        } else {
            $(iconSpan).removeClass();
            $(iconSpan).addClass('icon-white icon-arrow-down');
        }
        $(element).siblings().find('div').removeClass();
    }

Here is a demo. --You need to either run the demo in Firefox or IE, or disable Chrome's MIME-type checking for the demo to work. It depends on the sortElements Plugin, linked by the accepted answer, as an external resource. Just a heads up!

JavaScript sleep/wait before continuing

JS does not have a sleep function, it has setTimeout() or setInterval() functions.

If you can move the code that you need to run after the pause into the setTimeout() callback, you can do something like this:

//code before the pause
setTimeout(function(){
    //do what you need here
}, 2000);

see example here : http://jsfiddle.net/9LZQp/

This won't halt the execution of your script, but due to the fact that setTimeout() is an asynchronous function, this code

console.log("HELLO");
setTimeout(function(){
    console.log("THIS IS");
}, 2000);
console.log("DOG");

will print this in the console:

HELLO
DOG
THIS IS

(note that DOG is printed before THIS IS)


You can use the following code to simulate a sleep for short periods of time:

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}

now, if you want to sleep for 1 second, just use:

sleep(1000);

example: http://jsfiddle.net/HrJku/1/

please note that this code will keep your script busy for n milliseconds. This will not only stop execution of Javascript on your page, but depending on the browser implementation, may possibly make the page completely unresponsive, and possibly make the entire browser unresponsive. In other words this is almost always the wrong thing to do.

How do you get a list of the names of all files present in a directory in Node.js?

If many of the above options seem too complex or not what you are looking for here is another approach using node-dir - https://github.com/fshost/node-dir

npm install node-dir

Here is a somple function to list all .xml files searching in subdirectories

import * as nDir from 'node-dir' ;

listXMLs(rootFolderPath) {
    let xmlFiles ;

    nDir.files(rootFolderPath, function(err, items) {
        xmlFiles = items.filter(i => {
            return path.extname(i) === '.xml' ;
        }) ;
        console.log(xmlFiles) ;       
    });
}

What is a elegant way in Ruby to tell if a variable is a Hash or an Array?

First of all, the best answer for the literal question is

Hash === @some_var

But the question really should have been answered by showing how to do duck-typing here. That depends a bit on what kind of duck you need.

@some_var.respond_to?(:each_pair)

or

@some_var.respond_to?(:has_key?)

or even

@some_var.respond_to?(:to_hash)

may be right depending on the application.

Injecting Mockito mocks into a Spring bean

I use a combination of the approach used in answer by Markus T and a simple helper implementation of ImportBeanDefinitionRegistrar that looks for a custom annotation (@MockedBeans) in which one can specify which classes are to be mocked. I believe that this approach results in a concise unit test with some of the boilerplate code related to mocking removed.

Here's how a sample unit test looks with that approach:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader=AnnotationConfigContextLoader.class)
public class ExampleServiceIntegrationTest {

    //our service under test, with mocked dependencies injected
    @Autowired
    ExampleService exampleService;

    //we can autowire mocked beans if we need to used them in tests
    @Autowired
    DependencyBeanA dependencyBeanA;

    @Test
    public void testSomeMethod() {
        ...
        exampleService.someMethod();
        ...
        verify(dependencyBeanA, times(1)).someDependencyMethod();
    }

    /**
     * Inner class configuration object for this test. Spring will read it thanks to
     * @ContextConfiguration(loader=AnnotationConfigContextLoader.class) annotation on the test class.
     */
    @Configuration
    @Import(TestAppConfig.class) //TestAppConfig may contain some common integration testing configuration
    @MockedBeans({DependencyBeanA.class, DependencyBeanB.class, AnotherDependency.class}) //Beans to be mocked
    static class ContextConfiguration {

        @Bean
        public ExampleService exampleService() {
            return new ExampleService(); //our service under test
        }
    }
}

To make this happen you need to define two simple helper classes - custom annotation (@MockedBeans) and a custom ImportBeanDefinitionRegistrar implementation. @MockedBeans annotation definition needs to be annotated with @Import(CustomImportBeanDefinitionRegistrar.class) and the ImportBeanDefinitionRgistrar needs to add mocked beans definitions to the configuration in it's registerBeanDefinitions method.

If you like the approach you can find sample implementations on my blogpost.

How to express a One-To-Many relationship in Django

To be more clear - there's no OneToMany in Django, only ManyToOne - which is Foreignkey described above. You can describe OneToMany relation using Foreignkey but that is very inexpressively.

A good article about it: https://amir.rachum.com/blog/2013/06/15/a-case-for-a-onetomany-relationship-in-django/

How can I fix the Microsoft Visual Studio error: "package did not load correctly"?

For Visual Studio 2019: I have done the following things to solve the problem

Backup the following Folder. After Taking backup and Delete This Folder C:\Users\munirul2537\AppData\Roaming\Microsoft\VisualStudio\16.0_add0ca51

Go to the installation panel of visual studio and do the following things

1.Go to install 2.Modify 3.Go to "Installation location" tab 4. Check "keep download cache after the installation" 5. Modify

Unzipping files

I wrote an unzipper in Javascript. It works.

It relies on Andy G.P. Na's binary file reader and some RFC1951 inflate logic from notmasteryet. I added the ZipFile class.

working example:
http://cheeso.members.winisp.net/Unzip-Example.htm (dead link)

The source:
http://cheeso.members.winisp.net/srcview.aspx?dir=js-unzip (dead link)

NB: the links are dead; I'll find a new host soon.

Included in the source is a ZipFile.htm demonstration page, and 3 distinct scripts, one for the zipfile class, one for the inflate class, and one for a binary file reader class. The demo also depends on jQuery and jQuery UI. If you just download the js-zip.zip file, all of the necessary source is there.


Here's what the application code looks like in Javascript:

// In my demo, this gets attached to a click event.
// it instantiates a ZipFile, and provides a callback that is
// invoked when the zip is read.  This can take a few seconds on a
// large zip file, so it's asynchronous. 
var readFile = function(){
    $("#status").html("<br/>");
    var url= $("#urlToLoad").val();
    var doneReading = function(zip){
        extractEntries(zip);
    };

    var zipFile = new ZipFile(url, doneReading);
};


// this function extracts the entries from an instantiated zip
function extractEntries(zip){
    $('#report').accordion('destroy');

    // clear
    $("#report").html('');

    var extractCb = function(id) {
        // this callback is invoked with the entry name, and entry text
        // in my demo, the text is just injected into an accordion panel.
        return (function(entryName, entryText){
            var content = entryText.replace(new RegExp( "\\n", "g" ), "<br/>");
            $("#"+id).html(content);
            $("#status").append("extract cb, entry(" + entryName + ")  id(" + id + ")<br/>");
            $('#report').accordion('destroy');
            $('#report').accordion({collapsible:true, active:false});
        });
    }

    // for each entry in the zip, extract it. 
    for (var i=0; i<zip.entries.length;  i++) {
        var entry = zip.entries[i];

        var entryInfo = "<h4><a>" + entry.name + "</a></h4>\n<div>";

        // contrive an id for the entry, make it unique
        var randomId = "id-"+ Math.floor((Math.random() * 1000000000));

        entryInfo += "<span class='inputDiv'><h4>Content:</h4><span id='" + randomId +
            "'></span></span></div>\n";

        // insert the info for one entry as the last child within the report div
        $("#report").append(entryInfo);

        // extract asynchronously
        entry.extract(extractCb(randomId));
    }
}

The demo works in a couple of steps: The readFile fn is triggered by a click, and instantiates a ZipFile object, which reads the zip file. There's an asynchronous callback for when the read completes (usually happens in less than a second for reasonably sized zips) - in this demo the callback is held in the doneReading local variable, which simply calls extractEntries, which just blindly unzips all the content of the provided zip file. In a real app you would probably choose some of the entries to extract (allow the user to select, or choose one or more entries programmatically, etc).

The extractEntries fn iterates over all entries, and calls extract() on each one, passing a callback. Decompression of an entry takes time, maybe 1s or more for each entry in the zipfile, which means asynchrony is appropriate. The extract callback simply adds the extracted content to an jQuery accordion on the page. If the content is binary, then it gets formatted as such (not shown).


It works, but I think that the utility is somewhat limited.

For one thing: It's very slow. Takes ~4 seconds to unzip the 140k AppNote.txt file from PKWare. The same uncompress can be done in less than .5s in a .NET program. EDIT: The Javascript ZipFile unpacks considerably faster than this now, in IE9 and in Chrome. It is still slower than a compiled program, but it is plenty fast for normal browser usage.

For another: it does not do streaming. It basically slurps in the entire contents of the zipfile into memory. In a "real" programming environment you could read in only the metadata of a zip file (say, 64 bytes per entry) and then read and decompress the other data as desired. There's no way to do IO like that in javascript, as far as I know, therefore the only option is to read the entire zip into memory and do random access in it. This means it will place unreasonable demands on system memory for large zip files. Not so much a problem for a smaller zip file.

Also: It doesn't handle the "general case" zip file - there are lots of zip options that I didn't bother to implement in the unzipper - like ZIP encryption, WinZip encryption, zip64, UTF-8 encoded filenames, and so on. (EDIT - it handles UTF-8 encoded filenames now). The ZipFile class handles the basics, though. Some of these things would not be hard to implement. I have an AES encryption class in Javascript; that could be integrated to support encryption. Supporting Zip64 would probably useless for most users of Javascript, as it is intended to support >4gb zipfiles - don't need to extract those in a browser.

I also did not test the case for unzipping binary content. Right now it unzips text. If you have a zipped binary file, you'd need to edit the ZipFile class to handle it properly. I didn't figure out how to do that cleanly. It does binary files now, too.


EDIT - I updated the JS unzip library and demo. It now does binary files, in addition to text. I've made it more resilient and more general - you can now specify the encoding to use when reading text files. Also the demo is expanded - it shows unzipping an XLSX file in the browser, among other things.

So, while I think it is of limited utility and interest, it works. I guess it would work in Node.js.

Creating an R dataframe row-by-row

This is a silly example of how to use do.call(rbind,) on the output of Map() [which is similar to lapply()]

> DF <- do.call(rbind,Map(function(x) data.frame(a=x,b=x+1),x=1:3))
> DF
  x y
1 1 2
2 2 3
3 3 4
> class(DF)
[1] "data.frame"

I use this construct quite often.

Float a div above page content

Yes, the higher the z-index, the better. It will position your content element on top of every other element on the page. Say you have z-index to some elements on your page. Look for the highest and then give a higher z-index to your popup element. This way it will flow even over the other elements with z-index. If you don't have a z-index in any element on your page, you should give like z-index:2; or something higher.

SSL error : routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

Experienced this myself when using requests:

This is extremely insecure; use only as a last resort! (See rdlowrey's comment.)

requests.get('https://github.com', verify=True)

Making that verify=False did the trick for me.

How do you add a scroll bar to a div?

Css class to have a nice Div with scroll

.DivToScroll{   
    background-color: #F5F5F5;
    border: 1px solid #DDDDDD;
    border-radius: 4px 0 4px 0;
    color: #3B3C3E;
    font-size: 12px;
    font-weight: bold;
    left: -1px;
    padding: 10px 7px 5px;
}

.DivWithScroll{
    height:120px;
    overflow:scroll;
    overflow-x:hidden;
}

How to get datas from List<Object> (Java)?

For starters you aren't iterating over the result list properly, you are not using the index i at all. Try something like this:

List<Object> list = getHouseInfo();
for (int i=0; i<list.size; i++){
   System.out.println("Element "+i+list.get(i));
}

It looks like the query reutrns a List of Arrays of Objects, because Arrays are not proper objects that override toString you need to do a cast first and then use Arrays.toString().

 List<Object> list = getHouseInfo();
for (int i=0; i<list.size; i++){
   Object[] row = (Object[]) list.get(i);
   System.out.println("Element "+i+Arrays.toString(row));
}

Android emulator: How to monitor network traffic?

You can start the emulator with the command -avd Adfmf -http-proxy http://SYSTEM_IP:PORT. I used HTTP Analyzer, but it should work for anything else. More details can be found here: http://stick2code.blogspot.in/2014/04/intercept-http-requests-sent-from-app.html

The most efficient way to implement an integer based power function pow(int, int)

In case you know the exponent (and it is an integer) at compile-time, you can use templates to unroll the loop. This can be made more efficient, but I wanted to demonstrate the basic principle here:

#include <iostream>

template<unsigned long N>
unsigned long inline exp_unroll(unsigned base) {
    return base * exp_unroll<N-1>(base);
}

We terminate the recursion using a template specialization:

template<>
unsigned long inline exp_unroll<1>(unsigned base) {
    return base;
}

The exponent needs to be known at runtime,

int main(int argc, char * argv[]) {
    std::cout << argv[1] <<"**5= " << exp_unroll<5>(atoi(argv[1])) << ;std::endl;
}

How to check if a string is null in python

Try this:

if cookie and not cookie.isspace():
    # the string is non-empty
else:
    # the string is empty

The above takes in consideration the cases where the string is None or a sequence of white spaces.

MongoDB query multiple collections at once

As mentioned before in MongoDB you can't JOIN between collections.

For your example a solution could be:

var myCursor = db.users.find({admin:1});
var user_id = myCursor.hasNext() ? myCursor.next() : null;
db.posts.find({owner_id : user_id._id});

See the reference manual - cursors section: http://es.docs.mongodb.org/manual/core/cursors/

Other solution would be to embed users in posts collection, but I think for most web applications users collection need to be independent for security reasons. Users collection might have Roles, permissons, etc.

posts
{
 "content":"Some content",
 "user":{"_id":"12345", "admin":1},
 "via":"facebook"
},
{
 "content":"Some other content",
 "user":{"_id":"123456789", "admin":0},
 "via":"facebook"
}

and then:

db.posts.find({user.admin: 1 });

Conditional HTML Attributes using Razor MVC3

Note you can do something like this(at least in MVC3):

<td align="left" @(isOddRow ? "class=TopBorder" : "style=border:0px") >

What I believed was razor adding quotes was actually the browser. As Rism pointed out when testing with MVC 4(I haven't tested with MVC 3 but I assume behavior hasn't changed), this actually produces class=TopBorder but browsers are able to parse this fine. The HTML parsers are somewhat forgiving on missing attribute quotes, but this can break if you have spaces or certain characters.

<td align="left" class="TopBorder" >

OR

<td align="left" style="border:0px" >

What goes wrong with providing your own quotes

If you try to use some of the usual C# conventions for nested quotes, you'll end up with more quotes than you bargained for because Razor is trying to safely escape them. For example:

<button type="button" @(true ? "style=\"border:0px\"" : string.Empty)>

This should evaluate to <button type="button" style="border:0px"> but Razor escapes all output from C# and thus produces:

style=&quot;border:0px&quot;

You will only see this if you view the response over the network. If you use an HTML inspector, often you are actually seeing the DOM, not the raw HTML. Browsers parse HTML into the DOM, and the after-parsing DOM representation already has some niceties applied. In this case the Browser sees there aren't quotes around the attribute value, adds them:

style="&quot;border:0px&quot;"

But in the DOM inspector HTML character codes display properly so you actually see:

style=""border:0px""

In Chrome, if you right-click and select Edit HTML, it switch back so you can see those nasty HTML character codes, making it clear you have real outer quotes, and HTML encoded inner quotes.

So the problem with trying to do the quoting yourself is Razor escapes these.

If you want complete control of quotes

Use Html.Raw to prevent quote escaping:

<td @Html.Raw( someBoolean ? "rel='tooltip' data-container='.drillDown a'" : "" )>

Renders as:

<td rel='tooltip' title='Drilldown' data-container='.drillDown a'>

The above is perfectly safe because I'm not outputting any HTML from a variable. The only variable involved is the ternary condition. However, beware that this last technique might expose you to certain security problems if building strings from user supplied data. E.g. if you built an attribute from data fields that originated from user supplied data, use of Html.Raw means that string could contain a premature ending of the attribute and tag, then begin a script tag that does something on behalf of the currently logged in user(possibly different than the logged in user). Maybe you have a page with a list of all users pictures and you are setting a tooltip to be the username of each person, and one users named himself '/><script>$.post('changepassword.php?password=123')</script> and now any other user who views this page has their password instantly changed to a password that the malicious user knows.

What is the use of adding a null key or value to a HashMap in Java?

Here's my only-somewhat-contrived example of a case where the null key can be useful:

public class Timer {
    private static final Logger LOG = Logger.getLogger(Timer.class);
    private static final Map<String, Long> START_TIMES = new HashMap<String, Long>();

    public static synchronized void start() {
        long now = System.currentTimeMillis();
        if (START_TIMES.containsKey(null)) {
            LOG.warn("Anonymous timer was started twice without being stopped; previous timer has run for " + (now - START_TIMES.get(null).longValue()) +"ms"); 
        }
        START_TIMES.put(null, now);
    }

    public static synchronized long stop() {
        if (! START_TIMES.containsKey(null)) {
            return 0;
        }

        return printTimer("Anonymous", START_TIMES.remove(null), System.currentTimeMillis());
    }

    public static synchronized void start(String name) {
        long now = System.currentTimeMillis();
        if (START_TIMES.containsKey(name)) {
            LOG.warn(name + " timer was started twice without being stopped; previous timer has run for " + (now - START_TIMES.get(name).longValue()) +"ms"); 
        }
        START_TIMES.put(name, now);
    }

    public static synchronized long stop(String name) {
        if (! START_TIMES.containsKey(name)) {
            return 0;
        }

        return printTimer(name, START_TIMES.remove(name), System.currentTimeMillis());
    }

    private static long printTimer(String name, long start, long end) {
        LOG.info(name + " timer ran for " + (end - start) + "ms");
        return end - start;
    }
}

Accessing elements by type in javascript

The sizzle selector engine (what powers JQuery) is perfectly geared up for this:

var elements = $('input[type=text]');

Or

var elements = $('input:text');

Regular expression search replace in Sublime Text 2

By the way, in the question above:

For:

Hello, my name is bob

Find part:

my name is (\w)+

With replace part:

my name used to be \1

Would return:

Hello, my name used to be b

Change find part to:

my name is (\w+)

And replace will be what you expect:

Hello, my name used to be bob

While (\w)+ will match "bob", it is not the grouping you want for replacement.

How to do case insensitive string comparison?

This is an improved version of this answer.

String.equal = function (s1, s2, ignoreCase, useLocale) {
    if (s1 == null || s2 == null)
        return false;

    if (!ignoreCase) {
        if (s1.length !== s2.length)
            return false;

        return s1 === s2;
    }

    if (useLocale) {
        if (useLocale.length)
            return s1.toLocaleLowerCase(useLocale) === s2.toLocaleLowerCase(useLocale)
        else
            return s1.toLocaleLowerCase() === s2.toLocaleLowerCase()
    }
    else {
        if (s1.length !== s2.length)
            return false;

        return s1.toLowerCase() === s2.toLowerCase();
    }
}



Usages & tests:

_x000D_
_x000D_
String.equal = function (s1, s2, ignoreCase, useLocale) {_x000D_
    if (s1 == null || s2 == null)_x000D_
        return false;_x000D_
_x000D_
    if (!ignoreCase) {_x000D_
        if (s1.length !== s2.length)_x000D_
            return false;_x000D_
_x000D_
        return s1 === s2;_x000D_
    }_x000D_
_x000D_
    if (useLocale) {_x000D_
        if (useLocale.length)_x000D_
            return s1.toLocaleLowerCase(useLocale) === s2.toLocaleLowerCase(useLocale)_x000D_
        else_x000D_
            return s1.toLocaleLowerCase() === s2.toLocaleLowerCase()_x000D_
    }_x000D_
    else {_x000D_
        if (s1.length !== s2.length)_x000D_
            return false;_x000D_
_x000D_
        return s1.toLowerCase() === s2.toLowerCase();_x000D_
    }_x000D_
}_x000D_
_x000D_
// If you don't mind extending the prototype._x000D_
String.prototype.equal = function(string2, ignoreCase, useLocale) {_x000D_
  return String.equal(this.valueOf(), string2, ignoreCase, useLocale);_x000D_
}_x000D_
_x000D_
// ------------------ TESTS ----------------------_x000D_
console.log("Tests...");_x000D_
_x000D_
console.log('Case sensitive 1');_x000D_
var result = "Abc123".equal("Abc123");_x000D_
console.assert(result === true);_x000D_
_x000D_
console.log('Case sensitive 2');_x000D_
result = "aBC123".equal("Abc123");_x000D_
console.assert(result === false);_x000D_
_x000D_
console.log('Ignore case');_x000D_
result = "AbC123".equal("aBc123", true);_x000D_
console.assert(result === true);_x000D_
_x000D_
console.log('Ignore case + Current locale');_x000D_
result = "AbC123".equal("aBc123", true);_x000D_
console.assert(result === true);_x000D_
_x000D_
console.log('Turkish test 1 (ignore case, en-US)');_x000D_
result = "IiiI".equal("iiII", true, "en-US");_x000D_
console.assert(result === false);_x000D_
_x000D_
console.log('Turkish test 2 (ignore case, tr-TR)');_x000D_
result = "IiiI".equal("iiII", true, "tr-TR");_x000D_
console.assert(result === true);_x000D_
_x000D_
console.log('Turkish test 3 (case sensitive, tr-TR)');_x000D_
result = "IiiI".equal("iiII", false, "tr-TR");_x000D_
console.assert(result === false);_x000D_
_x000D_
console.log('null-test-1');_x000D_
result = "AAA".equal(null);_x000D_
console.assert(result === false);_x000D_
_x000D_
console.log('null-test-2');_x000D_
result = String.equal(null, "BBB");_x000D_
console.assert(result === false);_x000D_
_x000D_
console.log('null-test-3');_x000D_
result = String.equal(null, null);_x000D_
console.assert(result === false);
_x000D_
_x000D_
_x000D_

WPF Button with Image

You can create a custom control that inherits from the Button class. This code will be more reusable, please look at the following blog post for more details: WPF - create custom button with image (ImageButton)

Using this control:

<local:ImageButton Width="200" Height="50" Content="Click Me!"
    ImageSource="ok.png" ImageLocation="Left" ImageWidth="20" ImageHeight="25" />

ImageButton.cs file:

public class ImageButton : Button
{
   static ImageButton()
   {
       DefaultStyleKeyProperty.OverrideMetadata(typeof(ImageButton), new FrameworkPropertyMetadata(typeof(ImageButton)));
   }

   public ImageButton()
   {
       this.SetCurrentValue(ImageButton.ImageLocationProperty, WpfImageButton.ImageLocation.Left);
   }

   public int ImageWidth
   {
       get { return (int)GetValue(ImageWidthProperty); }
       set { SetValue(ImageWidthProperty, value); }
   }

   public static readonly DependencyProperty ImageWidthProperty =
       DependencyProperty.Register("ImageWidth", typeof(int), typeof(ImageButton), new PropertyMetadata(30));

   public int ImageHeight
   {
       get { return (int)GetValue(ImageHeightProperty); }
       set { SetValue(ImageHeightProperty, value); }
   }

   public static readonly DependencyProperty ImageHeightProperty =
       DependencyProperty.Register("ImageHeight", typeof(int), typeof(ImageButton), new PropertyMetadata(30));

   public ImageLocation? ImageLocation
   {
       get { return (ImageLocation)GetValue(ImageLocationProperty); }
       set { SetValue(ImageLocationProperty, value); }
   }

   public static readonly DependencyProperty ImageLocationProperty =
       DependencyProperty.Register("ImageLocation", typeof(ImageLocation?), typeof(ImageButton), new PropertyMetadata(null, PropertyChangedCallback));

   private static void PropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
   {
       var imageButton = (ImageButton)d;
       var newLocation = (ImageLocation?) e.NewValue ?? WpfImageButton.ImageLocation.Left;

       switch (newLocation)
       {
           case WpfImageButton.ImageLocation.Left:
               imageButton.SetCurrentValue(ImageButton.RowIndexProperty, 1);
               imageButton.SetCurrentValue(ImageButton.ColumnIndexProperty, 0);
               break;
           case WpfImageButton.ImageLocation.Top:
               imageButton.SetCurrentValue(ImageButton.RowIndexProperty, 0);
               imageButton.SetCurrentValue(ImageButton.ColumnIndexProperty, 1);
               break;
           case WpfImageButton.ImageLocation.Right:
               imageButton.SetCurrentValue(ImageButton.RowIndexProperty, 1);
               imageButton.SetCurrentValue(ImageButton.ColumnIndexProperty, 2);
               break;
           case WpfImageButton.ImageLocation.Bottom:
               imageButton.SetCurrentValue(ImageButton.RowIndexProperty, 2);
               imageButton.SetCurrentValue(ImageButton.ColumnIndexProperty, 1);
               break;
           case WpfImageButton.ImageLocation.Center:
               imageButton.SetCurrentValue(ImageButton.RowIndexProperty, 1);
               imageButton.SetCurrentValue(ImageButton.ColumnIndexProperty, 1);
               break;
           default:
               throw new ArgumentOutOfRangeException();
       }
   }

   public ImageSource ImageSource
   {
       get { return (ImageSource)GetValue(ImageSourceProperty); }
       set { SetValue(ImageSourceProperty, value); }
   }

   public static readonly DependencyProperty ImageSourceProperty =
       DependencyProperty.Register("ImageSource", typeof(ImageSource), typeof(ImageButton), new PropertyMetadata(null));

   public int RowIndex
   {
       get { return (int)GetValue(RowIndexProperty); }
       set { SetValue(RowIndexProperty, value); }
   }

   public static readonly DependencyProperty RowIndexProperty =
       DependencyProperty.Register("RowIndex", typeof(int), typeof(ImageButton), new PropertyMetadata(0));

   public int ColumnIndex
   {
       get { return (int)GetValue(ColumnIndexProperty); }
       set { SetValue(ColumnIndexProperty, value); }
   }

   public static readonly DependencyProperty ColumnIndexProperty =
       DependencyProperty.Register("ColumnIndex", typeof(int), typeof(ImageButton), new PropertyMetadata(0));
}

public enum ImageLocation
{
   Left,
   Top,
   Right,
   Bottom,
   Center
}

Generic.xaml file:

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfImageButton">
    <Style TargetType="{x:Type local:ImageButton}" BasedOn="{StaticResource {x:Type Button}}">
        <Setter Property="ContentTemplate">
            <Setter.Value>
                <DataTemplate>
                    <Grid>
                        <Grid.RowDefinitions>
                            <RowDefinition Height="Auto"/>
                            <RowDefinition Height="*"/>
                            <RowDefinition Height="Auto"/>
                        </Grid.RowDefinitions>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="Auto"/>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="Auto"/>
                        </Grid.ColumnDefinitions>
                        <Image Source="{Binding ImageSource, RelativeSource={RelativeSource AncestorType=local:ImageButton}}"
                               Width="{Binding ImageWidth, RelativeSource={RelativeSource AncestorType=local:ImageButton}}"
                               Height="{Binding ImageHeight, RelativeSource={RelativeSource AncestorType=local:ImageButton}}"
                               Grid.Row="{Binding RowIndex, RelativeSource={RelativeSource AncestorType=local:ImageButton}}"
                               Grid.Column="{Binding ColumnIndex, RelativeSource={RelativeSource AncestorType=local:ImageButton}}"
                               VerticalAlignment="Center" HorizontalAlignment="Center"></Image>
                        <ContentPresenter Grid.Row="1" Grid.Column="1" Content="{TemplateBinding Content}"
                                          VerticalAlignment="Center" HorizontalAlignment="Center"></ContentPresenter>
                    </Grid>
                </DataTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

How to join entries in a set into one string?

I wrote a method that handles the following edge-cases:

  • Set size one. A ", ".join({'abc'}) will return "a, b, c". My desired output was "abc".
  • Set including integers.
  • Empty set should returns ""
def set_to_str(set_to_convert, separator=", "):
        set_size = len(set_to_convert)
        if not set_size:
            return ""
        elif set_size == 1:
            (element,) = set_to_convert
            return str(element)
        else:
            return separator.join(map(str, set_to_convert))

What's in an Eclipse .classpath/.project file?

This eclipse documentation has details on the markups in .project file: The project description file

It describes the .project file as:

When a project is created in the workspace, a project description file is automatically generated that describes the project. The purpose of this file is to make the project self-describing, so that a project that is zipped up or released to a server can be correctly recreated in another workspace. This file is always called ".project"

Open page in new window without popup blocking

As a general rule, pop up blockers target windows that launch without user interaction. Usually a click event can open a window without it being blocked. (unless it's a really bad popup blocker)

Try launching after a click event

Regex allow a string to only contain numbers 0 - 9 and limit length to 45

Rails doesnt like the using of ^ and $ for some security reasons , probably its better to use \A and \z to set the beginning and the end of the string

Android Button setOnClickListener Design

You can use array to handle several button click listener in android like this: here i am setting button click listener for n buttons by using array as:

Button btn[] = new Button[n]; 

NOTE: n is a constant positive integer

Code example:

//class androidMultipleButtonActions 
package a.b.c.app;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class androidMultipleButtonActions extends Activity implements OnClickListener{
    Button btn[] = new Button[3];

    public void onCreate(Bundle savedInstanceState) {   
    super.onCreate(savedInstanceState);
        setContentView(R.layout.main);        
        btn[0] = (Button) findViewById(R.id.Button1);
        btn[1] = (Button) findViewById(R.id.Button2);
        btn[2] = (Button) findViewById(R.id.Button3);
        for(int i=0; i<3; i++){
            btn[i].setOnClickListener(this);
        }           
    }

    public void onClick(View v) {
        if(v == findViewById(R.id.Button1)){
            //do here what u wanna do.
        }
        else if(v == findViewById(R.id.Button2)){
            //do here what u wanna do.
        }
        else if(v == findViewById(R.id.Button3)){
            //do here what u wanna do.
        }
    }
}

Note: First write an main.xml file if u dont know how to write please mail to: [email protected]

html5 - canvas element - Multiple layers

You can create multiple canvas elements without appending them into document. These will be your layers:

Then do whatever you want with them and at the end just render their content in proper order at destination canvas using drawImage on context.

Example:

/* using canvas from DOM */
var domCanvas = document.getElementById('some-canvas');
var domContext = domCanvas.getContext('2d');
domContext.fillRect(50,50,150,50);

/* virtual canvase 1 - not appended to the DOM */
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
ctx.fillStyle = 'blue';
ctx.fillRect(50,50,150,150);

/* virtual canvase 2 - not appended to the DOM */    
var canvas2 = document.createElement('canvas')
var ctx2 = canvas2.getContext('2d');
ctx2.fillStyle = 'yellow';
ctx2.fillRect(50,50,100,50)

/* render virtual canvases on DOM canvas */
domContext.drawImage(canvas, 0, 0, 200, 200);
domContext.drawImage(canvas2, 0, 0, 200, 200);

And here is some codepen: https://codepen.io/anon/pen/mQWMMW

How to open CSV file in R when R says "no such file or directory"?

In my case this very problem was raised by wrong spelling, lower case 'c:' instead of upper case 'C:' in the path. I corrected spelling and problem vanished.

Split a string by a delimiter in python

You may be interested in the csv module, which is designed for comma-separated files but can be easily modified to use a custom delimiter.

import csv
csv.register_dialect( "myDialect", delimiter = "__", <other-options> )
lines = [ "MATCHES__STRING" ]

for row in csv.reader( lines ):
    ...

How can I make a Python script standalone executable to run without ANY dependency?

Yes, it is possible to compile Python scripts into standalone executables.

PyInstaller can be used to convert Python programs into stand-alone executables, under Windows, Linux, Mac OS X, FreeBSD, Solaris, and AIX. It is one of the recommended converters.

py2exe converts Python scripts into only executable on the Windows platform.

Cython is a static compiler for both the Python programming language and the extended Cython programming language.

How to clear a data grid view

IF you want to clear not only Data, but also ComboBoxes, Checkboxes, try

dataGridView.Columns.Clear();

How to capture Enter key press?

Use onkeypress . Check if the pressed key is enter (keyCode = 13). if yes, call the searching() function.

HTML

<input name="keywords" type="text" id="keywords" size="50"  onkeypress="handleKeyPress(event)">

JAVASCRIPT

function handleKeyPress(e){
 var key=e.keyCode || e.which;
  if (key==13){
     searching();
  }
}

Here is a snippet showing it in action:

_x000D_
_x000D_
document.getElementById("msg1").innerHTML = "Default";_x000D_
function handle(e){_x000D_
 document.getElementById("msg1").innerHTML = "Trigger";_x000D_
 var key=e.keyCode || e.which;_x000D_
  if (key==13){_x000D_
     document.getElementById("msg1").innerHTML = "HELLO!";_x000D_
  }_x000D_
}
_x000D_
<input type="text" name="box22" value="please" onkeypress="handle(event)"/>_x000D_
<div id="msg1"></div>
_x000D_
_x000D_
_x000D_

How to create multiple class objects with a loop in python?

you can use list to define it.

objs = list()
for i in range(10):
    objs.append(MyClass())

Laravel PHP Command Not Found

If you have Composer installed globally, you can install the Laravel installer tool using command below:

composer global require "laravel/installer=~1.1"

How to stop C# console applications from closing automatically?

Use:

Console.ReadKey();

For it to close when someone presses any key, or:

Console.ReadLine();

For when the user types something and presses enter.

How to hide console window in python?

Some additional info. for situations that'll need the win32gui solution posted by Mohsen Haddadi earlier in this thread:

As of python 361, win32gui & win32con are not part of the python std library. To use them, pywin32 package will need to be installed; now possible via pip.

More background info on pywin32 package is at: How to use the win32gui module with Python?.

Also, to apply discretion while closing a window so as to not inadvertently close any window in the foreground, the resolution could be extended along the lines of the following:

try     :

    import win32gui, win32con;

    frgrnd_wndw = win32gui.GetForegroundWindow();
    wndw_title  = win32gui.GetWindowText(frgrnd_wndw);
    if wndw_title.endswith("python.exe"):
        win32gui.ShowWindow(frgrnd_wndw, win32con.SW_HIDE);
    #endif
except  :
    pass

How can I change the text color with jQuery?

Nowadays, animating text color is included in the jQuery UI Effects Core. It's pretty small. You can make a custom download here: http://jqueryui.com/download - but you don't actually need anything but the effects core itself (not even the UI core), and it brings with it different easing functions as well.

Intellij JAVA_HOME variable

In my case I needed a lower JRE, so I had to tell IntelliJ to use a different one in "Platform Settings"

  • Platform Settings > SDKs ( +; )
  • Click the + button to add a new SDK (or rename and load an existing one)
  • Choose the /Contents/Home directory from the appropriate SDK
    (i.e. /Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home)

CodeIgniter PHP Model Access "Unable to locate the model you have specified"

I resolve this with this way:

  1. I rename file do Page_model.php
  2. Class name to Page_model extends...
  3. I call on autoload: $autoload['model'] = array('Page_model'=>'page');

Works fine.. I hope help.

Base64 encoding and decoding in oracle

All the previous posts are correct. There's more than one way to skin a cat. Here is another way to do the same thing: (just replace "what_ever_you_want_to_convert" with your string and run it in Oracle:

    set serveroutput on;
    DECLARE
    v_str VARCHAR2(1000);
    BEGIN
    --Create encoded value
    v_str := utl_encode.text_encode
    ('what_ever_you_want_to_convert','WE8ISO8859P1', UTL_ENCODE.BASE64);
    dbms_output.put_line(v_str);
    --Decode the value..
    v_str := utl_encode.text_decode
    (v_str,'WE8ISO8859P1', UTL_ENCODE.BASE64);
    dbms_output.put_line(v_str);
    END;
    /

source

Escaping Strings in JavaScript

You can also use this

_x000D_
_x000D_
let str = "hello single ' double \" and slash \\ yippie";

let escapeStr = escape(str);
document.write("<b>str : </b>"+str);
document.write("<br/><b>escapeStr : </b>"+escapeStr);
document.write("<br/><b>unEscapeStr : </b> "+unescape(escapeStr));
_x000D_
_x000D_
_x000D_

Add days Oracle SQL

It's Simple.You can use

select (sysdate+2) as new_date from dual;

This will add two days from current date.

Angular File Upload

First, you need to set up HttpClient in your Angular project.

Open the src/app/app.module.ts file, import HttpClientModule and add it to the imports array of the module as follows:

import { BrowserModule } from '@angular/platform-browser';  
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';  
import { AppComponent } from './app.component';  
import { HttpClientModule } from '@angular/common/http';

@NgModule({  
  declarations: [  
    AppComponent,  
  ],  
  imports: [  
    BrowserModule,  
    AppRoutingModule,  
    HttpClientModule  
  ],  
  providers: [],  
  bootstrap: [AppComponent]  
})  
export class AppModule { }

Next, generate a component:

$ ng generate component home

Next, generate an upload service:

$ ng generate service upload

Next, open the src/app/upload.service.ts file as follows:

import { HttpClient, HttpEvent, HttpErrorResponse, HttpEventType } from  '@angular/common/http';  
import { map } from  'rxjs/operators';

@Injectable({  
  providedIn: 'root'  
})  
export class UploadService { 
    SERVER_URL: string = "https://file.io/";  
    constructor(private httpClient: HttpClient) { }
    public upload(formData) {

      return this.httpClient.post<any>(this.SERVER_URL, formData, {  
         reportProgress: true,  
         observe: 'events'  
      });  
   }
}

Next, open the src/app/home/home.component.ts file, and start by adding the following imports:

import { Component, OnInit, ViewChild, ElementRef  } from '@angular/core';
import { HttpEventType, HttpErrorResponse } from '@angular/common/http';
import { of } from 'rxjs';  
import { catchError, map } from 'rxjs/operators';  
import { UploadService } from  '../upload.service';

Next, define the fileUpload and files variables and inject UploadService as follows:

@Component({  
  selector: 'app-home',  
  templateUrl: './home.component.html',  
  styleUrls: ['./home.component.css']  
})  
export class HomeComponent implements OnInit {
    @ViewChild("fileUpload", {static: false}) fileUpload: ElementRef;files  = [];  
    constructor(private uploadService: UploadService) { }

Next, define the uploadFile() method:

uploadFile(file) {  
    const formData = new FormData();  
    formData.append('file', file.data);  
    file.inProgress = true;  
    this.uploadService.upload(formData).pipe(  
      map(event => {  
        switch (event.type) {  
          case HttpEventType.UploadProgress:  
            file.progress = Math.round(event.loaded * 100 / event.total);  
            break;  
          case HttpEventType.Response:  
            return event;  
        }  
      }),  
      catchError((error: HttpErrorResponse) => {  
        file.inProgress = false;  
        return of(`${file.data.name} upload failed.`);  
      })).subscribe((event: any) => {  
        if (typeof (event) === 'object') {  
          console.log(event.body);  
        }  
      });  
  }

Next, define the uploadFiles() method which can be used to upload multiple image files:

private uploadFiles() {  
    this.fileUpload.nativeElement.value = '';  
    this.files.forEach(file => {  
      this.uploadFile(file);  
    });  
}

Next, define the onClick() method:

onClick() {  
    const fileUpload = this.fileUpload.nativeElement;fileUpload.onchange = () => {  
    for (let index = 0; index < fileUpload.files.length; index++)  
    {  
     const file = fileUpload.files[index];  
     this.files.push({ data: file, inProgress: false, progress: 0});  
    }  
      this.uploadFiles();  
    };  
    fileUpload.click();  
}

Next, we need to create the HTML template of our image upload UI. Open the src/app/home/home.component.html file and add the following content:

<div [ngStyle]="{'text-align':center; 'margin-top': 100px;}">
   <button mat-button color="primary" (click)="fileUpload.click()">choose file</button>  
   <button mat-button color="warn" (click)="onClick()">Upload</button>  
   <input [hidden]="true" type="file" #fileUpload id="fileUpload" name="fileUpload" multiple="multiple" accept="image/*" />
</div>

Check out this tutorial and this post

Error ITMS-90717: "Invalid App Store Icon"

If showing this error for ionic3 project when you upload to iTunes Connect, please check this ANSWER

This is my project error when I try to vilidated. enter image description here

Finally follow this ANSWER, error solved. enter image description here

How to avoid annoying error "declared and not used"

You can use a simple "null function" for this, for example:

func Use(vals ...interface{}) {
    for _, val := range vals {
        _ = val
    }
}

Which you can use like so:

package main

func main() {
    a := "declared and not used"
    b := "another declared and not used"
    c := 123

    Use(a, b, c)
}

There's also a package for this so you don't have to define the Use function every time:

import (
  "github.com/lunux2008/xulu"
)

func main() {
  // [..]

  xulu.Use(a, b, c)
}

Getting "cannot find Symbol" in Java project in Intellij

Sometimes the class you want is in the test source directory. Happened to me, anyway…

How to set a single, main title above all the subplots with Pyplot?

A few points I find useful when applying this to my own plots:

  • I prefer the consistency of using fig.suptitle(title) rather than plt.suptitle(title)
  • When using fig.tight_layout() the title must be shifted with fig.subplots_adjust(top=0.88)
  • See answer below about fontsizes

Example code taken from subplots demo in matplotlib docs and adjusted with a master title.

A nice 4x4 plot

import matplotlib.pyplot as plt
import numpy as np

# Simple data to display in various forms
x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x ** 2)

fig, axarr = plt.subplots(2, 2)
fig.suptitle("This Main Title is Nicely Formatted", fontsize=16)

axarr[0, 0].plot(x, y)
axarr[0, 0].set_title('Axis [0,0] Subtitle')
axarr[0, 1].scatter(x, y)
axarr[0, 1].set_title('Axis [0,1] Subtitle')
axarr[1, 0].plot(x, y ** 2)
axarr[1, 0].set_title('Axis [1,0] Subtitle')
axarr[1, 1].scatter(x, y ** 2)
axarr[1, 1].set_title('Axis [1,1] Subtitle')

# # Fine-tune figure; hide x ticks for top plots and y ticks for right plots
plt.setp([a.get_xticklabels() for a in axarr[0, :]], visible=False)
plt.setp([a.get_yticklabels() for a in axarr[:, 1]], visible=False)

# Tight layout often produces nice results
# but requires the title to be spaced accordingly
fig.tight_layout()
fig.subplots_adjust(top=0.88)

plt.show()

What is the C# equivalent of friend?

There's no direct equivalent of "friend" - the closest that's available (and it isn't very close) is InternalsVisibleTo. I've only ever used this attribute for testing - where it's very handy!

Example: To be placed in AssemblyInfo.cs

[assembly: InternalsVisibleTo("OtherAssembly")]

Add newline to VBA or Visual Basic 6

Use this code between two words:

& vbCrLf &

Using this, the next word displays on the next line.

Where IN clause in LINQ

public List<Requirement> listInquiryLogged()
{
    using (DataClassesDataContext dt = new DataClassesDataContext(System.Configuration.ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString))
    {
        var inq = new int[] {1683,1684,1685,1686,1687,1688,1688,1689,1690,1691,1692,1693};
        var result = from Q in dt.Requirements
                     where inq.Contains(Q.ID)
                     orderby Q.Description
                     select Q;

        return result.ToList<Requirement>();
    }
}

AngularJS: how to implement a simple file upload with multipart form?

A real working solution with no other dependencies than angularjs (tested with v.1.0.6)

html

<input type="file" name="file" onchange="angular.element(this).scope().uploadFile(this.files)"/>

Angularjs (1.0.6) not support ng-model on "input-file" tags so you have to do it in a "native-way" that pass the all (eventually) selected files from the user.

controller

$scope.uploadFile = function(files) {
    var fd = new FormData();
    //Take the first selected file
    fd.append("file", files[0]);

    $http.post(uploadUrl, fd, {
        withCredentials: true,
        headers: {'Content-Type': undefined },
        transformRequest: angular.identity
    }).success( ...all right!... ).error( ..damn!... );

};

The cool part is the undefined content-type and the transformRequest: angular.identity that give at the $http the ability to choose the right "content-type" and manage the boundary needed when handling multipart data.

C program to check little vs. big endian

In short, yes.

Suppose we are on a 32-bit machine.

If it is little endian, the x in the memory will be something like:

       higher memory
          ----->
    +----+----+----+----+
    |0x01|0x00|0x00|0x00|
    +----+----+----+----+
    A
    |
   &x

so (char*)(&x) == 1, and *y+48 == '1'.

If it is big endian, it will be:

    +----+----+----+----+
    |0x00|0x00|0x00|0x01|
    +----+----+----+----+
    A
    |
   &x

so this one will be '0'.

Import an Excel worksheet into Access using VBA

Pass the sheet name with the Range parameter of the DoCmd.TransferSpreadsheet Method. See the box titled "Worksheets in the Range Parameter" near the bottom of that page.

This code imports from a sheet named "temp" in a workbook named "temp.xls", and stores the data in a table named "tblFromExcel".

Dim strXls As String
strXls = CurrentProject.Path & Chr(92) & "temp.xls"
DoCmd.TransferSpreadsheet acImport, , "tblFromExcel", _
    strXls, True, "temp!"

How to drop unique in MySQL?

Simply you can use the following SQL Script to delete the index in MySQL:

alter table fuinfo drop index email;

In JPA 2, using a CriteriaQuery, how to count results

You can also use Projections:

ProjectionList projection = Projections.projectionList();
projection.add(Projections.rowCount());
criteria.setProjection(projection);

Long totalRows = (Long) criteria.list().get(0);

Objective-C declared @property attributes (nonatomic, copy, strong, weak)

Great answers! One thing that I would like to clarify deeper is nonatomic/atomic. The user should understand that this property - "atomicity" spreads only on the attribute's reference and not on it's contents. I.e. atomic will guarantee the user atomicity for reading/setting the pointer and only the pointer to the attribute. For example:

@interface MyClass: NSObject
@property (atomic, strong) NSDictionary *dict;
...

In this case it is guaranteed that the pointer to the dict will be read/set in the atomic manner by different threads. BUT the dict itself (the dictionary dict pointing to) is still thread unsafe, i.e. all read/add operations to the dictionary are still thread unsafe.

If you need thread safe collection you either have bad architecture (more often) OR real requirement (more rare). If it is "real requirement" - you should either find good&tested thread safe collection component OR be prepared for trials and tribulations writing your own one. It latter case look at "lock-free", "wait-free" paradigms. Looks like rocket-science at a first glance, but could help you achieving fantastic performance in comparison to "usual locking".

IF a cell contains a string

=IFS(COUNTIF(A1,"*cats*"),"cats",COUNTIF(A1,"*22*"),"22",TRUE,"none")

Include files from parent or other directory

I took inspiration from frank and I added something like this in my "settings.php" file that is then included in all pages when there is a link:

"settings.php"

    $folder_depth = substr_count($_SERVER["PHP_SELF"] , "/");

     $slash="";

    for ($i=1;$i<=($folder_depth-2);++$i){

        $slash= $slash."../";

    }

in my header.php to be included in all pages:

a href= .... php echo $slash.'index.php'....

seems it works both on local and hosted environment....

(NOTE: I am an absolute beginner )

Return from a promise then()

I prefer to use "await" command and async functions to get rid of confusions of promises,

In this case I would write an asynchronous function first, this will be used instead of the anonymous function called under "promise.then" part of this question :

async function SubFunction(output){

   // Call to database , returns a promise, like an Ajax call etc :

   const response = await axios.get( GetApiHost() + '/api/some_endpoint')

   // Return :
   return response;

}

and then I would call this function from main function :

async function justTesting() {
   const lv_result = await SubFunction(output);

   return lv_result + 1;
}

Noting that I returned both main function and sub function to async functions here.

How to reset / remove chrome's input highlighting / focus border?

To remove the default focus, use the following in your default .css file :

:focus {outline:none;}

You can then control the focus border color either individually by element, or in the default .css:

:focus {outline:none;border:1px solid red}

Obviously replace red with your chosen hex code.

You could also leave the border untouched and control the background color (or image) to highlight the field:

:focus {outline:none;background-color:red}

:-)

Using Excel as front end to Access database (with VBA)

It's quite easy and efficient to use Excel as a reporting tool for Access data. A quick "non programming" approach is to set a List or a Pivot Table, linked to your External Data source. But that's out of scope for Stackoverflow.
A programmatic approach can be very simple:

strProv = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & SourceFile & ";"
Set cnn = New ADODB.Connection  
cnn.Open strProv
Set rst = New ADODB.Recordset
rst.Open strSql, cnn
myDestRange.CopyFromRecordset rst

That's it !

JavaScript: Create and save file

_x000D_
_x000D_
setTimeout("create('Hello world!', 'myfile.txt', 'text/plain')");_x000D_
function create(text, name, type) {_x000D_
  var dlbtn = document.getElementById("dlbtn");_x000D_
  var file = new Blob([text], {type: type});_x000D_
  dlbtn.href = URL.createObjectURL(file);_x000D_
  dlbtn.download = name;_x000D_
}
_x000D_
<a href="javascript:void(0)" id="dlbtn"><button>click here to download your file</button></a>
_x000D_
_x000D_
_x000D_

CSS Select box arrow style

Try to replace the

padding: 2px 30px 2px 2px;

with

padding: 2px 2px 2px 2px;

It should work.

How to save a PNG image server-side, from a base64 data string

try this...

$file = $_POST['file']; //your data in base64 'data:image/png....';
$img = str_replace('data:image/png;base64,', '', $file);
file_put_contents('img/imag.png', base64_decode($img));

converting a base 64 string to an image and saving it

In my case it works only with two line of code. Test the below C# code:

String dirPath = "C:\myfolder\";
String imgName = "my_mage_name.bmp";

byte[] imgByteArray = Convert.FromBase64String("your_base64_string");
File.WriteAllBytes(dirPath + imgName, imgByteArray);

That's it. Kindly up vote if you really find this solution works for you. Thanks in advance.

Difference between VARCHAR and TEXT in MySQL

TL;DR

TEXT

  • fixed max size of 65535 characters (you cannot limit the max size)
  • takes 2 + c bytes of disk space, where c is the length of the stored string.
  • cannot be (fully) part of an index. One would need to specify a prefix length.

VARCHAR(M)

  • variable max size of M characters
  • M needs to be between 1 and 65535
  • takes 1 + c bytes (for M ≤ 255) or 2 + c (for 256 ≤ M ≤ 65535) bytes of disk space where c is the length of the stored string
  • can be part of an index

More Details

TEXT has a fixed max size of 2¹6-1 = 65535 characters.
VARCHAR has a variable max size M up to M = 2¹6-1.
So you cannot choose the size of TEXT but you can for a VARCHAR.

The other difference is, that you cannot put an index (except for a fulltext index) on a TEXT column.
So if you want to have an index on the column, you have to use VARCHAR. But notice that the length of an index is also limited, so if your VARCHAR column is too long you have to use only the first few characters of the VARCHAR column in your index (See the documentation for CREATE INDEX).

But you also want to use VARCHAR, if you know that the maximum length of the possible input string is only M, e.g. a phone number or a name or something like this. Then you can use VARCHAR(30) instead of TINYTEXT or TEXT and if someone tries to save the text of all three "Lord of the Ring" books in your phone number column you only store the first 30 characters :)

Edit: If the text you want to store in the database is longer than 65535 characters, you have to choose MEDIUMTEXT or LONGTEXT, but be careful: MEDIUMTEXT stores strings up to 16 MB, LONGTEXT up to 4 GB. If you use LONGTEXT and get the data via PHP (at least if you use mysqli without store_result), you maybe get a memory allocation error, because PHP tries to allocate 4 GB of memory to be sure the whole string can be buffered. This maybe also happens in other languages than PHP.

However, you should always check the input (Is it too long? Does it contain strange code?) before storing it in the database.

Notice: For both types, the required disk space depends only on the length of the stored string and not on the maximum length.
E.g. if you use the charset latin1 and store the text "Test" in VARCHAR(30), VARCHAR(100) and TINYTEXT, it always requires 5 bytes (1 byte to store the length of the string and 1 byte for each character). If you store the same text in a VARCHAR(2000) or a TEXT column, it would also require the same space, but, in this case, it would be 6 bytes (2 bytes to store the string length and 1 byte for each character).

For more information have a look at the documentation.

Finally, I want to add a notice, that both, TEXT and VARCHAR are variable length data types, and so they most likely minimize the space you need to store the data. But this comes with a trade-off for performance. If you need better performance, you have to use a fixed length type like CHAR. You can read more about this here.

Using an Alias in a WHERE clause

This is not possible directly, because chronologically, WHERE happens before SELECT, which always is the last step in the execution chain.

You can do a sub-select and filter on it:

SELECT * FROM
(
  SELECT A.identifier
    , A.name
    , TO_NUMBER(DECODE( A.month_no
      , 1, 200803 
      , 2, 200804 
      , 3, 200805 
      , 4, 200806 
      , 5, 200807 
      , 6, 200808 
      , 7, 200809 
      , 8, 200810 
      , 9, 200811 
      , 10, 200812 
      , 11, 200701 
      , 12, 200702
      , NULL)) as MONTH_NO
    , TO_NUMBER(TO_CHAR(B.last_update_date, 'YYYYMM')) as UPD_DATE
  FROM table_a A
    , table_b B
  WHERE A.identifier = B.identifier
) AS inner_table
WHERE 
  MONTH_NO > UPD_DATE

Interesting bit of info moved up from the comments:

There should be no performance hit. Oracle does not need to materialize inner queries before applying outer conditions -- Oracle will consider transforming this query internally and push the predicate down into the inner query and will do so if it is cost effective. – Justin Cave

Android How to adjust layout in Full Screen Mode when softkeyboard is visible

I'm currently using this approach and it works like a charm. The trick is we get keyboard height from different methods on 21 above and below and then use it as the bottom padding of our root view in our activity. I assumed your layout does not need a top padding (goes below status bar) but in case you do, inform me to update my answer.

MainActivity.java

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        RelativeLayout mainLayout = findViewById(R.id.main_layout);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            ViewCompat.setOnApplyWindowInsetsListener(mainLayout , new OnApplyWindowInsetsListener() {
                @Override
                public WindowInsetsCompat onApplyWindowInsets(View v, WindowInsetsCompat insets) {
                    v.setPadding(0, 0, 0, insets.getSystemWindowInsetBottom());
                    return insets;
                }
            });
        } else {
            View decorView = getWindow().getDecorView();
            final View contentView = mainLayout;
            decorView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    Rect r = new Rect();
                    //r will be populated with the coordinates of your view that area still visible.
                    decorView.getWindowVisibleDisplayFrame(r);

                    //get screen height and calculate the difference with the useable area from the r
                    int height = decorView.getContext().getResources().getDisplayMetrics().heightPixels;
                    int diff = height - r.bottom;

                    //if it could be a keyboard add the padding to the view
                    if (diff != 0) {
                        // if the use-able screen height differs from the total screen height we assume that it shows a keyboard now
                        //check if the padding is 0 (if yes set the padding for the keyboard)
                        if (contentView.getPaddingBottom() != diff) {
                            //set the padding of the contentView for the keyboard
                            contentView.setPadding(0, 0, 0, diff);
                        }
                    } else {
                        //check if the padding is != 0 (if yes reset the padding)
                        if (contentView.getPaddingBottom() != 0) {
                            //reset the padding of the contentView
                            contentView.setPadding(0, 0, 0, 0);
                        }
                    }
                }
            });
        }
    }
...
}

Don't forget to address your root view with an id:

activity_main.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/main_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

Hope it helps someone.

How does Java deal with multiple conditions inside a single IF statement

Yes, Java (similar to other mainstream languages) uses lazy evaluation short-circuiting which means it evaluates as little as possible.

This means that the following code is completely safe:

if(p != null && p.getAge() > 10)

Also, a || b never evaluates b if a evaluates to true.

What are the differences between stateless and stateful systems, and how do they impact parallelism?

A stateless system can be seen as a box [black? ;)] where at any point in time the value of the output(s) depends only on the value of the input(s) [after a certain processing time]

A stateful system instead can be seen as a box where at any point in time the value of the output(s) depends on the value of the input(s) and of an internal state, so basicaly a stateful system is like a state machine with "memory" as the same set of input(s) value can generate different output(s) depending on the previous input(s) received by the system.

From the parallel programming point of view, a stateless system, if properly implemented, can be executed by multiple threads/tasks at the same time without any concurrency issue [as an example think of a reentrant function] A stateful system will requires that multiple threads of execution access and update the internal state of the system in an exclusive way, hence there will be a need for a serialization [synchronization] point.

how to create a list of lists

You want to create an empty list, then append the created list to it. This will give you the list of lists. Example:

>>> l = []
>>> l.append([1,2,3])
>>> l.append([4,5,6])
>>> l
[[1, 2, 3], [4, 5, 6]]