Programs & Examples On #Bwtoolkit

Submitting a form by pressing enter without a submit button

For anyone looking at this answer in future, HTML5 implements a new attribute for form elements, hidden, which will automatically apply display:none to your element.

e.g.

<input type="submit" hidden />

How to get the last row of an Oracle a table

There is no such thing as the "last" row in a table, as an Oracle table has no concept of order.

However, assuming that you wanted to find the last inserted primary key and that this primary key is an incrementing number, you could do something like this:

select *
  from ( select a.*, max(pk) over () as max_pk
           from my_table a
                )
 where pk = max_pk

If you have the date that each row was created this would become, if the column is named created:

select *
  from ( select a.*, max(created) over () as max_created
           from my_table a
                )
 where created = max_created

Alternatively, you can use an aggregate query, for example:

select *
  from my_table
 where pk = ( select max(pk) from my_table )

Here's a little SQL Fiddle to demonstrate.

Apache Tomcat Not Showing in Eclipse Server Runtime Environments

In my case I needed to install "JST Server Adapters". I am running Eclipse 3.6 Helios RCP Edition.

Here are the steps I followed:

  1. Help -> Install New Software
  2. Choose "Helios - http://download.eclipse.org/releases/helios" site or kepler - http://download.ecliplse.org/releases/kepler
  3. Expand "Web, XML, and Java EE Development"
  4. Check JST Server Adapters (version 3.2.2)

After that I could define new Server Runtime Environments.

EDIT: With Eclipse 3.7 Indigo Classic, Eclipse Kepler and Luna, the steps are the same (with appropriate update site) but you need both JST Server Adapters and JST Server Adapters Extentions to get the Server Runtime Environment options.

How to set cache: false in jQuery.get call

Note that callback syntax is deprecated:

Deprecation Notice

The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callback methods introduced in jQuery 1.5 are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

Here a modernized solution using the promise interface

$.ajax({url: "...", cache: false}).done(function( data ) {
    // data contains result
}).fail(function(err){
    // error
});

How do I convert a String to a BigInteger?

Instead of using valueOf(long) and parse(), you can directly use the BigInteger constructor that takes a string argument:

BigInteger numBig = new BigInteger("8599825996872482982482982252524684268426846846846846849848418418414141841841984219848941984218942894298421984286289228927948728929829");

That should give you the desired value.

Converting Select results into Insert script - SQL Server

In SSMS:

  • Right click on the database > Tasks > Generate Scripts

  • Next

  • Select "Select specific database objects" and check the table you want scripted, Next

  • Click Advanced > in the list of options, scroll down to the bottom and look for the "Types of data to script" and change it to "Data Only" > OK

  • Select "Save to new query window" > Next > Next > Finish

All 180 rows now written as 180 insert statements!

Python copy files to a new directory and rename if file name already exists

For me shutil.copy is the best:

import shutil

#make a copy of the invoice to work with
src="invoice.pdf"
dst="copied_invoice.pdf"
shutil.copy(src,dst)

You can change the path of the files as you want.

Parsing ISO 8601 date in Javascript

If you want to keep it simple, this should suffice:

function parseIsoDatetime(dtstr) {
    var dt = dtstr.split(/[: T-]/).map(parseFloat);
    return new Date(dt[0], dt[1] - 1, dt[2], dt[3] || 0, dt[4] || 0, dt[5] || 0, 0);
}

note parseFloat is must, parseInt doesn't always work. Map requires IE9 or later.

Works for formats:

  • 2014-12-28 15:30:30
  • 2014-12-28T15:30:30
  • 2014-12-28

Not valid for timezones, see other answers about those.

Asp.net - Add blank item at top of dropdownlist

I think a better way is to insert the blank item first, then bind the data just as you have been doing. However you need to set the AppendDataBoundItems property of the list control.

We use the following method to bind any data source to any list control...

public static void BindList(ListControl list, IEnumerable datasource, string valueName, string textName)
{
    list.Items.Clear();
    list.Items.Add("", "");
    list.AppendDataBoundItems = true;
    list.DataValueField = valueName;
    list.DataTextField = textName;
    list.DataSource = datasource;
    list.DataBind();
}

How do I check if string contains substring?

The includes() method determines whether one string may be found within another string, returning true or false as appropriate.

Syntax :-string.includes(searchString[, position])

searchString:-A string to be searched for within this string.

position:-Optional. The position in this string at which to begin searching for searchString; defaults to 0.

string = 'LOL';
console.log(string.includes('lol')); // returns false 
console.log(string.includes('LOL')); // returns true 

php Replacing multiple spaces with a single space

$output = preg_replace('/\s+/', ' ',$input);

\s is shorthand for [ \t\n\r]. Multiple spaces will be replaced with single space.

Django REST Framework: adding additional field to ModelSerializer

My response to a similar question (here) might be useful.

If you have a Model Method defined in the following way:

class MyModel(models.Model):
    ...

    def model_method(self):
        return "some_calculated_result"

You can add the result of calling said method to your serializer like so:

class MyModelSerializer(serializers.ModelSerializer):
    model_method_field = serializers.CharField(source='model_method')

p.s. Since the custom field isn't really a field in your model, you'll usually want to make it read-only, like so:

class Meta:
    model = MyModel
    read_only_fields = (
        'model_method_field',
        )

How to set a CMake option() at command line

Delete the CMakeCache.txt file and try this:

cmake -G %1 -DBUILD_SHARED_LIBS=ON -DBUILD_STATIC_LIBS=ON -DBUILD_TESTS=ON ..

You have to enter all your command-line definitions before including the path.

In a Bash script, how can I exit the entire script if a certain condition occurs?

Instead of if construct, you can leverage the short-circuit evaluation:

#!/usr/bin/env bash

echo $[1+1]
echo $[2/0]              # division by 0 but execution of script proceeds
echo $[3+1]
(echo $[4/0]) || exit $? # script halted with code 1 returned from `echo`
echo $[5+1]

Note the pair of parentheses which is necessary because of priority of alternation operator. $? is a special variable set to exit code of most recently called command.

How Can I Set the Default Value of a Timestamp Column to the Current Timestamp with Laravel Migrations?

Use Paulo Freitas suggestion instead.


Until Laravel fixes this, you can run a standard database query after the Schema::create have been run.

    Schema::create("users", function($table){
        $table->increments('id');
        $table->string('email', 255);
        $table->string('given_name', 100);
        $table->string('family_name', 100);
        $table->timestamp('joined');
        $table->enum('gender', ['male', 'female', 'unisex'])->default('unisex');
        $table->string('timezone', 30)->default('UTC');
        $table->text('about');
    });
    DB::statement("ALTER TABLE ".DB::getTablePrefix()."users CHANGE joined joined TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL");

It worked wonders for me.

adding a datatable in a dataset

DataSet ds = new DataSet();

DataTable activity = DTsetgvActivity.Copy();
activity.TableName = "activity";
ds.Tables.Add(activity);

DataTable Honer = DTsetgvHoner.Copy();
Honer.TableName = "Honer";
ds.Tables.Add(Honer);

DataTable Property = DTsetgvProperty.Copy();
Property.TableName = "Property";
ds.Tables.Add(Property);


DataTable Income = DTsetgvIncome.Copy();
Income.TableName = "Income";
ds.Tables.Add(Income);

DataTable Dependant = DTsetgvDependant.Copy();
Dependant.TableName = "Dependant";
ds.Tables.Add(Dependant);

DataTable Insurance = DTsetgvInsurance.Copy();
Insurance.TableName = "Insurance";
ds.Tables.Add(Insurance);

DataTable Sacrifice = DTsetgvSacrifice.Copy();
Sacrifice.TableName = "Sacrifice";
ds.Tables.Add(Sacrifice);

DataTable Request = DTsetgvRequest.Copy();
Request.TableName = "Request";
ds.Tables.Add(Request);

DataTable Branchs = DTsetgvBranchs.Copy();
Branchs.TableName = "Branchs";
ds.Tables.Add(Branchs);

How to mount host volumes into docker containers in Dockerfile during build

UPDATE: Somebody just won't take no as the answer, and I like it, very much, especially to this particular question.

GOOD NEWS, There is a way now --

The solution is Rocker: https://github.com/grammarly/rocker

John Yani said, "IMO, it solves all the weak points of Dockerfile, making it suitable for development."

Rocker

https://github.com/grammarly/rocker

By introducing new commands, Rocker aims to solve the following use cases, which are painful with plain Docker:

  1. Mount reusable volumes on build stage, so dependency management tools may use cache between builds.
  2. Share ssh keys with build (for pulling private repos, etc.), while not leaving them in the resulting image.
  3. Build and run application in different images, be able to easily pass an artifact from one image to another, ideally have this logic in a single Dockerfile.
  4. Tag/Push images right from Dockerfiles.
  5. Pass variables from shell build command so they can be substituted to a Dockerfile.

And more. These are the most critical issues that were blocking our adoption of Docker at Grammarly.

Update: Rocker has been discontinued, per the official project repo on Github

As of early 2018, the container ecosystem is much more mature than it was three years ago when this project was initiated. Now, some of the critical and outstanding features of rocker can be easily covered by docker build or other well-supported tools, though some features do remain unique to rocker. See https://github.com/grammarly/rocker/issues/199 for more details.

Loading/Downloading image from URL on Swift

The only things there is missing is a !

let url = NSURL.URLWithString("http://live-wallpaper.net/iphone/img/app/i/p/iphone-4s-wallpapers-mobile-backgrounds-dark_2466f886de3472ef1fa968033f1da3e1_raw_1087fae1932cec8837695934b7eb1250_raw.jpg");
var err: NSError?
var imageData :NSData = NSData.dataWithContentsOfURL(url!,options: NSDataReadingOptions.DataReadingMappedIfSafe, error: &err)
var bgImage = UIImage(data:imageData!)

How do I separate an integer into separate digits in an array in JavaScript?

What about:

const n = 123456;
Array.from(n.toString()).map(Number);
// [1, 2, 3, 4, 5, 6]

OnChange event handler for radio button (INPUT type="radio") doesn't work as one value

I would make two changes:

<input type="radio" name="myRadios" onclick="handleClick(this);" value="1" />
<input type="radio" name="myRadios" onclick="handleClick(this);" value="2" />
  1. Use the onclick handler instead of onchange - you're changing the "checked state" of the radio input, not the value, so there's not a change event happening.
  2. Use a single function, and pass this as a parameter, that will make it easy to check which value is currently selected.

ETA: Along with your handleClick() function, you can track the original / old value of the radio in a page-scoped variable. That is:

var currentValue = 0;
function handleClick(myRadio) {
    alert('Old value: ' + currentValue);
    alert('New value: ' + myRadio.value);
    currentValue = myRadio.value;
}

_x000D_
_x000D_
var currentValue = 0;_x000D_
function handleClick(myRadio) {_x000D_
    alert('Old value: ' + currentValue);_x000D_
    alert('New value: ' + myRadio.value);_x000D_
    currentValue = myRadio.value;_x000D_
}
_x000D_
<input type="radio" name="myRadios" onclick="handleClick(this);" value="1" />_x000D_
<input type="radio" name="myRadios" onclick="handleClick(this);" value="2" />
_x000D_
_x000D_
_x000D_

Python: CSV write by column rather than row

what about Result_* there also are generated in the loop (because i don't think it's possible to add to the csv file)

i will go like this ; generate all the data at one rotate the matrix write in the file:

A = []

A.append(range(1, 5))  # an Example of you first loop

A.append(range(5, 9))  # an Example of you second loop

data_to_write = zip(*A)

# then you can write now row by row

how to properly display an iFrame in mobile safari

Don't scroll the IFrame page or its content, scroll the parent page. If you control the IFrame content, you can use the iframe-resizer library to turn the iframe element itself into a proper block level element, with a natural/correct/native height. Also, don't attempt to position (fixed, absolute) your iframe in the parent page, or present an iframe in a modal window, especially if it has form elements.

I also suspect that iOS Safari has a non-standards behavior that expands your iframe's height to its natural height, much like the iframe-resizer library will do for desktop browsers, which seem to render responsive iframe content at height 0px or 150px or some other not useful default. If you need to contrain width, try a max-width style inside the iframe.

Visual Studio: Relative Assembly References Paths

Probably, the easiest way to achieve this is to simply add the reference to the assembly and then (manually) patch the textual representation of the reference in the corresponding Visual Studio project file (extension .csproj) such that it becomes relative.

I've done this plenty of times in VS 2005 without any problems.

Passing an array to a query using a WHERE clause

Use:

select id from galleries where id in (1, 2, 5);

A simple for each loop will work.

Flavius/AvatarKava's way is better, but make sure that none of the array values contain commas.

Call a React component method from outside

You can do like

import React from 'react';

class Header extends React.Component{

    constructor(){
        super();
        window.helloComponent = this;
    }

    alertMessage(){
       console.log("Called from outside");
    }

    render(){

      return (
      <AppBar style={{background:'#000'}}>
        Hello
      </AppBar>
      )
    }
}

export default Header;

Now from outside of this component you can called like this below

window.helloComponent.alertMessage();

Why does .json() return a promise?

Also, what helped me understand this particular scenario that you described is the Promise API documentation, specifically where it explains how the promised returned by the then method will be resolved differently depending on what the handler fn returns:

if the handler function:

  • returns a value, the promise returned by then gets resolved with the returned value as its value;
  • throws an error, the promise returned by then gets rejected with the thrown error as its value;
  • returns an already resolved promise, the promise returned by then gets resolved with that promise's value as its value;
  • returns an already rejected promise, the promise returned by then gets rejected with that promise's value as its value.
  • returns another pending promise object, the resolution/rejection of the promise returned by then will be subsequent to the resolution/rejection of the promise returned by the handler. Also, the value of the promise returned by then will be the same as the value of the promise returned by the handler.

'if' statement in jinja2 template

We need to remember that the {% endif %} comes after the {% else %}.

So this is an example:

{% if someTest %}
     <p> Something is True </p>
{% else %}
     <p> Something is False </p>
{% endif %}

PostgreSQL "DESCRIBE TABLE"

The best way to describe a table such as a column, type, modifiers of columns, etc.

\d+ tablename or \d tablename

DB2 SQL error: SQLCODE: -206, SQLSTATE: 42703

That only means that an undefined column or parameter name was detected. The errror that DB2 gives should point what that may be:

DB2 SQL Error: SQLCODE=-206, SQLSTATE=42703, SQLERRMC=[THE_UNDEFINED_COLUMN_OR_PARAMETER_NAME], DRIVER=4.8.87

Double check your table definition. Maybe you just missed adding something.

I also tried google-ing this problem and saw this:

http://www.coderanch.com/t/515475/JDBC/databases/sql-insert-statement-giving-sqlcode

How to convert interface{} to string?

You don't need to use a type assertion, instead just use the %v format specifier with Sprintf:

hostAndPort := fmt.Sprintf("%v:%v", arguments["<host>"], arguments["<port>"])

What is the proper way to check and uncheck a checkbox in HTML5?

Complementary answer to Robert's answer http://jsfiddle.net/ak9Sb/ in jQuery

When getting/setting checkbox state, one may encounter these phenomenons:

.trigger("click");

Does check an unchecked checkbox, but do not add the checked attribute. If you use triggers, do not try to get the state with "checked" attribute.

.attr("checked", "");

Does not uncheck the checkbox...

How to restrict user to type 10 digit numbers in input element?

try this

<input type="text" name="country_code" title="Error Message" pattern="[1-9]{1}[0-9]{9}"> 

This will ensure

  1. It is numeric
  2. It will be max of 10 chars
  3. First digit is not zero

How to set HTTP headers (for cache-control)?

You can set the headers in PHP by using:

<?php
  //set headers to NOT cache a page
  header("Cache-Control: no-cache, must-revalidate"); //HTTP 1.1
  header("Pragma: no-cache"); //HTTP 1.0
  header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past

  //or, if you DO want a file to cache, use:
  header("Cache-Control: max-age=2592000"); //30days (60sec * 60min * 24hours * 30days)

?>

Note that the exact headers used will depend on your needs (and if you need to support HTTP 1.0 and/or HTTP 1.1)

How to get the day of week and the month of the year?

You can look at datejs which parses the localized date output for example.

The formatting may look like this, in your example:

new Date().toString('dddd, d MMMM yyyy at HH:mm:ss') 

"string could not resolved" error in Eclipse for C++ (Eclipse can't resolve standard library)

Hello here is a simple solution,

Just go to File -> Convert to a C/C++ Autotools Project Select your project files appropriately.

Inclusions will be added to your project file

Why I'm getting 'Non-static method should not be called statically' when invoking a method in a Eloquent model?

Solution to the original question

You called a non-static method statically. To make a public function static in the model, would look like this:

public static function {
  
}

In General:

Post::get()

In this particular instance:

Post::take(2)->get()

One thing to be careful of, when defining relationships and scope, that I had an issue with that caused a 'non-static method should not be called statically' error is when they are named the same, for example:

public function category(){
    return $this->belongsTo('App\Category');
}

public function scopeCategory(){
    return $query->where('category', 1);
}

When I do the following, I get the non-static error:

Event::category()->get();

The issue, is that Laravel is using my relationship method called category, rather than my category scope (scopeCategory). This can be resolved by renaming the scope or the relationship. I chose to rename the relationship:

public function cat(){
    return $this->belongsTo('App\Category', 'category_id');
}

Please observe that I defined the foreign key (category_id) because otherwise Laravel would have looked for cat_id instead, and it wouldn't have found it, as I had defined it as category_id in the database.

LINQ query on a DataTable

You can use LINQ to objects on the Rows collection, like so:

var results = from myRow in myDataTable.Rows where myRow.Field("RowNo") == 1 select myRow;

Cannot connect to Database server (mysql workbench)

Try opening services.msc from the start menu search box and try manually starting the MySQL service or directly write services.msc in Run box

Unmarshaling nested JSON objects

What about anonymous fields? I'm not sure if that will constitute a "nested struct" but it's cleaner than having a nested struct declaration. What if you want to reuse the nested element elsewhere?

type NestedElement struct{
    someNumber int `json:"number"`
    someString string `json:"string"`
}

type BaseElement struct {
    NestedElement `json:"bar"`
}

Get width height of remote image from url

The w and h variables in img.onload function are not in the same scope with those in the getMeta() function. One way to do it, is as follows:

Fiddle: http://jsfiddle.net/ppanagi/28UES/2/

function getMeta(varA, varB) {
    if (typeof varB !== 'undefined') {
       alert(varA + ' width ' + varB + ' height');
    } else {
       var img = new Image();
       img.src = varA;
       img.onload = getMeta(this.width, this.height);
    }
}


getMeta("http://snook.ca/files/mootools_83_snookca.png");

How to install MySQLdb (Python data access library to MySQL) on Mac OS X?

A quick and easy way for Mac OS X 10.8 (Mountain Lion), 10.9 (Mavericks), 10.10 (Yosemite), and 10.11 (El Capitan):

I assume you have XCode, its command line tools, Python, and MySQL installed.

  1. Install PIP:

    sudo easy_install pip
    
  2. Edit ~/.profile: (Might not be necessary in Mac OS X 10.10)

    nano ~/.profile
    

    Copy and paste the following two line

    export PATH=/usr/local/mysql/bin:$PATH
    export DYLD_LIBRARY_PATH=/usr/local/mysql/lib/
    

    Save and exit. Afterwords execute the following command:

    source  ~/.profile
    
  3. Install MySQLdb

    sudo pip install MySQL-python
    

    To test if everything works fine just try

    python -c "import MySQLdb"
    

It worked like a charm for me. I hope it helps.

If you encounter an error regarding a missing library: Library not loaded: libmysqlclient.18.dylib then you have to symlink it to /usr/lib like so:

sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib 

How do I prevent Conda from activating the base environment by default?

This might be a bug of the recent anaconda. What works for me:

step1: vim /anaconda/bin/activate, it shows:

 #!/bin/sh                                                                                
 _CONDA_ROOT="/anaconda"
 # Copyright (C) 2012 Anaconda, Inc
 # SPDX-License-Identifier: BSD-3-Clause
 \. "$_CONDA_ROOT/etc/profile.d/conda.sh" || return $?
 conda activate "$@"

step2: comment out the last line: # conda activate "$@"

How to add directory to classpath in an application run profile in IntelliJ IDEA?

It appears that IntelliJ 11 has changed the method, and the checked answer no longer works for me. In case anyone else arrives here via a search engine, here's how I solved it in IntelliJ 11:

  1. Go to the Project Structure, click on Modules, and click on your Module
  2. Choose the "Dependencies" tab
  3. Click the "+" button on the right-hand side and select "Jars or directories..."
  4. Add the directory(ies) you want (note you can multi-select) and click OK
  5. In the dialog that comes up, select "classes" and NOT "jar directory"
  6. Make sure you're using that Module in your run target

Note that step 5 seems to be the key difference. If you select "jar directory" it will look exactly the same in the IDE but won't include the path at runtime. There appears to be no way to determine whether you've previously selected "classes" or "jar directory" after the fact.

How to set a primary key in MongoDB?

In mongodb _id field is reserved for primary key. Mongodb use an internal ObjectId value if you don't define it in your object and also create an index to ensure performance.

But you can put your own unique value for _id and Mongodb will use it instead of making one for you. And even if you want to use multiple field as primary key you can use an object:

{ _id : { a : 1, b: 1} }

Just be careful when creating these ids that the order of keys (a and b in the example) matters, if you swap them around, it is considered a different object.

Accessing variables from other functions without using global variables

I don't know specifics of your issue, but if the function needs the value then it can be a parameter passed through the call.

Globals are considered bad because globals state and multiple modifiers can create hard to follow code and strange errors. To many actors fiddling with something can create chaos.

How to split a string with angularJS

You may want to wrap that functionality up into a filter, this way you don't have to put the mySplit function in all of your controllers. For example

angular.module('myModule', [])
    .filter('split', function() {
        return function(input, splitChar, splitIndex) {
            // do some bounds checking here to ensure it has that index
            return input.split(splitChar)[splitIndex];
        }
    });

From here, you can use a filter as you originally intended

{{test | split:',':0}}
{{test | split:',':0}}

More info at http://docs.angularjs.org/guide/filter (thanks ross)

Plunkr @ http://plnkr.co/edit/NA4UeL

How does a hash table work?

Here's an explanation in layman's terms.

Let's assume you want to fill up a library with books and not just stuff them in there, but you want to be able to easily find them again when you need them.

So, you decide that if the person that wants to read a book knows the title of the book and the exact title to boot, then that's all it should take. With the title, the person, with the aid of the librarian, should be able to find the book easily and quickly.

So, how can you do that? Well, obviously you can keep some kind of list of where you put each book, but then you have the same problem as searching the library, you need to search the list. Granted, the list would be smaller and easier to search, but still you don't want to search sequentially from one end of the library (or list) to the other.

You want something that, with the title of the book, can give you the right spot at once, so all you have to do is just stroll over to the right shelf, and pick up the book.

But how can that be done? Well, with a bit of forethought when you fill up the library and a lot of work when you fill up the library.

Instead of just starting to fill up the library from one end to the other, you devise a clever little method. You take the title of the book, run it through a small computer program, which spits out a shelf number and a slot number on that shelf. This is where you place the book.

The beauty of this program is that later on, when a person comes back in to read the book, you feed the title through the program once more, and get back the same shelf number and slot number that you were originally given, and this is where the book is located.

The program, as others have already mentioned, is called a hash algorithm or hash computation and usually works by taking the data fed into it (the title of the book in this case) and calculates a number from it.

For simplicity, let's say that it just converts each letter and symbol into a number and sums them all up. In reality, it's a lot more complicated than that, but let's leave it at that for now.

The beauty of such an algorithm is that if you feed the same input into it again and again, it will keep spitting out the same number each time.

Ok, so that's basically how a hash table works.

Technical stuff follows.

First, there's the size of the number. Usually, the output of such a hash algorithm is inside a range of some large number, typically much larger than the space you have in your table. For instance, let's say that we have room for exactly one million books in the library. The output of the hash calculation could be in the range of 0 to one billion which is a lot higher.

So, what do we do? We use something called modulus calculation, which basically says that if you counted to the number you wanted (i.e. the one billion number) but wanted to stay inside a much smaller range, each time you hit the limit of that smaller range you started back at 0, but you have to keep track of how far in the big sequence you've come.

Say that the output of the hash algorithm is in the range of 0 to 20 and you get the value 17 from a particular title. If the size of the library is only 7 books, you count 1, 2, 3, 4, 5, 6, and when you get to 7, you start back at 0. Since we need to count 17 times, we have 1, 2, 3, 4, 5, 6, 0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 3, and the final number is 3.

Of course modulus calculation isn't done like that, it's done with division and a remainder. The remainder of dividing 17 by 7 is 3 (7 goes 2 times into 17 at 14 and the difference between 17 and 14 is 3).

Thus, you put the book in slot number 3.

This leads to the next problem. Collisions. Since the algorithm has no way to space out the books so that they fill the library exactly (or the hash table if you will), it will invariably end up calculating a number that has been used before. In the library sense, when you get to the shelf and the slot number you wish to put a book in, there's already a book there.

Various collision handling methods exist, including running the data into yet another calculation to get another spot in the table (double hashing), or simply to find a space close to the one you were given (i.e. right next to the previous book assuming the slot was available also known as linear probing). This would mean that you have some digging to do when you try to find the book later, but it's still better than simply starting at one end of the library.

Finally, at some point, you might want to put more books into the library than the library allows. In other words, you need to build a bigger library. Since the exact spot in the library was calculated using the exact and current size of the library, it goes to follow that if you resize the library you might end up having to find new spots for all the books since the calculation done to find their spots has changed.

I hope this explanation was a bit more down to earth than buckets and functions :)

PHP 5.4 Call-time pass-by-reference - Easy fix available?

You should be denoting the call by reference in the function definition, not the actual call. Since PHP started showing the deprecation errors in version 5.3, I would say it would be a good idea to rewrite the code.

From the documentation:

There is no reference sign on a function call - only on function definitions. Function definitions alone are enough to correctly pass the argument by reference. As of PHP 5.3.0, you will get a warning saying that "call-time pass-by-reference" is deprecated when you use & in foo(&$a);.

For example, instead of using:

// Wrong way!
myFunc(&$arg);               # Deprecated pass-by-reference argument
function myFunc($arg) { }

Use:

// Right way!
myFunc($var);                # pass-by-value argument
function myFunc(&$arg) { }

Setting DIV width and height in JavaScript

Be careful of span!

myspan.styles.width='100px' doesn't want to work.

Change the span to a div.

How to programmatically set the Image source

Use asp:image

<asp:Image id="Image1" runat="server"
           AlternateText="Image text"
           ImageAlign="left"
           ImageUrl="images/image1.jpg"/>

and codebehind to change image url

Image1.ImageUrl = "/MyProject;component/Images/down.png"; 

Collectors.toMap() keyMapper -- more succinct expression?

We can use an optional merger function also in case of same key collision. For example, If two or more persons have the same getLast() value, we can specify how to merge the values. If we not do this, we could get IllegalStateException. Here is the example to achieve this...

Map<String, Person> map = 
roster
    .stream()
    .collect(
        Collectors.toMap(p -> p.getLast(),
                         p -> p,
                         (person1, person2) -> person1+";"+person2)
    );

What is the "proper" way to cast Hibernate Query.list() to List<Type>?

The proper way is to use Hibernate Transformers:

public class StudentDTO {
private String studentName;
private String courseDescription;

public StudentDTO() { }  
...
} 

.

List resultWithAliasedBean = s.createSQLQuery(
"SELECT st.name as studentName, co.description as courseDescription " +
"FROM Enrolment e " +
"INNER JOIN Student st on e.studentId=st.studentId " +
"INNER JOIN Course co on e.courseCode=co.courseCode")
.setResultTransformer( Transformers.aliasToBean(StudentDTO.class))
.list();

StudentDTO dto =(StudentDTO) resultWithAliasedBean.get(0);

Iterating througth Object[] is redundant and would have some performance penalty. Detailed information about transofrmers usage you will find here: Transformers for HQL and SQL

If you are looking for even more simple solution you can use out-of-the-box-map-transformer:

List iter = s.createQuery(
"select e.student.name as studentName," +
"       e.course.description as courseDescription" +
"from   Enrolment as e")
.setResultTransformer( Transformers.ALIAS_TO_ENTITY_MAP )
.iterate();

String name = (Map)(iter.next()).get("studentName");

Java: object to byte[] and byte[] to object converter (for Tokyo Cabinet)

public static byte[] serialize(Object obj) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ObjectOutputStream os = new ObjectOutputStream(out);
    os.writeObject(obj);
    return out.toByteArray();
}
public static Object deserialize(byte[] data) throws IOException, ClassNotFoundException {
    ByteArrayInputStream in = new ByteArrayInputStream(data);
    ObjectInputStream is = new ObjectInputStream(in);
    return is.readObject();
}

Google Maps API v3 adding an InfoWindow to each marker

You can use this in event:

google.maps.event.addListener(marker, 'click', function() {  
    // this = marker
    var marker_map = this.getMap();
    this.info.open(marker_map);
    // this.info.open(marker_map, this);
    // Note: If you call open() without passing a marker, the InfoWindow will use the position specified upon construction through the InfoWindowOptions object literal.
});

Update one MySQL table with values from another

It depends what is a use of those tables, but you might consider putting trigger on original table on insert and update. When insert or update is done, update the second table based on only one item from the original table. It will be quicker.

Getting a list of values from a list of dicts

[x['value'] for x in list_of_dicts]

Adb over wireless without usb cable at all for not rooted phones

type in Windows cmd.exe

    cd %userprofile%\.android
    dir
    copy adbkey.pub adb_keys
    dir

copy the file adb_keys to your phone folder /data/misc/adb. Reboot the phone. RSA Key is now authorized.

from: How to solve ADB device unauthorized in Android ADB host device?

now follow the instructions for adb connect, or use any app for preparing. i prefer ADB over WIFI Widget from Mehdy Bohlool, it works without root.

from: How can I connect to Android with ADB over TCP?

Get specific ArrayList item

You can simply get your answer from ArrayList API doc.

Please always refer API documentation .. it helps

Your call will looklike following :

mainList.get(3);

Here is simple tutorial for understanding ArrayList with Basics :) :

http://www.javadeveloper.co.in/java/java-arraylist-tutorial.html

Are there any Open Source alternatives to Crystal Reports?

So far based on my research JasperSoft has turned out promising open source reporting tool… Matter of fact I am currently working on a huge project wherein I have started converting and building reports using JasperReports/iReports…

Every reporting tool has its own learning curve. The support group from and for Jasper and the quality of response that I have gotten so far is good.

Again at the end of the day it all comes down to what your business / organization needs.

To show only file name without the entire directory path

you could add an sed script to your commandline:

ls /home/user/new/*.txt | sed -r 's/^.+\///'

Open CSV file via VBA (performance)

I have the same issue, I'm not able to open a CSV file in Excel. I've found a solution that worked for me in this question Opening a file in excel via Workbooks.OpenText

That question helped me to figure out a code that works for me. The code looks more or less like this:

Private Sub OpenCSVFile(filename as String)
    Dim datasourceFilename As String
    Dim currentPath As String

    datasourceFilename = "\" & filename & ".csv"
    currentPath = ActiveWorkbook.Path

    Workbooks.OpenText Filename:=currentPath & datasourceFilename, _
                       Origin:=xlWindows, _
                       StartRow:=1, _
                       DataType:=xlDelimited, _
                       TextQualifier:=xlDoubleQuote, _
                       ConsecutiveDelimiter:=False, _
                       Tab:=False, _
                       Semicolon:=False, _
                       Comma:=True, _
                       Space:=False, _
                       Other:=False, _
                       FieldInfo:=Array(Array(1, 1), Array(2, 1)), _
                       DecimalSeparator:=".", _
                       ThousandsSeparator:=",", _
                       TrailingMinusNumbers:=True
End Sub

At least, it helped me to know about lots of parameters I can use with Workbooks.OpenText method.

How to get a view table query (code) in SQL Server 2008 Management Studio

if i understood you can do the following

Right Click on View Name in SQL Server Management Studio -> Script View As ->CREATE To ->New Query Window

Access item in a list of lists

List1 = [[10,-13,17],[3,5,1],[13,11,12]]

num = 50
for i in List1[0]:num -= i
print num

ASP.NET: Session.SessionID changes between requests

In my case I figured out that the session cookie had a domain that included www. prefix, while I was requesting page with no www..
Adding www. to the URL immediately fixed the problem. Later I changed cookie's domain to be set to .mysite.com instead of www.mysite.com.

How do I create a comma delimited string from an ArrayList?

The solutions so far are all quite complicated. The idiomatic solution should doubtless be:

String.Join(",", x.Cast(Of String)().ToArray())

There's no need for fancy acrobatics in new framework versions. Supposing a not-so-modern version, the following would be easiest:

Console.WriteLine(String.Join(",", CType(x.ToArray(GetType(String)), String())))

mspmsp's second solution is a nice approach as well but it's not working because it misses the AddressOf keyword. Also, Convert.ToString is rather inefficient (lots of unnecessary internal evaluations) and the Convert class is generally not very cleanly designed. I tend to avoid it, especially since it's completely redundant.

Handling optional parameters in javascript

I think you want to use typeof() here:

function f(id, parameters, callback) {
  console.log(typeof(parameters)+" "+typeof(callback));
}

f("hi", {"a":"boo"}, f); //prints "object function"
f("hi", f, {"a":"boo"}); //prints "function object"

how to evenly distribute elements in a div next to each other?

This is the quick and easy way to do it

<div>
    <span>Span 1</span>
    <span>Span 2</span>
    <span>Span 3</span>
</div>

css

div{
    width:100%;
}
span{
    display:inline-block;    
    width:33%;
    text-align:center;
}

Then adjust the width of the spans for the number you have.

Example: http://jsfiddle.net/jasongennaro/wvJxD/

Installing Apache Maven Plugin for Eclipse

Eclipse > Help > Eclipse Marketplace...

Search for m2e

Install Maven Integration for Eclipse (Juno and newer). [It works for Indigo also]

"No backupset selected to be restored" SQL Server 2012

Run SQL Server Management Studio as an administrator (right-click the shortcut/exe, then select "Run as Administrator"), then try to restore.

Origin is not allowed by Access-Control-Allow-Origin

When you receive the request you can

var origin = (req.headers.origin || "*");

than when you have to response go with something like that:

res.writeHead(
    206,
    {
        'Access-Control-Allow-Credentials': true,
        'Access-Control-Allow-Origin': origin,
    }
);

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details

While you are in debug mode within the catch {...} block open up the "QuickWatch" window (ctrl+alt+q) and paste in there:

((System.Data.Entity.Validation.DbEntityValidationException)ex).EntityValidationErrors

or:

((System.Data.Entity.Validation.DbEntityValidationException)$exception).EntityValidationErrors

If you are not in a try/catch or don't have access to the exception object.

This will allow you to drill down into the ValidationErrors tree. It's the easiest way I've found to get instant insight into these errors.

How to get the HTML's input element of "file" type to only accept pdf files?

To get the HTML file input form element to only accept PDFs, you can use the accept attribute in modern browsers such as Firefox 9+, Chrome 16+, Opera 11+ and IE10+ like such:

<input name="file1" type="file" accept="application/pdf">

You can string together multiple mime types with a comma.

The following string will accept JPG, PNG, GIF, PDF, and EPS files:

<input name="foo" type="file" accept="image/jpeg,image/gif,image/png,application/pdf,image/x-eps">

In older browsers the native OS file dialog cannot be restricted – you'd have to use Flash or a Java applet or something like that to handle the file transfer.

And of course it goes without saying that this doesn't do anything to verify the validity of the file type. You'll do that on the server-side once the file has uploaded.

A little update – with javascript and the FileReader API you could do more validation client-side before uploading huge files to your server and checking them again.

Settings to Windows Firewall to allow Docker for Windows to share drive

For Windows 10 machines on domain networks, when creating the Hyper-V virtual Ethernet adapter, it gets categorized as a public network. You have to change it to a private network to allow the more relaxed Windows Firewall rules, and therefore allow file sharing.

Run the following command in PowerShell:

Set-NetConnectionProfile -interfacealias "vEthernet (DockerNAT)" -NetworkCategory Private

Change the name in quotes if your machine's virtual Hyper-V network connection is called something else.

Can (a== 1 && a ==2 && a==3) ever evaluate to true?

Same, but different, but still same (can be "tested" multiple times):

_x000D_
_x000D_
const a = { valueOf: () => this.n = (this.n || 0) % 3 + 1}_x000D_
    _x000D_
if(a == 1 && a == 2 && a == 3) {_x000D_
  console.log('Hello World!');_x000D_
}_x000D_
_x000D_
if(a == 1 && a == 2 && a == 3) {_x000D_
  console.log('Hello World!');_x000D_
}
_x000D_
_x000D_
_x000D_

My idea started from how Number object type equation works.

How to Troubleshoot Intermittent SQL Timeout Errors

I've seen similar problems happen if anti-virus was installed on the SQL server. The AV's auto-update features were clocking the server and not allowing enough CPU for SQL Server.

Also, have you put a small application on the SQL server itself that verifies that connections can be made or runs very basic SQL like "SELECT GETDATE();"? This would eliminate network possibilities.

Can't ping a local VM from the host

The issue could be that the VM is connected to the network via NAT. You need to set the network adapter of the VM to a bridged connection so that the VM will get it's own IP within the actual network and not on the LAN on the host.

What is "entropy and information gain"?

I assume entropy was mentioned in the context of building decision trees.

To illustrate, imagine the task of learning to classify first-names into male/female groups. That is given a list of names each labeled with either m or f, we want to learn a model that fits the data and can be used to predict the gender of a new unseen first-name.

name       gender
-----------------        Now we want to predict 
Ashley        f              the gender of "Amro" (my name)
Brian         m
Caroline      f
David         m

First step is deciding what features of the data are relevant to the target class we want to predict. Some example features include: first/last letter, length, number of vowels, does it end with a vowel, etc.. So after feature extraction, our data looks like:

# name    ends-vowel  num-vowels   length   gender
# ------------------------------------------------
Ashley        1         3           6        f
Brian         0         2           5        m
Caroline      1         4           8        f
David         0         2           5        m

The goal is to build a decision tree. An example of a tree would be:

length<7
|   num-vowels<3: male
|   num-vowels>=3
|   |   ends-vowel=1: female
|   |   ends-vowel=0: male
length>=7
|   length=5: male

basically each node represent a test performed on a single attribute, and we go left or right depending on the result of the test. We keep traversing the tree until we reach a leaf node which contains the class prediction (m or f)

So if we run the name Amro down this tree, we start by testing "is the length<7?" and the answer is yes, so we go down that branch. Following the branch, the next test "is the number of vowels<3?" again evaluates to true. This leads to a leaf node labeled m, and thus the prediction is male (which I happen to be, so the tree predicted the outcome correctly).

The decision tree is built in a top-down fashion, but the question is how do you choose which attribute to split at each node? The answer is find the feature that best splits the target class into the purest possible children nodes (ie: nodes that don't contain a mix of both male and female, rather pure nodes with only one class).

This measure of purity is called the information. It represents the expected amount of information that would be needed to specify whether a new instance (first-name) should be classified male or female, given the example that reached the node. We calculate it based on the number of male and female classes at the node.

Entropy on the other hand is a measure of impurity (the opposite). It is defined for a binary class with values a/b as:

Entropy = - p(a)*log(p(a)) - p(b)*log(p(b))

This binary entropy function is depicted in the figure below (random variable can take one of two values). It reaches its maximum when the probability is p=1/2, meaning that p(X=a)=0.5 or similarlyp(X=b)=0.5 having a 50%/50% chance of being either a or b (uncertainty is at a maximum). The entropy function is at zero minimum when probability is p=1 or p=0 with complete certainty (p(X=a)=1 or p(X=a)=0 respectively, latter implies p(X=b)=1).

https://en.wikipedia.org/wiki/File:Binary_entropy_plot.svg

Of course the definition of entropy can be generalized for a discrete random variable X with N outcomes (not just two):

entropy

(the log in the formula is usually taken as the logarithm to the base 2)


Back to our task of name classification, lets look at an example. Imagine at some point during the process of constructing the tree, we were considering the following split:

     ends-vowel
      [9m,5f]          <--- the [..,..] notation represents the class
    /          \            distribution of instances that reached a node
   =1          =0
 -------     -------
 [3m,4f]     [6m,1f]

As you can see, before the split we had 9 males and 5 females, i.e. P(m)=9/14 and P(f)=5/14. According to the definition of entropy:

Entropy_before = - (5/14)*log2(5/14) - (9/14)*log2(9/14) = 0.9403

Next we compare it with the entropy computed after considering the split by looking at two child branches. In the left branch of ends-vowel=1, we have:

Entropy_left = - (3/7)*log2(3/7) - (4/7)*log2(4/7) = 0.9852

and the right branch of ends-vowel=0, we have:

Entropy_right = - (6/7)*log2(6/7) - (1/7)*log2(1/7) = 0.5917

We combine the left/right entropies using the number of instances down each branch as weight factor (7 instances went left, and 7 instances went right), and get the final entropy after the split:

Entropy_after = 7/14*Entropy_left + 7/14*Entropy_right = 0.7885

Now by comparing the entropy before and after the split, we obtain a measure of information gain, or how much information we gained by doing the split using that particular feature:

Information_Gain = Entropy_before - Entropy_after = 0.1518

You can interpret the above calculation as following: by doing the split with the end-vowels feature, we were able to reduce uncertainty in the sub-tree prediction outcome by a small amount of 0.1518 (measured in bits as units of information).

At each node of the tree, this calculation is performed for every feature, and the feature with the largest information gain is chosen for the split in a greedy manner (thus favoring features that produce pure splits with low uncertainty/entropy). This process is applied recursively from the root-node down, and stops when a leaf node contains instances all having the same class (no need to split it further).

Note that I skipped over some details which are beyond the scope of this post, including how to handle numeric features, missing values, overfitting and pruning trees, etc..

Prolog "or" operator, query

Just another viewpoint. Performing an "or" in Prolog can also be done with the "disjunct" operator or semi-colon:

registered(X, Y) :-
    X = ct101; X = ct102; X = ct103.

For a fuller explanation:

Predicate control in Prolog

Can I use an HTML input type "date" to collect only a year?

No you can not but you may want to use input type number as a workaround. Look at the following example:

<input type="number" min="1900" max="2099" step="1" value="2016" />

How do I debug Node.js applications?

Enable VS Code preference Auto Attach from File -> Preferences -> Settings -> Search for Auto Attach and set it On, open the console (ctrl + *) or from the menu Terminal -> New Terminal, set a breakpoint in your code, type in the command

node --inspect <name of your file>

This will start the debugging and the VS Code will show the Debug menu.

Note: Auto Attach is also very helpful if you are working with node cluster worker threads.

Angular2 disable button

If you are using reactive forms and want to disable some input associated with a form control, you should place this disabled logic into you code and call yourFormControl.disable() or yourFormControl.enable()

How to extract a substring using regex

Because you also ticked Scala, a solution without regex which easily deals with multiple quoted strings:

val text = "some string with 'the data i want' inside 'and even more data'"
text.split("'").zipWithIndex.filter(_._2 % 2 != 0).map(_._1)

res: Array[java.lang.String] = Array(the data i want, and even more data)

Run a controller function whenever a view is opened/shown

Following up on the answer and link from AlexMart, something like this works:

.controller('MyCtrl', function($scope) {
  $scope.$on('$ionicView.enter', function() {
     // Code you want executed every time view is opened
     console.log('Opened!')
  })
})

Rendering a template variable as HTML

If you don't want the HTML to be escaped, look at the safe filter and the autoescape tag:

safe:

{{ myhtml |safe }}

autoescape:

{% autoescape off %}
    {{ myhtml }}
{% endautoescape %}

How to set an image's width and height without stretching it?

You can use as below :

_x000D_
_x000D_
.width100 {_x000D_
  max-width: 100px;_x000D_
  height: 100px;_x000D_
  width: auto;_x000D_
  border: solid red;_x000D_
}
_x000D_
<img src="https://www.gravatar.com/avatar/dc48e9b92e4210d7a3131b3ef46eb8b1?s=512&d=identicon&r=PG" class="width100" />
_x000D_
_x000D_
_x000D_

How to programmatically get iOS status bar height

Swift 5

UIApplication.shared.statusBarFrame.height

How to set selected value on select using selectpicker plugin from bootstrap

The value is correctly selected, but you didn't see it because the plugin hide the real select and show a button with an unordered list, so, if you want that the user see the selected value on the select you can do something like this:

//Get the text using the value of select
var text = $("select[name=selValue] option[value='1']").text();
//We need to show the text inside the span that the plugin show
$('.bootstrap-select .filter-option').text(text);
//Check the selected attribute for the real select
$('select[name=selValue]').val(1);

Edit:

Like @blushrt points out, a better solution is:

$('select[name=selValue]').val(1);
$('.selectpicker').selectpicker('refresh')

Edit 2:

To select multiple values, pass the values as an array.

Accessing private member variables from prototype-defined functions

I know it has been more than 1 decade since this was was asked, but I just put my thinking on this for the n-th time in my programmer life, and found a possible solution that I don't know if I entirely like yet. I have not seen this methodology documented before, so I will name it the "private/public dollar pattern" or _$ / $ pattern.

var ownFunctionResult = this.$("functionName"[, arg1[, arg2 ...]]);
var ownFieldValue = this._$("fieldName"[, newValue]);

var objectFunctionResult = objectX.$("functionName"[, arg1[, arg2 ...]]);

//Throws an exception. objectX._$ is not defined
var objectFieldValue = objectX._$("fieldName"[, newValue]);

The concept uses a ClassDefinition function that returns a Constructor function that returns an Interface object. The interface's only method is $ which receives a name argument to invoke the corresponding function in the constructor object, any additional arguments passed after name are passed in the invocation.

The globally-defined helper function ClassValues stores all fields in an object as needed. It defines the _$ function to access them by name. This follows a short get/set pattern so if value is passed, it will be used as the new variable value.

var ClassValues = function (values) {
  return {
    _$: function _$(name, value) {
      if (arguments.length > 1) {
        values[name] = value;
      }

      return values[name];
    }
  };
};

The globally defined function Interface takes an object and a Values object to return an _interface with one single function $ that examines obj to find a function named after the parameter name and invokes it with values as the scoped object. The additional arguments passed to $ will be passed on the function invocation.

var Interface = function (obj, values, className) {
  var _interface = {
    $: function $(name) {
      if (typeof(obj[name]) === "function") {
        return obj[name].apply(values, Array.prototype.splice.call(arguments, 1));
      }

      throw className + "." + name + " is not a function.";
    }
  };

  //Give values access to the interface.
  values.$ = _interface.$;

  return _interface;
};

In the sample below, ClassX is assigned to the result of ClassDefinition, which is the Constructor function. Constructor may receive any number of arguments. Interface is what external code gets after calling the constructor.

var ClassX = (function ClassDefinition () {
  var Constructor = function Constructor (valA) {
    return Interface(this, ClassValues({ valA: valA }), "ClassX");
  };

  Constructor.prototype.getValA = function getValA() {
    //private value access pattern to get current value.
    return this._$("valA");
  };

  Constructor.prototype.setValA = function setValA(valA) {
    //private value access pattern to set new value.
    this._$("valA", valA);
  };

  Constructor.prototype.isValAValid = function isValAValid(validMessage, invalidMessage) {
    //interface access pattern to call object function.
    var valA = this.$("getValA");

    //timesAccessed was not defined in constructor but can be added later...
    var timesAccessed = this._$("timesAccessed");

    if (timesAccessed) {
      timesAccessed = timesAccessed + 1;
    } else {
      timesAccessed = 1;
    }

    this._$("timesAccessed", timesAccessed);

    if (valA) {
      return "valA is " + validMessage + ".";
    }

    return "valA is " + invalidMessage + ".";
  };

  return Constructor;
}());

There is no point in having non-prototyped functions in Constructor, although you could define them in the constructor function body. All functions are called with the public dollar pattern this.$("functionName"[, param1[, param2 ...]]). The private values are accessed with the private dollar pattern this._$("valueName"[, replacingValue]);. As Interface does not have a definition for _$, the values cannot be accessed by external objects. Since each prototyped function body's this is set to the values object in function $, you will get exceptions if you call Constructor sibling functions directly; the _$ / $ pattern needs to be followed in prototyped function bodies too. Below sample usage.

var classX1 = new ClassX();
console.log("classX1." + classX1.$("isValAValid", "valid", "invalid"));
console.log("classX1.valA: " + classX1.$("getValA"));
classX1.$("setValA", "v1");
console.log("classX1." + classX1.$("isValAValid", "valid", "invalid"));
var classX2 = new ClassX("v2");
console.log("classX1.valA: " + classX1.$("getValA"));
console.log("classX2.valA: " + classX2.$("getValA"));
//This will throw an exception
//classX1._$("valA");

And the console output.

classX1.valA is invalid.
classX1.valA: undefined
classX1.valA is valid.
classX1.valA: v1
classX2.valA: v2

The _$ / $ pattern allows full privacy of values in fully-prototyped classes. I don't know if I will ever use this, nor if it has flaws, but hey, it was a good puzzle!

Customizing the template within a Directive

angular.module('formComponents', [])
  .directive('formInput', function() {
    return {
        restrict: 'E',
        compile: function(element, attrs) {
            var type = attrs.type || 'text';
            var required = attrs.hasOwnProperty('required') ? "required='required'" : "";
            var htmlText = '<div class="control-group">' +
                '<label class="control-label" for="' + attrs.formId + '">' + attrs.label + '</label>' +
                    '<div class="controls">' +
                    '<input type="' + type + '" class="input-xlarge" id="' + attrs.formId + '" name="' + attrs.formId + '" ' + required + '>' +
                    '</div>' +
                '</div>';
            element.replaceWith(htmlText);
        }
    };
})

How to change CSS using jQuery?

_x000D_
_x000D_
$(function(){ _x000D_
$('.bordered').css({_x000D_
"border":"1px solid #EFEFEF",_x000D_
"margin":"0 auto",_x000D_
"width":"80%"_x000D_
});_x000D_
_x000D_
$('h1').css({_x000D_
"margin-left":"10px"_x000D_
});_x000D_
_x000D_
$('#myParagraph').css({_x000D_
"margin-left":"10px",_x000D_
"font-family":"sans-serif"_x000D_
});_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>_x000D_
<div class="bordered">_x000D_
<h1>Header</h1>_x000D_
<p id="myParagraph">This is some paragraph text</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to make readonly all inputs in some div in Angular2?

All inputs should be replaced with custom directive that reads a single global variable to toggle readonly status.

// template
<your-input [readonly]="!childmessage"></your-input>

// component value
childmessage = false;

How to analyze information from a Java core dump?

IBM provide a number of tools which can be used on the sun jvm as well. Take a look at some of the projects on alphaworks, they provide a heap and thread dump analyzers

Karl

How to scroll HTML page to given anchor?

A pure javascript solution without JQuery. Tested on Chrome & I.e, not tested on IOS

function ScrollTo(name) {
  ScrollToResolver(document.getElementById(name));
}

function ScrollToResolver(elem) {
  var jump = parseInt(elem.getBoundingClientRect().top * .2);
  document.body.scrollTop += jump;
  document.documentElement.scrollTop += jump;
  if (!elem.lastjump || elem.lastjump > Math.abs(jump)) {
    elem.lastjump = Math.abs(jump);
    setTimeout(function() { ScrollToResolver(elem);}, "100");
  } else {
    elem.lastjump = null;
  }
}

demo: https://jsfiddle.net/jd7q25hg/12/

How to extract or unpack an .ab file (Android Backup file)

I have had to unpack a .ab-file, too and found this post while looking for an answer. My suggested solution is Android Backup Extractor, a free Java tool for Windows, Linux and Mac OS.

Make sure to take a look at the README, if you encounter a problem. You might have to download further files, if your .ab-file is password-protected.

Usage:
java -jar abe.jar [-debug] [-useenv=yourenv] unpack <backup.ab> <backup.tar> [password]

Example:

Let's say, you've got a file test.ab, which is not password-protected, you're using Windows and want the resulting .tar-Archive to be called test.tar. Then your command should be:

java.exe -jar abe.jar unpack test.ab test.tar ""

java.lang.ClassNotFoundException: org.apache.xmlbeans.XmlObject Error

I was working with talend V7.3.1 and I had poi version "4.1.0" and including xml-beans from the list of dependencies didnt fix my problem (i.e: 2.3.0 and 2.6.0).

It was fixed by downloading the jar "xmlbeans-3.0.1.jar" and adding it to the project

enter image description here

How do I address unchecked cast warnings?

A quick guess if you post your code can say for sure but you might have done something along the lines of

HashMap<String, Object> test = new HashMap();

which will produce the warning when you need to do

HashMap<String, Object> test = new HashMap<String, Object>();

it might be worth looking at

Generics in the Java Programming Language

if your unfamiliar with what needs to be done.

Imply bit with constant 1 or 0 in SQL Server

Enjoy this :) Without cast each value individually.

SELECT ...,
  IsCoursedBased = CAST(
      CASE WHEN fc.CourseId is not null THEN 1 ELSE 0 END
    AS BIT
  )
FROM fc

How to select first parent DIV using jQuery?

Use .closest(), which gets the first ancestor element that matches the given selector 'div':

var classes = $(this).closest('div').attr('class').split(' ');

EDIT:

As @Shef noted, .closest() will return the current element if it happens to be a DIV also. To take that into account, use .parent() first:

var classes = $(this).parent().closest('div').attr('class').split(' ');

Android SDK installation doesn't find JDK

Yeah install the 32 bit version of the Java SE SDK (or any of the combinations). That should help solve your problem.

How to link a folder with an existing Heroku app

Two things to take care while setting up a new deployment System for old App

1. To check your app access to Heroku (especially the app)

heroku apps

it will list the apps you have access to if you set up for the first time, you probably need to

heroku keys:add

2. Then set up your git remote

For already created Heroku app, you can easily add a remote to your local repository with the heroku git: remote command. All you need is your Heroku app’s name:

heroku git:remote -a appName

you can also rename your remotes with the git remote rename command:

git remote rename heroku heroku-dev(you desired app name)

then You can use the git remote command to confirm that a remote been set for your app

 git remote -v

What's the difference between REST & RESTful

A "REST service" and a "RESTful service" are one and the same.

A RESTful system is any system that follows the REST conventions as defined in the original document that created the idea of RESTful networked applications.

It's worth noting there are varying levels of RESTfulness. Overall, REST is a style, not a standard, so there is room for interpretation based on needs. one example is hierarchical resource URLs (e.g. /things/ID/relatedthings) vs flat URLs (e.g. /things/ID and /relatedthings?thing=ID)

"The POM for ... is missing, no dependency information available" even though it exists in Maven Repository

I had a similar problem quite recently. In my case:

  1. I downloaded an artifact from some less popular Maven repo

  2. This repo dissappeared over this year

  3. Now builds fail, even if I have this artifact and its pom.xml in my local repo

Workaround:

delete _remote.repositories file in your local repo, where this artifact resides. Now the project builds.

Images can't contain alpha channels or transparencies

To get around the problem I batched converted using fireworks my png32 files to png24 for upload quick and easy. Jpeg works also but it is lossy.

Make an existing Git branch track a remote branch?

For git version 2.25.1, use the command:

git push --set-upstream origin <local_branch_name>

SELECT list is not in GROUP BY clause and contains nonaggregated column

country.code is not in your group by statement, and is not an aggregate (wrapped in an aggregate function).

https://www.w3schools.com/sql/sql_ref_sqlserver.asp

JavaScript module pattern with example

Here https://toddmotto.com/mastering-the-module-pattern you can find the pattern thoroughly explained. I would add that the second thing about modular JavaScript is how to structure your code in multiple files. Many folks may advice you here to go with AMD, yet I can say from experience that you will end up on some point with slow page response because of numerous HTTP requests. The way out is pre-compilation of your JavaScript modules (one per file) into a single file following CommonJS standard. Take a look at samples here http://dsheiko.github.io/cjsc/

Excel: replace part of cell's string value

what you're looking for is SUBSTITUTE:

=SUBSTITUTE(A2,"Author","Authoring")

Will substitute Author for Authoring without messing with everything else

Good Linux (Ubuntu) SVN client

If you use eclipse, subclipse is the best I've ever used. In my opinion, this should exist as stand-alone as well... Easy to use, linked with the code and the project you have in eclipse... Just perfect for a developer who uses eclipse and wants a gui.

Personally, I prefer the command-line client, both for linux and windows.

Edit: if you use XFCE and its file manager (called Thunar), there's a plugin which works quite well. If I don't want to open the terminal, I just use that one, it has all the functionality, is fast and easy to use. There's also one for git included, though...

Search for a string in all tables, rows and columns of a DB

This query can do the thing for you.

DECLARE
@search_string  VARCHAR(100),
@table_name     SYSNAME,
@table_id       INT,
@column_name    SYSNAME,
@sql_string     VARCHAR(2000)

SET @search_string = 'StringtoSearch'

DECLARE tables_cur CURSOR FOR SELECT ss.name +'.'+ so.name [name], object_id FROM sys.objects so INNER JOIN sys.schemas ss ON so.schema_id = ss.schema_id WHERE  type = 'U'

OPEN tables_cur

FETCH NEXT FROM tables_cur INTO @table_name, @table_id

WHILE (@@FETCH_STATUS = 0)
BEGIN
    DECLARE columns_cur CURSOR FOR SELECT name FROM sys.columns WHERE object_id = @table_id 
        AND system_type_id IN (167, 175, 231, 239, 99)

    OPEN columns_cur

    FETCH NEXT FROM columns_cur INTO @column_name
        WHILE (@@FETCH_STATUS = 0)
        BEGIN
            SET @sql_string = 'IF EXISTS (SELECT * FROM ' + @table_name + ' WHERE [' + @column_name + '] 
            LIKE ''%' + @search_string + '%'') PRINT ''' + @table_name + ', ' + @column_name + ''''

            EXECUTE(@sql_string)

        FETCH NEXT FROM columns_cur INTO @column_name
        END

    CLOSE columns_cur

DEALLOCATE columns_cur

FETCH NEXT FROM tables_cur INTO @table_name, @table_id
END

CLOSE tables_cur
DEALLOCATE tables_cur

how to emulate "insert ignore" and "on duplicate key update" (sql merge) with postgresql?

To get the insert ignore logic you can do something like below. I found simply inserting from a select statement of literal values worked best, then you can mask out the duplicate keys with a NOT EXISTS clause. To get the update on duplicate logic I suspect a pl/pgsql loop would be necessary.

INSERT INTO manager.vin_manufacturer
(SELECT * FROM( VALUES
  ('935',' Citroën Brazil','Citroën'),
  ('ABC', 'Toyota', 'Toyota'),
  ('ZOM',' OM','OM')
  ) as tmp (vin_manufacturer_id, manufacturer_desc, make_desc)
  WHERE NOT EXISTS (
    --ignore anything that has already been inserted
    SELECT 1 FROM manager.vin_manufacturer m where m.vin_manufacturer_id = tmp.vin_manufacturer_id)
)

Send inline image in email

I added the complete code below to display images in Gmail,Thunderbird and other email clients :

MailMessage mailWithImg = getMailWithImg();
MySMTPClient.Send(mailWithImg); //* Set up your SMTPClient before!

private MailMessage getMailWithImg()
{
    MailMessage mail = new MailMessage();
    mail.IsBodyHtml = true;
    mail.AlternateViews.Add(getEmbeddedImage("c:/image.png"));
    mail.From = new MailAddress("yourAddress@yourDomain");
    mail.To.Add("recipient@hisDomain");
    mail.Subject = "yourSubject";
    return mail;
}
private AlternateView getEmbeddedImage(String filePath)
 {
    // below line was corrected to include the mediatype so it displays in all 
    // mail clients. previous solution only displays in Gmail the inline images 
    LinkedResource res = new LinkedResource(filePath, MediaTypeNames.Image.Jpeg);  
    res.ContentId = Guid.NewGuid().ToString();
    string htmlBody = @"<img src='cid:" + res.ContentId + @"'/>";
    AlternateView alternateView = AlternateView.CreateAlternateViewFromString(htmlBody,  
     null, MediaTypeNames.Text.Html);
    alternateView.LinkedResources.Add(res);
    return alternateView;
}

how to insert date and time in oracle?

You are doing everything right by using a to_date function and specifying the time. The time is there in the database. The trouble is just that when you select a column of DATE datatype from the database, the default format mask doesn't show the time. If you issue a

alter session set nls_date_format = 'dd/MON/yyyy hh24:mi:ss'

or something similar including a time component, you will see that the time successfully made it into the database.

How do I revert a Git repository to a previous commit?

I couldn't revert mine manually for some reason so here is how I ended up doing it.

  1. Checked out the branch I wanted to have, copied it.
  2. Checked out the latest branch.
  3. Copied the contents from the branch I wanted to the latest branch's directory overwriting the changes and committing that.

Xcode swift am/pm time to 24 hour format

Below is the swift 3 version of the solution -

let dateAsString = "6:35:58 PM"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "h:mm:ss a"
let date = dateFormatter.date(from: dateAsString)

dateFormatter.dateFormat = "HH:mm:ss"
let date24 = dateFormatter.string(from: date!)
print(date24)

How do I authenticate a WebClient request?

Public Function getWeb(ByRef sURL As String) As String
    Dim myWebClient As New System.Net.WebClient()

    Try
        Dim myCredentialCache As New System.Net.CredentialCache()
        Dim myURI As New Uri(sURL)
        myCredentialCache.Add(myURI, "ntlm", System.Net.CredentialCache.DefaultNetworkCredentials)
        myWebClient.Encoding = System.Text.Encoding.UTF8
        myWebClient.Credentials = myCredentialCache
        Return myWebClient.DownloadString(myURI)
    Catch ex As Exception
        Return "Exception " & ex.ToString()
    End Try
End Function

How can I use NSError in my iPhone App?

Great answer Alex. One potential issue is the NULL dereference. Apple's reference on Creating and Returning NSError objects

...
[details setValue:@"ran out of money" forKey:NSLocalizedDescriptionKey];

if (error != NULL) {
    // populate the error object with the details
    *error = [NSError errorWithDomain:@"world" code:200 userInfo:details];
}
// we couldn't feed the world's children...return nil..sniffle...sniffle
return nil;
...

Apply style to parent if it has child with css

It's not possible with CSS3. There is a proposed CSS4 selector, $, to do just that, which could look like this (Selecting the li element):

ul $li ul.sub { ... }

See the list of CSS4 Selectors here.

As an alternative, with jQuery, a one-liner you could make use of would be this:

$('ul li:has(ul.sub)').addClass('has_sub');

You could then go ahead and style the li.has_sub in your CSS.

How to format code in Xcode?

I would suggest taking a look JetBrains AppCode IDE. It has a Reformat Code command. I have come from a C# background and used Visual Studio with Jetbrains Resharper plugin, so learning AppCode has been a pleasure because many of the features in Resharper also exist in AppCode!

Theres too many features to list here but could well be worth checking out

make UITableViewCell selectable only while editing

Have you tried setting the selection properties of your tableView like this:

tableView.allowsMultipleSelection = NO; tableView.allowsMultipleSelectionDuringEditing = YES; tableView.allowsSelection = NO; tableView.allowsSelectionDuringEditing YES; 

If you want more fine-grain control over when selection is allowed you can override - (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath in your UITableView delegate. The documentation states:

Return Value An index-path object that confirms or alters the selected row. Return an NSIndexPath object other than indexPath if you want another cell to be selected. Return nil if you don't want the row selected. 

You can have this method return nil in cases where you don't want the selection to happen.

How to find the length of an array in shell?

In the Fish Shell the length of an array can be found with:

$ set a 1 2 3 4
$ count $a
4

How can I get the timezone name in JavaScript?

Most upvoted answer is probably the best way to get the timezone, however, Intl.DateTimeFormat().resolvedOptions().timeZone returns IANA timezone name by definition, which is in English.

If you want the timezone's name in current user's language, you can parse it from Date's string representation like so:

_x000D_
_x000D_
function getTimezoneName() {_x000D_
  const today = new Date();_x000D_
  const short = today.toLocaleDateString(undefined);_x000D_
  const full = today.toLocaleDateString(undefined, { timeZoneName: 'long' });_x000D_
_x000D_
  // Trying to remove date from the string in a locale-agnostic way_x000D_
  const shortIndex = full.indexOf(short);_x000D_
  if (shortIndex >= 0) {_x000D_
    const trimmed = full.substring(0, shortIndex) + full.substring(shortIndex + short.length);_x000D_
    _x000D_
    // by this time `trimmed` should be the timezone's name with some punctuation -_x000D_
    // trim it from both sides_x000D_
    return trimmed.replace(/^[\s,.\-:;]+|[\s,.\-:;]+$/g, '');_x000D_
_x000D_
  } else {_x000D_
    // in some magic case when short representation of date is not present in the long one, just return the long one as a fallback, since it should contain the timezone's name_x000D_
    return full;_x000D_
  }_x000D_
}_x000D_
_x000D_
console.log(getTimezoneName());
_x000D_
_x000D_
_x000D_

Tested in Chrome and Firefox.

Ofcourse, this will not work as intended in some of the environments. For example, node.js returns a GMT offset (e.g. GMT+07:00) instead of a name. But I think it's still readable as a fallback.

P.S. Won't work in IE11, just as the Intl... solution.

Validate date in dd/mm/yyyy format using JQuery Validate

I encountered a similar problem in my project. After struggling a lot, I found this solution:

if ($.datepicker.parseDate("dd/mm/yy","17/06/2015") > $.datepicker.parseDate("dd/mm/yy","20/06/2015"))
    // do something

You DO NOT NEED plugins like jQuery Validate or Moment.js for this issue. Hope this solution helps.

How to reference a method in javadoc?

you can use @see to do that:

sample:

interface View {
        /**
         * @return true: have read contact and call log permissions, else otherwise
         * @see #requestReadContactAndCallLogPermissions()
         */
        boolean haveReadContactAndCallLogPermissions();

        /**
         * if not have permissions, request to user for allow
         * @see #haveReadContactAndCallLogPermissions()
         */
        void requestReadContactAndCallLogPermissions();
    }

Aggregate multiple columns at once

We can use the formula method of aggregate. The variables on the 'rhs' of ~ are the grouping variables while the . represents all other variables in the 'df1' (from the example, we assume that we need the mean for all the columns except the grouping), specify the dataset and the function (mean).

aggregate(.~id1+id2, df1, mean)

Or we can use summarise_each from dplyr after grouping (group_by)

library(dplyr)
df1 %>%
    group_by(id1, id2) %>% 
    summarise_each(funs(mean))

Or using summarise with across (dplyr devel version - ‘0.8.99.9000’)

df1 %>% 
    group_by(id1, id2) %>%
    summarise(across(starts_with('val'), mean))

Or another option is data.table. We convert the 'data.frame' to 'data.table' (setDT(df1), grouped by 'id1' and 'id2', we loop through the subset of data.table (.SD) and get the mean.

library(data.table)
setDT(df1)[, lapply(.SD, mean), by = .(id1, id2)] 

data

df1 <- structure(list(id1 = c("a", "a", "a", "a", "b", "b", 
"b", "b"
), id2 = c("x", "x", "y", "y", "x", "y", "x", "y"), 
val1 = c(1L, 
2L, 3L, 4L, 1L, 4L, 3L, 2L), val2 = c(9L, 4L, 5L, 9L, 7L, 4L, 
9L, 8L)), .Names = c("id1", "id2", "val1", "val2"), 
class = "data.frame", row.names = c("1", 
"2", "3", "4", "5", "6", "7", "8"))

How to create an ArrayList from an Array in PowerShell?

Probably the shortest version:

[System.Collections.ArrayList]$someArray

It is also faster because it does not call relatively expensive New-Object.

MemoryStream - Cannot access a closed Stream

when it gets out from the using statement the Dispose method will be called automatically closing the stream

try the below:

using (var ms = new MemoryStream())
{
    var sw = new StreamWriter(ms);

        sw.WriteLine("data");
        sw.WriteLine("data 2");
        ms.Position = 0;
        using (var sr = new StreamReader(ms))
        {
            Console.WriteLine(sr.ReadToEnd());
        }
}    

CSS hexadecimal RGBA?

The CSS Color Module Level 4 will probably support 4 and 8-digit hexadecimal RGBA notation!

Three weeks ago (18th of December 2014) the CSS Color Module Level 4 editor's draft was submitted to the CSS W3C Working Group. Though in a state which is heavily susceptible to change, the current version of the document implies that in the somewhat near future CSS will support both the 4 and 8-digit hexadecimal RGBA notation.

Note: the following quote has irrelevant chunks cut out and the source may have been heavily modified by the time you read this (as mentioned above, it's an editor's draft and not a finalised document).
If things have heavily changed, please leave a comment letting me know so I can update this answer!

§ 4.2. The RGB hexadecimal notations: #RRGGBB

The syntax of a <hex-color> is a <hash-token> token whose value consists of 3, 4, 6, or 8 hexadecimal digits. In other words, a hex color is written as a hash character, "#", followed by some number of digits 0-9 or letters a-f (the case of the letters doesn’t matter - #00ff00 is identical to #00FF00).

8 digits

The first 6 digits are interpreted identically to the 6-digit notation. The last pair of digits, interpreted as a hexadecimal number, specifies the alpha channel of the color, where 00 represents a fully transparent color and ff represent a fully opaque color.

Example 3
In other words, #0000ffcc represents the same color as rgba(0, 0, 100%, 80%) (a slightly-transparent blue).

4 digits

This is a shorter variant of the 8-digit notation, "expanded" in the same way as the 3-digit notation is. The first digit, interpreted as a hexadecimal number, specifies the red channel of the color, where 0 represents the minimum value and f represents the maximum. The next three digits represent the green, blue, and alpha channels, respectively.

What does this mean for the future of CSS colours?

This means that assuming this isn't completely removed from the Level 4 document, we'll soon be able to define our RGBA colours (or HSLA colours, if you're one of those guys) in hexadecimal format in browsers which support the Color Module Level 4's syntax.

Example

elem {
    background: rgb(0, 0, 0);           /* RGB notation (no alpha). */
    background: #000;                   /* 3-digit hexadecimal notation (no alpha). */
    background: #000000;                /* 6-digit hexadecimal notation (no alpha). */
    background: rgba(0, 0, 0, 1.0);     /* RGBA notation. */

    /* The new 4 and 8-digit hexadecimal notation. */
    background: #0000;                  /* 4-digit hexadecimal notation. */
    background: #00000000;              /* 8-digit hexadecimal notation. */
}

When will I be able to use this in my client-facing products?

Tumble weed is the only real response...

All jokes aside: it's currently only the start of 2015, so these will not be supported in any browser for quite some time yet - even if your product is only designed to work on the most up-to-date of browsers you'll probably not be seeing this in action in a production browser any time soon.

View current browser support for #RRGGBBAA color notation

However, that said, the way CSS works means that we can actually start using these today! If you really want to start using them right now, as long as you add a fall back any non-supporting browsers will simply ignore the new properties until they are deemed valid:

_x000D_
_x000D_
figure {_x000D_
  margin: 0;_x000D_
  padding: 4px;_x000D_
  _x000D_
  /* Fall back (...to browsers which don't support alpha transparency). */_x000D_
  background: #FEFE7F;_x000D_
  color: #3F3FFE;_x000D_
  _x000D_
  /* Current 'modern' browser support. */_x000D_
  background: rgba(255, 255, 0, 0.5);_x000D_
  color: rgba(0, 0, 255, 0.75);_x000D_
  _x000D_
  /* Fall... foward? */_x000D_
  background: #ffff007F; /* Or, less accurately, #ff08 */_x000D_
  color: #0000ffbe;      /* Or #00fc */_x000D_
}
_x000D_
<figure>Hello, world!</figure>
_x000D_
_x000D_
_x000D_

As long as you're viewing this answer on a browser which supports the background and color properties in CSS, the <figure> element in result of the above snippet will look very similar to this:

Code Snippet Result Image

Using the most recent version of Chrome on Windows (v39.0.2171) to inspect our <figure> element, we'll see the following:

Element Inspector Example

The 6-digit hexadecimal fall back is overridden by the rgba() values, and our 8-digit hexadecimal values are ignored as they are currently deemed invalid by Chrome's CSS parser. As soon as our browser supports these 8-digit values, these will override the rgba() ones.

UPDATE 2018-07-04: Firefox, Chrome and Safari are support this notation now, Edge still missing but will probably follow (https://caniuse.com/#feat=css-rrggbbaa).

Java Generate Random Number Between Two Given Values

int Random = (int)(Math.random()*100);

if You need to generate more than one value, then just use for loop for that

 for (int i = 1; i <= 10 ; i++)
       {
        int Random = (int)(Math.random()*100);
        System.out.println(Random);
       }

If You want to specify a more decent range, like from 10 to 100 ( both are in the range )

so the code would be :

   int Random =10 +  (int)(Math.random()*(91));
   /* int Random = (min.value ) + (int)(Math.random()* ( Max - Min + 1));
  *Where min is the smallest value You want to be the smallest number possible to       
  generate and Max is the biggest possible number to generate*/

Convert floating point number to a certain precision, and then copy to string

It's not print that does the formatting, It's a property of strings, so you can just use

newstring = "%.9f" % numvar

How to compare two columns in Excel (from different sheets) and copy values from a corresponding column if the first two columns match?

Make a truth table and use SUMPRODUCT to get the values. Copy this into cell B1 on Sheet2 and copy down as far as you need:
=SUMPRODUCT(--($A1 = Sheet1!$A:$A), Sheet1!$B:$B)
the part that creates the truth table is:
--($A1 = Sheet1!$A:$A)
This returns an array of 0's and 1's. 1 when the values match and a 0 when they don't. Then the comma after that will basically do what I call "funny" matrix multiplication and will return the result. I may have misunderstood your question though, are there duplicate values in Column A of Sheet1?

Row count on the Filtered data

If you try to count the number of rows in the already autofiltered range like this:

Rowz = rnData.SpecialCells(xlCellTypeVisible).Rows.Count

It will only count the number of rows in the first contiguous visible area of the autofiltered range. E.g. if the autofilter range is rows 1 through 10 and rows 3, 5, 6, 7, and 9 are filtered, four rows are visible (rows 2, 4, 8, and 10), but it would return 2 because the first contiguous visible range is rows 1 (the header row) and 2.

A more accurate alternative is this (assuming that ws contains the worksheet with the filtered data):

Rowz = ws.AutoFilter.Range.Columns(1).SpecialCells(xlCellTypeVisible).Cells.Count - 1

We have to subtract 1 to remove the header row. We need to include the header row in our counted range because SpecialCells will throw an error if no cells are found, which we want to avoid.

The Cells property will give you an accurate count even if the Range has multiple Areas, unlike the Rows property. So we just take the first column of the autofilter range and count the number of visible cells.

Npm Error - No matching version found for

first, in C:\users\your PC write npm uninstall -g create-react-app then, create your project folder with npx create-react-app folder-name.

Why am I getting "Cannot Connect to Server - A network-related or instance-specific error"?

I got Solution for me :

Open "SQL Server Configuration Manager"

Now Click on "SQL Server Network Configuration" and Click on "Protocols for Name"

Right Click on "TCP/IP" (make sure it is Enabled) Click on Properties

Now Select "IP Addresses" Tab -and- Go to the last entry "IP All"

Enter "TCP Port" 1433.

Now Restart "SQL Server .Name." using "services.msc" (winKey + r)

It Will Work...

c#: getter/setter

It's an automatically backed property, basically equivalent to:

private string type;
public string Type
{
   get{ return type; }
   set{ type = value; }
}

Two decimal places using printf( )

Use: "%.2f" or variations on that.

See the POSIX spec for an authoritative specification of the printf() format strings. Note that it separates POSIX extras from the core C99 specification. There are some C++ sites which show up in a Google search, but some at least have a dubious reputation, judging from comments seen elsewhere on SO.

Since you're coding in C++, you should probably be avoiding printf() and its relatives.

How to use concerns in Rails 4

I have been reading about using model concerns to skin-nize fat models as well as DRY up your model codes. Here is an explanation with examples:

1) DRYing up model codes

Consider a Article model, a Event model and a Comment model. An article or an event has many comments. A comment belongs to either Article or Event.

Traditionally, the models may look like this:

Comment Model:

class Comment < ActiveRecord::Base
  belongs_to :commentable, polymorphic: true
end

Article Model:

class Article < ActiveRecord::Base
  has_many :comments, as: :commentable 

  def find_first_comment
    comments.first(created_at DESC)
  end

  def self.least_commented
   #return the article with least number of comments
  end
end

Event Model

class Event < ActiveRecord::Base
  has_many :comments, as: :commentable 

  def find_first_comment
    comments.first(created_at DESC)
  end

  def self.least_commented
   #returns the event with least number of comments
  end
end

As we can notice, there is a significant piece of code common to both Event and Article. Using concerns we can extract this common code in a separate module Commentable.

For this create a commentable.rb file in app/models/concerns.

module Commentable
  extend ActiveSupport::Concern

  included do
    has_many :comments, as: :commentable
  end

  # for the given article/event returns the first comment
  def find_first_comment
    comments.first(created_at DESC)
  end

  module ClassMethods
    def least_commented
      #returns the article/event which has the least number of comments
    end
  end
end

And now your models look like this :

Comment Model:

class Comment < ActiveRecord::Base
  belongs_to :commentable, polymorphic: true
end

Article Model:

class Article < ActiveRecord::Base
  include Commentable
end

Event Model:

class Event < ActiveRecord::Base
  include Commentable
end

2) Skin-nizing Fat Models.

Consider a Event model. A event has many attenders and comments.

Typically, the event model might look like this

class Event < ActiveRecord::Base   
  has_many :comments
  has_many :attenders


  def find_first_comment
    # for the given article/event returns the first comment
  end

  def find_comments_with_word(word)
    # for the given event returns an array of comments which contain the given word
  end 

  def self.least_commented
    # finds the event which has the least number of comments
  end

  def self.most_attended
    # returns the event with most number of attendes
  end

  def has_attendee(attendee_id)
    # returns true if the event has the mentioned attendee
  end
end

Models with many associations and otherwise have tendency to accumulate more and more code and become unmanageable. Concerns provide a way to skin-nize fat modules making them more modularized and easy to understand.

The above model can be refactored using concerns as below: Create a attendable.rb and commentable.rb file in app/models/concerns/event folder

attendable.rb

module Attendable
  extend ActiveSupport::Concern

  included do 
    has_many :attenders
  end

  def has_attender(attender_id)
    # returns true if the event has the mentioned attendee
  end

  module ClassMethods
    def most_attended
      # returns the event with most number of attendes
    end
  end
end

commentable.rb

module Commentable
  extend ActiveSupport::Concern

  included do 
    has_many :comments
  end

  def find_first_comment
    # for the given article/event returns the first comment
  end

  def find_comments_with_word(word)
    # for the given event returns an array of comments which contain the given word
  end

  module ClassMethods
    def least_commented
      # finds the event which has the least number of comments
    end
  end
end

And now using Concerns, your Event model reduces to

class Event < ActiveRecord::Base
  include Commentable
  include Attendable
end

* While using concerns its advisable to go for 'domain' based grouping rather than 'technical' grouping. Domain Based grouping is like 'Commentable', 'Photoable', 'Attendable'. Technical grouping will mean 'ValidationMethods', 'FinderMethods' etc

How can I run PowerShell with the .NET 4 runtime?

If you don't want to modify the registry or app.config files, an alternate way is to create a simple .NET 4 console app that mimicks what PowerShell.exe does and hosts the PowerShell ConsoleShell.

See Option 2 – Hosting Windows PowerShell yourself

First, add a reference to the System.Management.Automation and Microsoft.PowerShell.ConsoleHost assemblies which can be found under %programfiles%\Reference Assemblies\Microsoft\WindowsPowerShell\v1.0

Then use the following code:

using System;
using System.Management.Automation.Runspaces;
using Microsoft.PowerShell;

namespace PSHostCLRv4
{
    class Program
    {
        static int Main(string[] args)
        {
            var config = RunspaceConfiguration.Create();
                return ConsoleShell.Start(
                config,
                "Windows PowerShell - Hosted on CLR v4\nCopyright (C) 2010 Microsoft Corporation. All rights reserved.",
                "",
                args
            );
        }
    }
}

Difference between app.use and app.get in express.js

app.get is called when the HTTP method is set to GET, whereas app.use is called regardless of the HTTP method, and therefore defines a layer which is on top of all the other RESTful types which the express packages gives you access to.

AttributeError: 'numpy.ndarray' object has no attribute 'append'

Use numpy.concatenate(list1 , list2) or numpy.append() Look into the thread at Append a NumPy array to a NumPy array.

Git commit in terminal opens VIM, but can't get back to terminal

not really the answer to the VIM problem but you could use the command line to also enter the commit message:

git commit -m "This is the first commit"

How do I count a JavaScript object's attributes?

This function makes use of Mozilla's __count__ property if it is available as it is faster than iterating over every property.

function countProperties(obj) {
  var count = "__count__",
  hasOwnProp = Object.prototype.hasOwnProperty;

  if (typeof obj[count] === "number" && !hasOwnProp.call(obj, count)) {
    return obj[count];
  }
  count = 0;
  for (var prop in obj) {
    if (hasOwnProp.call(obj, prop)) {
      count++;
    }
  }
  return count;
};

countProperties({
  "1": 2,
  "3": 4,
  "5": 6
}) === 3;

Removing input background colour for Chrome autocomplete?

Try this: Same as @Nathan-white answer above with minor tweaks.

/* For removing autocomplete highlight color in chrome (note: use this at bottom of your css file). */

input:-webkit-autofill,
input:-webkit-autofill:hover,
input:-webkit-autofill:focus,
input:-webkit-autofill:active {
    transition: all 5000s ease-in-out 0s;
    transition-property: background-color, color;
}

How to concatenate and minify multiple CSS and JavaScript files with Grunt.js (0.3.x)

I want to mention here a very, VERY, interesting technique that is being used in huge projects like jQuery and Modernizr for concatenate things.

Both of this projects are entirely developed with requirejs modules (you can see that in their github repos) and then they use the requirejs optimizer as a very smart concatenator. The interesting thing is that, as you can see, nor jQuery neither Modernizr needs on requirejs to work, and this happen because they erase the requirejs syntatic ritual in order to get rid of requirejs in their code. So they end up with a standalone library that was developed with requirejs modules! Thanks to this they are able to perform cutsom builds of their libraries, among other advantages.

For all those interested in concatenation with the requirejs optimizer, check out this post

Also there is a small tool that abstracts all the boilerplate of the process: AlbanilJS

Creating a data frame from two vectors using cbind

Using data.frame instead of cbind should be helpful

x <- data.frame(col1=c(10, 20), col2=c("[]", "[]"), col3=c("[[1,2]]","[[1,3]]"))
x
  col1 col2    col3
1   10   [] [[1,2]]
2   20   [] [[1,3]]

sapply(x, class) # looking into x to see the class of each element
     col1      col2      col3 
"numeric"  "factor"  "factor" 

As you can see elements from col1 are numeric as you wish.

data.frame can have variables of different class: numeric, factor and character but matrix doesn't, once you put a character element into a matrix all the other will become into this class no matter what clase they were before.

iOS 6 apps - how to deal with iPhone 5 screen size?

All apps will continue to work in the vertically stretched screen from what I could tell in today's presentation. They will be letterboxed or basically the extra 88 points in height would simply be black.

If you only plan to support iOS 6+, then definitely consider using Auto Layout. It removes all fixed layout handling and instead uses constraints to lay things out. Nothing will be hard-coded, and your life will become a lot simpler.

However, if you have to support older iOS's, then it really depends on your application. A majority of applications that use a standard navigation bar, and/or tab bar, could simply expand the content in the middle to use up that extra points. Set the autoresizing mask of the center content to expand in both directions.

view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

It works great out of the box for table views, however, if your app used pixel-perfect layout for displaying content, then your best bet would be to re-imagine the content so that it can accommodate varying heights.

If that's not a possibility, then the only remaining option is to have two UIs (pre iPhone 5, and iPhone 5).

If that sounds ugly, then you could go with the default letterboxed model where the extra points/pixels just show up black.

Edit

To enable your apps to work with iPhone 5, you need to add a retina version of the launcher image. It should be named [email protected]. And it has to be retina quality - there's no backward compatibility here :)

You could also select this image from within Xcode. Go to the target, and under the Summary section, look for Launch Images. The image has to be 640x1136 pixels in size. Here's a screenshot of where to find it, if that helps.

Xcode screenshot

How to find day of week in php in a specific timezone

My solution is this:

$tempDate = '2012-07-10';
echo date('l', strtotime( $tempDate));

Output is: Tuesday

$tempDate = '2012-07-10';
echo date('D', strtotime( $tempDate));

Output is: Tue

How to lookup JNDI resources on WebLogic?

You should be able to simply do this:

Context context = new InitialContext();
dataSource = (javax.sql.DataSource) context.lookup("jdbc/myDataSource");

If you are looking it up from a remote destination you need to use the WL initial context factory like this:

Hashtable<String, String> h = new Hashtable<String, String>(7);
h.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
h.put(Context.PROVIDER_URL, pURL); //For example "t3://127.0.0.1:7001"
h.put(Context.SECURITY_PRINCIPAL, pUsername);
h.put(Context.SECURITY_CREDENTIALS, pPassword);

InitialContext context = new InitialContext(h);
dataSource = (javax.sql.DataSource) context.lookup("jdbc/myDataSource");

weblogic.jndi.WLInitialContextFactory

VBA for filtering columns

Here's a different approach. The heart of it was created by turning on the Macro Recorder and filtering the columns per your specifications. Then there's a bit of code to copy the results. It will run faster than looping through each row and column:

Sub FilterAndCopy()
Dim LastRow As Long

Sheets("Sheet2").UsedRange.Offset(0).ClearContents
With Worksheets("Sheet1")
    .Range("$A:$E").AutoFilter
    .Range("$A:$E").AutoFilter field:=1, Criteria1:="#N/A"
    .Range("$A:$E").AutoFilter field:=2, Criteria1:="=String1", Operator:=xlOr, Criteria2:="=string2"
    .Range("$A:$E").AutoFilter field:=3, Criteria1:=">0"
    .Range("$A:$E").AutoFilter field:=5, Criteria1:="Number"
    LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
    .Range("A1:A" & LastRow).SpecialCells(xlCellTypeVisible).EntireRow.Copy _
            Destination:=Sheets("Sheet2").Range("A1")
End With
End Sub

As a side note, your code has more loops and counter variables than necessary. You wouldn't need to loop through the columns, just through the rows. You'd then check the various cells of interest in that row, much like you did.

Append an int to a std::string

I have a feeling that your ClientID is not of a string type (zero-terminated char* or std::string) but some integral type (e.g. int) so you need to convert number to the string first:

std::stringstream ss;
ss << ClientID;
query.append(ss.str());

But you can use operator+ as well (instead of append):

query += ss.str();

How to retrieve raw post data from HttpServletRequest in java

We had a situation where IE forced us to post as text/plain, so we had to manually parse the parameters using getReader. The servlet was being used for long polling, so when AsyncContext::dispatch was executed after a delay, it was literally reposting the request empty handed.

So I just stored the post in the request when it first appeared by using HttpServletRequest::setAttribute. The getReader method empties the buffer, where getParameter empties the buffer too but stores the parameters automagically.

    String input = null;

    // we have to store the string, which can only be read one time, because when the
    // servlet awakens an AsyncContext, it reposts the request and returns here empty handed
    if ((input = (String) request.getAttribute("com.xp.input")) == null) {
        StringBuilder buffer = new StringBuilder();
        BufferedReader reader = request.getReader();

        String line;
        while((line = reader.readLine()) != null){
            buffer.append(line);
        }
        // reqBytes = buffer.toString().getBytes();

        input = buffer.toString();
        request.setAttribute("com.xp.input", input);
    }

    if (input == null) {
        response.setContentType("text/plain");
        PrintWriter out = response.getWriter();
        out.print("{\"act\":\"fail\",\"msg\":\"invalid\"}");
    }       

Can I use DIV class and ID together in CSS?

That's HTML, but yes, you can bang pretty much any selectors you like together.

#x.y { }

(And the HTML is fine too)

How do I check if an index exists on a table field in MySQL?

If you need the functionality if a index for a column exists (here at first place in sequence) as a database function you can use/adopt this code. If you want to check if an index exists at all regardless of the position in a multi-column-index, then just delete the part "AND SEQ_IN_INDEX = 1".

DELIMITER $$
CREATE FUNCTION `fct_check_if_index_for_column_exists_at_first_place`(
    `IN_SCHEMA` VARCHAR(255),
    `IN_TABLE` VARCHAR(255),
    `IN_COLUMN` VARCHAR(255)
)
RETURNS tinyint(4)
LANGUAGE SQL
DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT 'Check if index exists at first place in sequence for a given column in a given table in a given schema. Returns -1 if schema does not exist. Returns -2 if table does not exist. Returns -3 if column does not exist. If index exists in first place it returns 1, otherwise 0.'
BEGIN

-- Check if index exists at first place in sequence for a given column in a given table in a given schema. 
-- Returns -1 if schema does not exist. 
-- Returns -2 if table does not exist. 
-- Returns -3 if column does not exist. 
-- If the index exists in first place it returns 1, otherwise 0.
-- Example call: SELECT fct_check_if_index_for_column_exists_at_first_place('schema_name', 'table_name', 'index_name');

-- check if schema exists
SELECT 
    COUNT(*) INTO @COUNT_EXISTS
FROM 
    INFORMATION_SCHEMA.SCHEMATA
WHERE 
    SCHEMA_NAME = IN_SCHEMA
;

IF @COUNT_EXISTS = 0 THEN
    RETURN -1;
END IF;


-- check if table exists
SELECT 
    COUNT(*) INTO @COUNT_EXISTS
FROM 
    INFORMATION_SCHEMA.TABLES
WHERE 
    TABLE_SCHEMA = IN_SCHEMA
AND TABLE_NAME = IN_TABLE
;

IF @COUNT_EXISTS = 0 THEN
    RETURN -2;
END IF;


-- check if column exists
SELECT 
    COUNT(*) INTO @COUNT_EXISTS
FROM 
    INFORMATION_SCHEMA.COLUMNS
WHERE 
    TABLE_SCHEMA = IN_SCHEMA
AND TABLE_NAME = IN_TABLE
AND COLUMN_NAME = IN_COLUMN
;

IF @COUNT_EXISTS = 0 THEN
    RETURN -3;
END IF;

-- check if index exists at first place in sequence
SELECT 
    COUNT(*) INTO @COUNT_EXISTS
FROM 
    information_schema.statistics 
WHERE 
    TABLE_SCHEMA = IN_SCHEMA
AND TABLE_NAME = IN_TABLE AND COLUMN_NAME = IN_COLUMN
AND SEQ_IN_INDEX = 1;


IF @COUNT_EXISTS > 0 THEN
    RETURN 1;
ELSE
    RETURN 0;
END IF;


END$$
DELIMITER ;

Using multiple parameters in URL in express

For what you want I would've used

    app.get('/fruit/:fruitName&:fruitColor', function(request, response) {
       const name = request.params.fruitName 
       const color = request.params.fruitColor 
    });

or better yet

    app.get('/fruit/:fruit', function(request, response) {
       const fruit = request.params.fruit
       console.log(fruit)
    });

where fruit is a object. So in the client app you just call

https://mydomain.dm/fruit/{"name":"My fruit name", "color":"The color of the fruit"}

and as a response you should see:

    //  client side response
    // { name: My fruit name, color:The color of the fruit}

Jquery click event not working after append method

TRY THIS

As of jQuery version 1.7+, the on() method is the new replacement for the bind(), live() and delegate() methods.

SO ADD THIS,

$(document).on("click", "a.new_participant_form" , function() {
      console.log('clicked');
});

Or for more information CHECK HERE

How to get all the AD groups for a particular user?

This code works even faster (two 1.5 faster than my previous version):

    public List<String> GetUserGroups(WindowsIdentity identity)
    {
        List<String> groups = new List<String>();

        String userName = identity.Name;
        int pos = userName.IndexOf(@"\");
        if (pos > 0) userName = userName.Substring(pos + 1);

        PrincipalContext domain = new PrincipalContext(ContextType.Domain, "riomc.com");
        UserPrincipal user = UserPrincipal.FindByIdentity(domain, IdentityType.SamAccountName, userName); // NGeodakov

        DirectoryEntry de = new DirectoryEntry("LDAP://RIOMC.com");
        DirectorySearcher search = new DirectorySearcher(de);
        search.Filter = "(&(objectClass=group)(member=" + user.DistinguishedName + "))";
        search.PropertiesToLoad.Add("cn");
        search.PropertiesToLoad.Add("samaccountname");
        search.PropertiesToLoad.Add("memberOf");

        SearchResultCollection results = search.FindAll();
        foreach (SearchResult sr in results)
        {
            GetUserGroupsRecursive(groups, sr, de);
        }

        return groups;
    }

    public void GetUserGroupsRecursive(List<String> groups, SearchResult sr, DirectoryEntry de)
    {
        if (sr == null) return;

        String group = (String)sr.Properties["cn"][0];
        if (String.IsNullOrEmpty(group))
        {
            group = (String)sr.Properties["samaccountname"][0];
        }
        if (!groups.Contains(group))
        {
            groups.Add(group);
        }

        DirectorySearcher search;
        SearchResult sr1;
        String name;
        int equalsIndex, commaIndex;
        foreach (String dn in sr.Properties["memberof"])
        {
            equalsIndex = dn.IndexOf("=", 1);
            if (equalsIndex > 0)
            {
                commaIndex = dn.IndexOf(",", equalsIndex + 1);
                name = dn.Substring(equalsIndex + 1, commaIndex - equalsIndex - 1);

                search = new DirectorySearcher(de);
                search.Filter = "(&(objectClass=group)(|(cn=" + name + ")(samaccountname=" + name + ")))";
                search.PropertiesToLoad.Add("cn");
                search.PropertiesToLoad.Add("samaccountname");
                search.PropertiesToLoad.Add("memberOf");
                sr1 = search.FindOne();
                GetUserGroupsRecursive(groups, sr1, de);
            }
        }
    }

Out-File -append in Powershell does not produce a new line and breaks string into characters

Out-File defaults to unicode encoding which is why you are seeing the behavior you are. Use -Encoding Ascii to change this behavior. In your case

Out-File -Encoding Ascii -append textfile.txt. 

Add-Content uses Ascii and also appends by default.

"This is a test" | Add-Content textfile.txt.

As for the lack of newline: You did not send a newline so it will not write one to file.

How to convert byte array to string

You can do it without dealing with encoding by using BlockCopy:

char[] chars = new char[bytes.Length / sizeof(char)];
System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
string str = new string(chars);

How to properly use jsPDF library

This is finally what did it for me (and triggers a disposition):

_x000D_
_x000D_
function onClick() {_x000D_
  var pdf = new jsPDF('p', 'pt', 'letter');_x000D_
  pdf.canvas.height = 72 * 11;_x000D_
  pdf.canvas.width = 72 * 8.5;_x000D_
_x000D_
  pdf.fromHTML(document.body);_x000D_
_x000D_
  pdf.save('test.pdf');_x000D_
};_x000D_
_x000D_
var element = document.getElementById("clickbind");_x000D_
element.addEventListener("click", onClick);
_x000D_
<h1>Dsdas</h1>_x000D_
_x000D_
<a id="clickbind" href="#">Click</a>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.3/jspdf.min.js"></script>
_x000D_
_x000D_
_x000D_

And for those of the KnockoutJS inclination, a little binding:

ko.bindingHandlers.generatePDF = {
    init: function(element) {

        function onClick() {
            var pdf = new jsPDF('p', 'pt', 'letter');
            pdf.canvas.height = 72 * 11;
            pdf.canvas.width = 72 * 8.5;

            pdf.fromHTML(document.body);

            pdf.save('test.pdf');                    
        };

        element.addEventListener("click", onClick);
    }
};

How to set dropdown arrow in spinner?

Basically one needs to create a custom background for a spinner. It should be something like this:

spinner_background.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item>

        <layer-list>

            <item>
                <color
                    android:color="@android:color/white"/>
            </item>

            <item>
                <bitmap
                    android:gravity="center_vertical|right"
                    android:src="@drawable/ic_arrow_drop_down_black_24dp"/>
            </item>

        </layer-list>

    </item>

</selector>

Then create a custom style for your spinner, where you specify the above selector as background:

<style name="Widget.App.Spinner" parent="@style/Widget.AppCompat.Spinner">
    <item name="overlapAnchor">true</item>
    <item name="android:background">@drawable/spinner_background</item>
</style>

And finally in your app theme you should override two attributes if you want it to be applied all across your app:

<item name="spinnerStyle">@style/Widget.App.Spinner</item>
<item name="android:spinnerStyle">@style/Widget.App.Spinner</item>

And that's pretty much it.

MySQL vs MySQLi when using PHP

If you have a look at MySQL Improved Extension Overview, it should tell you everything you need to know about the differences between the two.

The main useful features are:

  • an Object-oriented interface
  • support for prepared statements
  • support for multiple statements
  • support for transactions
  • enhanced debugging capabilities
  • embedded server support.

How to get the height of a body element

Set

html { height: 100%; }
body { min-height: 100%; }

instead of height: 100%.

The result jQuery returns is correct, because you've set the height of the body to 100%, and that's probably the height of the viewport. These three DIVs were causing an overflow, because there weren't enough space for them in the BODY element. To see what I mean, set a border to the BODY tag and check where the border ends.

Convert JS object to JSON string

use JSON.stringify(param1, param2, param3);

What is: -

param1 --> value to convert to JSON

param2 --> function to stringify in your own way. Alternatively, it serves as a white list for which objects need to be included in the final JSON.

param3 --> A Number data type which indicates number of whitespaces to add. Max allowed are 10.

Flatten an irregular list of lists

No recursion or nested loops. A few lines. Well formatted and easy to read:

def flatten_deep(arr: list):
""" Flattens arbitrarily-nested list `arr` into single-dimensional. """

while arr:
    if isinstance(arr[0], list):  # Checks whether first element is a list
        arr = arr[0] + arr[1:]  # If so, flattens that first element one level
    else:
        yield arr.pop(0)  # Otherwise yield as part of the flat array

flatten_deep(L)

From my own code at https://github.com/jorgeorpinel/flatten_nested_lists/blob/master/flatten.py

Run a vbscript from another vbscript

You can try using the Wshshell.Run method which gives you little control of the process you start with it. Or you could use the WshShell.Exec method which will give you control to terminate it, get a response, pass more parameters (other than commandline args), get status, and others

To use Run (Simple Method)

Dim ProgramPath, WshShell, ProgramArgs, WaitOnReturn,intWindowStyle
Set WshShell=CreateObject ("WScript.Shell")
ProgramPath="c:\test run script.vbs"
ProgramArgs="/hello /world"
intWindowStyle=1
WaitOnReturn=True
WshShell.Run Chr (34) & ProgramPath & Chr (34) & Space (1) & ProgramArgs,intWindowStyle, WaitOnReturn

ProgramPath is the full path to your script you want to run
ProgramArgs is the arguments you want to pass to the script. (NOTE: the arguments are separated by a space, if you want to use an argument that contains a space then you will have to enclose that argument in quotes [Safe way to do this is use CHR (34) Example ProgramArgs= chr (34) & "/Hello World" & chr (34)])
IntWindowStyle is the integer that determines how the window will be displayed. More info on this and WaitOnReturn can be found here WshShell.Run Method
WaitOnReturn if true then the script will pause until the command has terminated, if false then the script will continue right after starting command.

NOTE: The Run method can return the exit code but you must set WaitOnReturn to True, and assign the 'WshShell.Run' to a variable. (EX: ExitCode=WshShell.Run (Command,intWindowStyle,True))

To Use EXEC (Advanced Method)

Dim ProgramPath, WshShell, ProgramArgs, Process, ScriptEngine
Set WshShell=CreateObject ("WScript.Shell")
ProgramPath="c:\test run script.vbs"
ProgramArgs="/hello /world"
ScriptEngine="CScript.exe"
Set Process=WshShell.Exec (ScriptEngine & space (1) & Chr(34) & ProgramPath & Chr (34) & Space (1) & ProgramArgs)
Do While Process.Status=0
    'Currently Waiting on the program to finish execution.
    WScript.Sleep 300
Loop

ProgramPath same as Run READ RUN'S DESCRIPTION
ProgramArgs DITTO
ScriptEngine The Engine you will be using for executing the script. since the exec method requires a win32 application, you need to specify this. Usually either "WScript.exe" or "CScript.exe". Note that in order to use stdin and stdout (we'll cover what these are a bit further down) you must choose "CScript.exe".
Process this is the Object that references to the program the script will start. It has several members and they are: ExitCode, ProcessID, Status, StdErr, StdIn, StdOut, Terminate.

More Details about the members of Process Object

  1. ExitCode This is the exit code that is returned when the process terminates.
  2. ProcessID This is the ID that is assigned to the process, every process has an unique processID.
  3. Status This is a code number that indicates the status of the process, it get set to '-1' when the process terminates.
  4. StdErr This is the object that represents the Standard Error Stream
  5. StdIn This is the Object that represents the Standard Input Stream, use it to write additional parameters or anything you want to pass to the script you are calling. (Process.StdIn.WriteLine "Hello Other Worlds")
  6. StdOut This is the Object that represents the Standard Output Stream, It is READONLY so you can use Process.StdOut.ReadLine. This is the stream that the called script will receive any information sent by the calling script's stdin. If you used the stdin's example then StdOut.Readline will return "Hello Other Worlds". If there is nothing to read then the script will hang while waiting for an output. meaning the script will appear to be Not Responding
    Note: you can use Read or ReadAll instead of ReadLine if you want. Use Read (X) if you want to read X amount of characters. Or ReadAll if you want the rest of the stream.
  7. Terminate Call this method to force terminate the process.

For more information about WshShell.Exec go to Exec Method Windows Scripting Host

What is the list of supported languages/locales on Android?

Just FYI, if you are unable to set any locale, the problem might be below attribute in your app level gradle file:

resConfigs "en", "hi" //to specify allowed locales for your app

So, if you want to support any locale other than English and Hindi, specify your locale here or just remove above line. By default your app will support all the locales.

Thanks :)

How can I assign the output of a function to a variable using bash?

You may use bash functions in commands/pipelines as you would otherwise use regular programs. The functions are also available to subshells and transitively, Command Substitution:

VAR=$(scan)

Is the straighforward way to achieve the result you want in most cases. I will outline special cases below.

Preserving trailing Newlines:

One of the (usually helpful) side effects of Command Substitution is that it will strip any number of trailing newlines. If one wishes to preserve trailing newlines, one can append a dummy character to output of the subshell, and subsequently strip it with parameter expansion.

function scan2 () {
    local nl=$'\x0a';  # that's just \n
    echo "output${nl}${nl}" # 2 in the string + 1 by echo
}

# append a character to the total output.
# and strip it with %% parameter expansion.
VAR=$(scan2; echo "x"); VAR="${VAR%%x}"

echo "${VAR}---"

prints (3 newlines kept):

output


---

Use an output parameter: avoiding the subshell (and preserving newlines)

If what the function tries to achieve is to "return" a string into a variable , with bash v4.3 and up, one can use what's called a nameref. Namerefs allows a function to take the name of one or more variables output parameters. You can assign things to a nameref variable, and it is as if you changed the variable it 'points to/references'.

function scan3() {
    local -n outvar=$1    # -n makes it a nameref.
    local nl=$'\x0a'
    outvar="output${nl}${nl}"  # two total. quotes preserve newlines
}

VAR="some prior value which will get overwritten"

# you pass the name of the variable. VAR will be modified.
scan3 VAR

# newlines are also preserved.
echo "${VAR}==="

prints:

output

===

This form has a few advantages. Namely, it allows your function to modify the environment of the caller without using global variables everywhere.

Note: using namerefs can improve the performance of your program greatly if your functions rely heavily on bash builtins, because it avoids the creation of a subshell that is thrown away just after. This generally makes more sense for small functions reused often, e.g. functions ending in echo "$returnstring"

This is relevant. https://stackoverflow.com/a/38997681/5556676

How to add custom html attributes in JSX

See attribute value in console on click event

//...
   alertMessage (cEvent){
           console.log(cEvent.target.getAttribute('customEvent')); /*display attribute value */
        }
//...

simple add customAttribute as your wish in render method

render(){
    return <div>
//..
    <button customAttribute="My Custom Event Message" onClick={this.alertMessage.bind(this) } >Click Me</button>
            </div>
        }
//...

Height equal to dynamic width (CSS fluid layout)

really this belongs as a comment to Nathan's answer, but I'm not allowed to do that yet...
I wanted to maintain the aspect ratio, even if there is too much stuff to fit in the box. His example expands the height, changing the aspect ratio. I found adding

overflow: hidden;
overflow-x: auto;
overflow-y: auto;

to the .element helped. See http://jsfiddle.net/B8FU8/3111/

%i or %d to print integer in C using printf()?

I am just adding example here because I think examples make it easier to understand.

In printf() they behave identically so you can use any either %d or %i. But they behave differently in scanf().

For example:

int main()
{
    int num,num2;
    scanf("%d%i",&num,&num2);// reading num using %d and num2 using %i

    printf("%d\t%d",num,num2);
    return 0;
}

Output:

enter image description here

You can see the different results for identical inputs.

num:

We are reading num using %d so when we enter 010 it ignores the first 0 and treats it as decimal 10.

num2:

We are reading num2 using %i.

That means it will treat decimals, octals, and hexadecimals differently.

When it give num2 010 it sees the leading 0 and parses it as octal.

When we print it using %d it prints the decimal equivalent of octal 010 which is 8.

.Net HttpWebRequest.GetResponse() raises exception when http status code 400 (bad request) is returned

An asynchronous version of extension function:

    public static async Task<WebResponse> GetResponseAsyncNoEx(this WebRequest request)
    {
        try
        {
            return await request.GetResponseAsync();
        }
        catch(WebException ex)
        {
            return ex.Response;
        }
    }

How to vertically align a html radio button to it's label?

While I agree tables shouldn't be used for design layouts contrary to popular belief they do pass validation. i.e. the table tag is not deprecated. The best way to align radio buttons is using the vertical align middle CSS with margins adjusted on the input elements.

Have nginx access_log and error_log log to STDOUT and STDERR of master process

Edit: it seems nginx now supports error_log stderr; as mentioned in Anon's answer.

You can send the logs to /dev/stdout. In nginx.conf:

daemon off;
error_log /dev/stdout info;

http {
  access_log /dev/stdout;
  ...
}

edit: May need to run ln -sf /proc/self/fd /dev/ if using running certain docker containers, then use /dev/fd/1 or /dev/fd/2

WebService Client Generation Error with JDK8

It is now fixed in 2.5 version (released in jul/17). https://github.com/mojohaus/jaxws-maven-plugin/issues/8.

For the 2.4.x versions there is a workaround (as decribed in https://github.com/mojohaus/jaxws-maven-plugin/issues/4):

    <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>jaxws-maven-plugin</artifactId>
        <version>2.4.1</version>
        <dependencies>
            <dependency>
                <groupId>com.sun.xml.ws</groupId>
                <artifactId>jaxws-tools</artifactId>
                <version>2.2.10</version>
            </dependency>
        </dependencies>
    </plugin>

bind/unbind service example (android)

You can try using this code:

protected ServiceConnection mServerConn = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder binder) {
        Log.d(LOG_TAG, "onServiceConnected");
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        Log.d(LOG_TAG, "onServiceDisconnected");
    }
}

public void start() {
    // mContext is defined upper in code, I think it is not necessary to explain what is it 
    mContext.bindService(intent, mServerConn, Context.BIND_AUTO_CREATE);
    mContext.startService(intent);
}

public void stop() {
    mContext.stopService(new Intent(mContext, ServiceRemote.class));
    mContext.unbindService(mServerConn);
}

document.getElementById replacement in angular4 / typescript?

  element: HTMLElement;

  constructor() {}

  fakeClick(){
    this.element = document.getElementById('ButtonX') as HTMLElement;
    this.element.click();
  }

Add an element to an array in Swift

Use += and + operators :

extension Array {

}

func += <V> (inout left: [V], right: V) {
    left.append(right)
}

func + <V>(left: Array<V>, right: V) -> Array<V>
{
    var map = Array<V>()
    for (v) in left {
        map.append(v)
    }

    map.append(right)

    return map
}

then use :

var list = [AnyObject]()
list += "hello" 
list += ["hello", "world!"]
var list2 = list + "anything"

Getting Hour and Minute in PHP

print date('H:i');

You have to set the correct timezone in php.ini .

Look for these lines:

[Date]

; Defines the default timezone used by the date functions

;date.timezone =

It will be something like :

date.timezone ="Europe/Lisbon"

Don't forget to restart your webserver.

Change app language programmatically in Android

For Android 7.0 Nougat (and lower) follow this article:

Change Language Programatically in Android

Old answer
This include RTL/LTR support:

public static void changeLocale(Context context, Locale locale) {
    Configuration conf = context.getResources().getConfiguration();
    conf.locale = locale;
    Locale.setDefault(locale);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
       conf.setLayoutDirection(conf.locale);
    }

    context.getResources().updateConfiguration(conf, context.getResources().getDisplayMetrics());
}

Email and phone Number Validation in android

in Kotlin you can use Extension function to validate input

// for Email validation

 fun String.isValidEmail(): Boolean =
        this.isNotEmpty() && Patterns.EMAIL_ADDRESS.matcher(this).matches()

// for Phone validation

fun String.isValidMobile(phone: String): Boolean {
    return Patterns.PHONE.matcher(phone).matches()
}

How can I execute Shell script in Jenkinsfile?

Based on the number of views this question has, it looks like a lot of people are visiting this to see how to set up a job that executes a shell script.

These are the steps to execute a shell script in Jenkins:

  • In the main page of Jenkins select New Item.
  • Enter an item name like "my shell script job" and chose Freestyle project. Press OK.
  • On the configuration page, in the Build block click in the Add build step dropdown and select Execute shell.
  • In the textarea you can either paste a script or indicate how to run an existing script. So you can either say:

    #!/bin/bash
    
    echo "hello, today is $(date)" > /tmp/jenkins_test
    

    or just

    /path/to/your/script.sh
    
  • Click Save.

Now the newly created job should appear in the main page of Jenkins, together with the other ones. Open it and select Build now to see if it works. Once it has finished pick that specific build from the build history and read the Console output to see if everything happened as desired.

You can get more details in the document Create a Jenkins shell script job in GitHub.

In laymans terms, what does 'static' mean in Java?

Another great example of when static attributes and operations are used when you want to apply the Singleton design pattern. In a nutshell, the Singleton design pattern ensures that one and only one object of a particular class is ever constructeed during the lifetime of your system. to ensure that only one object is ever constructed, typical implemenations of the Singleton pattern keep an internal static reference to the single allowed object instance, and access to that instance is controlled using a static operation

How to do a "Save As" in vba code, saving my current Excel workbook with datestamp?

Easiest way to use this function is to start by 'Recording a Macro'. Once you start recording, save the file to the location you want, with the name you want, and then of course set the file type, most likely 'Excel Macro Enabled Workbook' ~ 'XLSM'

Stop recording and you can start inspecting your code.

I wrote the code below which allows you to save a workbook using the path where the file was originally located, naming it as "Event [date in cell "A1"]"

Option Explicit

Sub SaveFile()

Dim fdate As Date
Dim fname As String
Dim path As String

fdate = Range("A1").Value
path = Application.ActiveWorkbook.path

If fdate > 0 Then
    fname = "Event " & fdate
    Application.ActiveWorkbook.SaveAs Filename:=path & "\" & fname, _
        FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
Else
    MsgBox "Chose a date for the event", vbOKOnly
End If

End Sub

Copy the code into a new module and then write a date in cell "A1" e.g. 01-01-2016 -> assign the sub to a button and run. [Note] you need to make a save file before this script will work, because a new workbook is saved to the default autosave location!

How can I slice an ArrayList out of an ArrayList in Java?

If there is no existing method then I guess you can iterate from 0 to input.size()/2, taking each consecutive element and appending it to a new ArrayList.

EDIT: Actually, I think you can take that List and use it to instantiate a new ArrayList using one of the ArrayList constructors.

What is this date format? 2011-08-12T20:17:46.384Z

@John-Skeet gave me the clue to fix my own issue around this. As a younger programmer this small issue is easy to miss and hard to diagnose. So Im sharing it in the hopes it will help someone.

My issue was that I wanted to parse the following string contraining a time stamp from a JSON I have no influence over and put it in more useful variables. But I kept getting errors.

So given the following (pay attention to the string parameter inside ofPattern();

String str = "20190927T182730.000Z"

LocalDateTime fin;
fin = LocalDateTime.parse( str, DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss.SSSZ") );

Error:

Exception in thread "main" java.time.format.DateTimeParseException: Text 
'20190927T182730.000Z' could not be parsed at index 19

The problem? The Z at the end of the Pattern needs to be wrapped in 'Z' just like the 'T' is. Change "yyyyMMdd'T'HHmmss.SSSZ" to "yyyyMMdd'T'HHmmss.SSS'Z'" and it works.

Removing the Z from the pattern alltogether also led to errors.

Frankly, I'd expect a Java class to have anticipated this.

What is `git push origin master`? Help with git's refs, heads and remotes

Git has two types of branches: local and remote. To use git pull and git push as you'd like, you have to tell your local branch (my_test) which remote branch it's tracking. In typical Git fashion this can be done in both the config file and with commands.

Commands

Make sure you're on your master branch with

1)git checkout master

then create the new branch with

2)git branch --track my_test origin/my_test

and check it out with

3)git checkout my_test.

You can then push and pull without specifying which local and remote.

However if you've already created the branch then you can use the -u switch to tell git's push and pull you'd like to use the specified local and remote branches from now on, like so:

git pull -u my_test origin/my_test
git push -u my_test origin/my_test

Config

The commands to setup remote branch tracking are fairly straight forward but I'm listing the config way as well as I find it easier if I'm setting up a bunch of tracking branches. Using your favourite editor open up your project's .git/config and add the following to the bottom.

[remote "origin"]
    url = [email protected]:username/repo.git
    fetch = +refs/heads/*:refs/remotes/origin/*
[branch "my_test"]
    remote = origin
    merge = refs/heads/my_test

This specifies a remote called origin, in this case a GitHub style one, and then tells the branch my_test to use it as it's remote.

You can find something very similar to this in the config after running the commands above.

Some useful resources:

How to get child process from parent process

Just use :

pgrep -P $your_process1_pid

How to convert binary string value to decimal

Test it

import java.util.Scanner;
public class BinaryToDecimal{

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);
    int binaryNumber = 0;
    int counter = 0;
    int number = 0;


    System.out.print("Input binary number: ");
    binaryNumber = input.nextInt();

    //it's going to stop when the binaryNumber/10 is less than 0
    //example:
    //binaryNumber = 11/10. The result value is 1 when you do the next
    //operation 1/10 . The result value is 0     

    while(binaryNumber != 0)
    {
        //Obtaining the remainder of the division and multiplying it 
        //with the number raised to two

        //adding it up with the previous result

        number += ((binaryNumber % 10)) * Math.pow(2,counter);

        binaryNumber /= 10;  //removing one digit from the binary number

        //Increasing counter 2^0, 2^1, 2^2, 2^3.....
        counter++;

    }
    System.out.println("Decimal number : " + number);


}

}

Is it not possible to define multiple constructors in Python?

Unlike Java, you cannot define multiple constructors. However, you can define a default value if one is not passed.

def __init__(self, city="Berlin"):
  self.city = city

AttributeError: 'dict' object has no attribute 'predictors'

#Try without dot notation
sample_dict = {'name': 'John', 'age': 29}
print(sample_dict['name']) # John
print(sample_dict['age']) # 29

How do I perform HTML decoding/encoding using Python/Django?

Use daniel's solution if the set of encoded characters is relatively restricted. Otherwise, use one of the numerous HTML-parsing libraries.

I like BeautifulSoup because it can handle malformed XML/HTML :

http://www.crummy.com/software/BeautifulSoup/

for your question, there's an example in their documentation

from BeautifulSoup import BeautifulStoneSoup
BeautifulStoneSoup("Sacr&eacute; bl&#101;u!", 
                   convertEntities=BeautifulStoneSoup.HTML_ENTITIES).contents[0]
# u'Sacr\xe9 bleu!'

How do I initialize Kotlin's MutableList to empty MutableList?

You can simply write:

val mutableList = mutableListOf<Kolory>()

This is the most idiomatic way.

Alternative ways are

val mutableList : MutableList<Kolory> = arrayListOf()

or

val mutableList : MutableList<Kolory> = ArrayList()

This is exploiting the fact that java types like ArrayList are implicitly implementing the type MutableList via a compiler trick.

CSS table td width - fixed, not flexible

you also can try to use that:

table {
    table-layout:fixed;
}
table td {
    width: 30px;
    overflow: hidden;
    text-overflow: ellipsis;
}

http://www.w3schools.com/cssref/pr_tab_table-layout.asp

Creating an instance of class

  1. Allocates some dynamic memory from the free store, and creates an object in that memory using its default constructor. You never delete it, so the memory is leaked.
  2. Does exactly the same as 1; in the case of user-defined types, the parentheses are optional.
  3. Allocates some automatic memory, and creates an object in that memory using its default constructor. The memory is released automatically when the object goes out of scope.
  4. Similar to 3. Notionally, the named object foo4 is initialised by default-constructing, copying and destroying a temporary object; usually, this is elided giving the same result as 3.
  5. Allocates a dynamic object, then initialises a second by copying the first. Both objects are leaked; and there's no way to delete the first since you don't keep a pointer to it.
  6. Does exactly the same as 5.
  7. Does not compile. Foo foo5 is a declaration, not an expression; function (and constructor) arguments must be expressions.
  8. Creates a temporary object, and initialises a dynamic object by copying it. Only the dynamic object is leaked; the temporary is destroyed automatically at the end of the full expression. Note that you can create the temporary with just Foo() rather than the equivalent Foo::Foo() (or indeed Foo::Foo::Foo::Foo::Foo())

When do I use each?

  1. Don't, unless you like unnecessary decorations on your code.
  2. When you want to create an object that outlives the current scope. Remember to delete it when you've finished with it, and learn how to use smart pointers to control the lifetime more conveniently.
  3. When you want an object that only exists in the current scope.
  4. Don't, unless you think 3 looks boring and what to add some unnecessary decoration.
  5. Don't, because it leaks memory with no chance of recovery.
  6. Don't, because it leaks memory with no chance of recovery.
  7. Don't, because it won't compile
  8. When you want to create a dynamic Bar from a temporary Foo.

Get WooCommerce product categories from WordPress

You could also use wp_list_categories();

wp_list_categories( array('taxonomy' => 'product_cat', 'title_li'  => '') );

How to list processes attached to a shared memory segment in linux?

Just in case someone is interest only in what kind of process created the shared moeries, call

ls -l /dev/shm

It lists the names that are associated with the shared memories - at least on Ubuntu. Usually the names are quite telling.

IIS7 folder permissions for web application

In IIS 7 (not IIS 7.5), sites access files and folders based on the account set on the application pool for the site. By default, in IIS7, this account is NETWORK SERVICE.

Specify an Identity for an Application Pool (IIS 7)

In IIS 7.5 (Windows 2008 R2 and Windows 7), the application pools run under the ApplicationPoolIdentity which is created when the application pool starts. If you want to set ACLS for this account, you need to choose IIS AppPool\ApplicationPoolName instead of NT Authority\Network Service.

How to add a new audio (not mixing) into a video using ffmpeg?

Code to add audio to video using ffmpeg.

If audio length is greater than video length it will cut the audio to video length. If you want full audio in video remove -shortest from the cmd.

String[] cmd = new String[]{"-i", selectedVideoPath,"-i",audiopath,"-map","1:a","-map","0:v","-codec","copy", ,outputFile.getPath()};

private void execFFmpegBinaryShortest(final String[] command) {



            final File outputFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/videoaudiomerger/"+"Vid"+"output"+i1+".mp4");




            String[] cmd = new String[]{"-i", selectedVideoPath,"-i",audiopath,"-map","1:a","-map","0:v","-codec","copy","-shortest",outputFile.getPath()};


            try {

                ffmpeg.execute(cmd, new ExecuteBinaryResponseHandler() {
                    @Override
                    public void onFailure(String s) {
                        System.out.println("on failure----"+s);
                    }

                    @Override
                    public void onSuccess(String s) {
                        System.out.println("on success-----"+s);
                    }

                    @Override
                    public void onProgress(String s) {
                        //Log.d(TAG, "Started command : ffmpeg "+command);
                        System.out.println("Started---"+s);

                    }

                    @Override
                    public void onStart() {


                        //Log.d(TAG, "Started command : ffmpeg " + command);
                        System.out.println("Start----");

                    }

                    @Override
                    public void onFinish() {
                        System.out.println("Finish-----");


                    }
                });
            } catch (FFmpegCommandAlreadyRunningException e) {
                // do nothing for now
                System.out.println("exceptio :::"+e.getMessage());
            }


        }

EC2 instance types's exact network performance?

Almost everything in EC2 is multi-tenant. What the network performance indicates is what priority you will have compared with other instances sharing the same infrastructure.

If you need a guaranteed level of bandwidth, then EC2 will likely not work well for you.

How can I get terminal output in python?

>>> import subprocess
>>> cmd = [ 'echo', 'arg1', 'arg2' ]
>>> output = subprocess.Popen( cmd, stdout=subprocess.PIPE ).communicate()[0]
>>> print output
arg1 arg2

>>> 

There is a bug in using of the subprocess.PIPE. For the huge output use this:

import subprocess
import tempfile

with tempfile.TemporaryFile() as tempf:
    proc = subprocess.Popen(['echo', 'a', 'b'], stdout=tempf)
    proc.wait()
    tempf.seek(0)
    print tempf.read()

Live-stream video from one android phone to another over WiFi

If you do not need the recording and playback functionality in your app, using off-the-shelf streaming app and player is a reasonable choice.

If you do need them to be in your app, however, you will have to look into MediaRecorder API (for the server/camera app) and MediaPlayer (for client/player app).

Quick sample code for the server:

// this is your network socket
ParcelFileDescriptor pfd = ParcelFileDescriptor.fromSocket(socket);
mCamera = getCameraInstance();
mMediaRecorder = new MediaRecorder();
mCamera.unlock();
mMediaRecorder.setCamera(mCamera);
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
// this is the unofficially supported MPEG2TS format, suitable for streaming (Android 3.0+)
mMediaRecorder.setOutputFormat(8);
mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT);
mediaRecorder.setOutputFile(pfd.getFileDescriptor());
mMediaRecorder.setPreviewDisplay(mPreview.getHolder().getSurface());
mMediaRecorder.prepare();
mMediaRecorder.start();

On the player side it is a bit tricky, you could try this:

// this is your network socket, connected to the server
ParcelFileDescriptor pfd = ParcelFileDescriptor.fromSocket(socket);
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(pfd.getFileDescriptor());
mMediaPlayer.prepare();
mMediaPlayer.start();

Unfortunately mediaplayer tends to not like this, so you have a couple of options: either (a) save data from socket to file and (after you have a bit of data) play with mediaplayer from file, or (b) make a tiny http proxy that runs locally and can accept mediaplayer's GET request, reply with HTTP headers, and then copy data from the remote server to it. For (a) you would create the mediaplayer with a file path or file url, for (b) give it a http url pointing to your proxy.

See also:

Stream live video from phone to phone using socket fd

MediaPlayer stutters at start of mp3 playback