Programs & Examples On #Non convex

How to set an environment variable from a Gradle build?

You can also "prepend" the environment variable setting by using 'environment' command:

run.doFirst { environment 'SPARK_LOCAL_IP', 'localhost' }

Round a divided number in Bash

If you have integer division of positive numbers which rounds toward zero, then you can add one less than the divisor to the dividend to make it round up.

That is to say, replace X / Y with (X + Y - 1) / Y.

Proof:

  • Case 1: X = k * Y (X is integer multiple of Y): In this case, we have (k * Y + Y - 1) / Y, which splits into (k * Y) / Y + (Y - 1) / Y. The (Y - 1)/Y part rounds to zero, and we are left with a quotient of k. This is exactly what we want: when the inputs are divisible, we want the adjusted calculation to still produce the correct exact quotient.

  • Case 2: X = k * Y + m where 0 < m < Y (X is not a multiple of Y). In this case we have a numerator of k * Y + m + Y - 1, or k * Y + Y + m - 1, and we can write the division out as (k * Y)/Y + Y/Y + (m - 1)/Y. Since 0 < m < Y, 0 <= m - 1 < Y - 1, and so the last term (m - 1)/Y goes to zero. We are left with (k * Y)/Y + Y/Y which work out to k + 1. This shows that the behavior rounds up. If we have an X which is a k multiple of Y, if we add just 1 to it, the division rounds up to k + 1.

But this rounding is extremely opposite; all inexact divisions go away from zero. How about something in between?

That can be achieved by "priming" the numerator with Y/2. Instead of X/Y, calculate (X+Y/2)/Y. Instead of proof, let's go empirical on this one:

$ round()
> {
>   echo $((($1 + $2/2) / $2))
> }
$ round 4 10
0
$ round 5 10
1
$ round 6 10
1
$ round 9 10
1
$ round 10 10
1
$ round 14 10
1
$ round 15 10
2

Whenever the divisor is an even, positive number, if the numerator is congruent to half that number, it rounds up, and rounds down if it is one less than that.

For instance, round 6 12 goes to 1, as do all values which are equal to 6, modulo 12, like 18 (which goes to 2) and so on. round 5 12 goes down to 0.

For odd numbers, the behavior is correct. None of the exact rational numbers are midway between two consecutive multiples. For instance, with a denominator of 11 we have 5/11 < 5.5/11 (exact middle) < 6/11; and round 5 11 rounds down, whereas round 6 11 rounds up.

How to force input to only allow Alpha Letters?

The property event.key gave me an undefined value. Instead, I used event.keyCode:

function alphaOnly(event) {
  var key = event.keyCode;
  return ((key >= 65 && key <= 90) || key == 8);
};

Note that the value of 8 is for the backspace key.

Getting Class type from String

You can get the Class reference of any class during run time through the Java Reflection Concept.

Check the Below Code. Explanation is given below

Here is one example that uses returned Class to create an instance of AClass:

package com.xyzws;
class AClass {
    public AClass() {
        System.out.println("AClass's Constructor"); 
    }  
    static {   
        System.out.println("static block in AClass");  
    }
}
public class Program {   
    public static void main(String[] args) {
        try {       
            System.out.println("The first time calls forName:");   
            Class c = Class.forName("com.xyzws.AClass");      
            AClass a = (AClass)c.newInstance();    
            System.out.println("The second time calls forName:");  
            Class c1 = Class.forName("com.xyzws.AClass"); 
        } catch (ClassNotFoundException e) { 
            // ...
        } catch (InstantiationException e) {  
            // ...
        } catch (IllegalAccessException e) { 
            // ...
        }     
    }
}

The printed output is

    The first time calls forName:
    static block in AClass
    AClass's Constructor
    The second time calls forName:

The class has already been loaded so there is no second "static block in AClass"

The Explanation is below

Class.ForName is called to get a Class Object

By Using the Class Object we are creating the new instance of the Class.

Any doubts about this let me know

How do you normalize a file path in Bash?

Old question, but there is much simpler way if you are dealing with full path names at the shell level:

   abspath="$( cd "$path" && pwd )"

As the cd happens in a subshell it does not impact the main script.

Two variations, supposing your shell built-in commands accept -L and -P, are:

   abspath="$( cd -P "$path" && pwd -P )"    #physical path with resolved symlinks
   abspath="$( cd -L "$path" && pwd -L )"    #logical path preserving symlinks

Personally, I rarely need this later approach unless I'm fascinated with symbolic links for some reason.

FYI: variation on obtaining the starting directory of a script which works even if the script changes it's current directory later on.

name0="$(basename "$0")";                  #base name of script
dir0="$( cd "$( dirname "$0" )" && pwd )"; #absolute starting dir

The use of CD assures you always have the absolute directory, even if the script is run by commands such as ./script.sh which, without the cd/pwd, often gives just .. Useless if the script does a cd later on.

How to compile or convert sass / scss to css with node-sass (no Ruby)?

The installation of these tools may vary on different OS.

Under Windows, node-sass currently supports VS2015 by default, if you only have VS2013 in your box and meet any error while running the command, you can define the version of VS by adding: --msvs_version=2013. This is noted on the node-sass npm page.

So, the safe command line that works on Windows with VS2013 is: npm install --msvs_version=2013 gulp node-sass gulp-sass

Check if table exists without using "select from"

Just to add an extra way to do it, and depending on what you need it for you could use a handler for er_no_such_table error:1146 like this:

DELIMITER ;;
CREATE PROCEDURE `insert_in_my_table`(in my_var INT)
BEGIN
   -- Error number for table not found
   DECLARE CONTINUE HANDLER FOR 1146
   BEGIN
      -- table doesn't exists, do something...
      CREATE TABLE my_table(n INT);
      INSERT INTO my_table (n) values(my_var);
   END;
      -- table does exists, do something...
      INSERT INTO my_table (n) values(my_var);
END ;;
DELIMITER ;

Access is denied when attaching a database

I just wanted to add this information as well.

http://www.mssqltips.com/sqlservertip/2528/database-attach-failure-in-sql-server-2008-r2/

Solution

You get this error because two different logins did the detach and attach operations. So the files, when detached, were owned by the first login, but the attach failed because the login that was used was not the owner of the mdf and ldf files.

When we detach database files, the owner becomes the person who did the detach command, so to resolve the issue we need to change or add the other login as the owner of the mdf and ldf files.

Right click on the "filename.mdf" file and select properties to check the permissions of the mdf file. Here we can see that only one account has permission to the "filename.mdf" file because that was the account that was used to detach the database.

To resolve this issue, click on the Add... button to add the other login or any other login needed and give the login Full Control. You should do this for the "ldf" file as well. Once you have completed this task click the OK button. (Note for other OS versions you may have an Edit option , click this first and then you will see the Add... option.)

Split by comma and strip whitespace in Python

import re
mylist = [x for x in re.compile('\s*[,|\s+]\s*').split(string)]

Simply, comma or at least one white spaces with/without preceding/succeeding white spaces.

Please try!

How to override !important?

Overriding the !important modifier

  1. Simply add another CSS rule with !important, and give the selector a higher specificity (adding an additional tag, id or class to the selector)
  2. add a CSS rule with the same selector at a later point than the existing one (in a tie, the last one defined wins).

Some examples with a higher specificity (first is highest/overrides, third is lowest):

table td    {height: 50px !important;}
.myTable td {height: 50px !important;}
#myTable td {height: 50px !important;}

Or add the same selector after the existing one:

td {height: 50px !important;}

Disclaimer:

It's almost never a good idea to use !important. This is bad engineering by the creators of the WordPress template. In viral fashion, it forces users of the template to add their own !important modifiers to override it, and it limits the options for overriding it via JavaScript.

But, it's useful to know how to override it, if you sometimes have to.

Scanner method to get a char

Scanner sc = new Scanner (System.in)
char c = sc.next().trim().charAt(0);

Redirecting to a page after submitting form in HTML

For anyone else having the same problem, I figured it out myself.

_x000D_
_x000D_
    <html>_x000D_
      <body>_x000D_
        <form target="_blank" action="https://website.com/action.php" method="POST">_x000D_
          <input type="hidden" name="fullname" value="Sam" />_x000D_
          <input type="hidden" name="city" value="Dubai&#32;" />_x000D_
          <input onclick="window.location.href = 'https://website.com/my-account';" type="submit" value="Submit request" />_x000D_
        </form>_x000D_
      </body>_x000D_
    </html>
_x000D_
_x000D_
_x000D_

All I had to do was add the target="_blank" attribute to inline on form to open the response in a new page and redirect the other page using onclick on the submit button.

android listview item height

The height of list view items are adjusted based on its contents. In first image, no content. so height is very minimum. In second image, height is increased based on the size of the text. Because, you specified android:layout_height="wrap_content".

git clone from another directory

Use git clone c:/folder1 c:/folder2

git clone [--template=<template_directory>] [-l] [-s] [--no-hardlinks]
[-q] [-n] [--bare] [--mirror] [-o <name>] [-b <name>] [-u <upload-pack>]
[--reference <repository>] [--separate-git-dir <git dir>] [--depth <depth>]
[--[no-]single-branch] [--recursive|--recurse-submodules] [--]<repository>
[<directory>]


<repository>

    The (possibly remote) repository to clone from.
    See the URLS section below for more information on specifying repositories.
<directory>

    The name of a new directory to clone into.
    The "humanish" part of the source repository is used if no directory 
    is explicitly given (repo for /path/to/repo.git and foo for host.xz:foo/.git).
    Cloning into an existing directory is only allowed if the directory is empty.

What does the DOCKER_HOST variable do?

Upon investigation, it's also worth noting that when you want to start using docker in a new terminal window, the correct command is:

$(boot2docker shellinit)

I had tested these commands:

>>  docker info
Get http:///var/run/docker.sock/v1.15/info: dial unix /var/run/docker.sock: no such file or directory
>>  boot2docker shellinit
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/ca.pem
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/cert.pem
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/key.pem
    export DOCKER_HOST=tcp://192.168.59.103:2376
    export DOCKER_CERT_PATH=/Users/ddavison/.boot2docker/certs/boot2docker-vm
    export DOCKER_TLS_VERIFY=1
>> docker info
Get http:///var/run/docker.sock/v1.15/info: dial unix /var/run/docker.sock: no such file or directory

Notice that docker info returned that same error. however.. when using $(boot2docker shellinit)...

>>  $(boot2docker init)
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/ca.pem
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/cert.pem
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/key.pem
>>  docker info
Containers: 3
...

simple HTTP server in Java using only Java SE API

Check out NanoHttpd

NanoHTTPD is a light-weight HTTP server designed for embedding in other applications, released under a Modified BSD licence.

It is being developed at Github and uses Apache Maven for builds & unit testing"

smtpclient " failure sending mail"

Well, the "failure sending e-mail" should hopefully have a bit more detail. But there are a few things that could cause this.

  1. Restrictions on the "From" address. If you are using different from addresses, some could be blocked by your SMTP service from being able to send.
  2. Flood prevention on your SMTP service could be stopping the e-mails from going out.

Regardless if it is one of these or another error, you will want to look at the exception and inner exception to get a bit more detail.

IDENTITY_INSERT is set to OFF - How to turn it ON?

Add set off also

 SET IDENTITY_INSERT Genre ON

    INSERT INTO Genre(Id, Name, SortOrder)VALUES (12,'Moody Blues', 20) 

    SET IDENTITY_INSERT Genre  OFF

Retrieving a List from a java.util.stream.Stream in Java 8

I like to use a util method that returns a collector for ArrayList when that is what I want.

I think the solution using Collectors.toCollection(ArrayList::new) is a little too noisy for such a common operation.

Example:

ArrayList<Long> result = sourceLongList.stream()
    .filter(l -> l > 100)
    .collect(toArrayList());

public static <T> Collector<T, ?, ArrayList<T>> toArrayList() {
    return Collectors.toCollection(ArrayList::new);
}

With this answer I also want to demonstrate how simple it is to create and use custom collectors, which is very useful generally.

Check if an element is present in an array

You can use the _contains function from the underscore.js library to achieve this:

if (_.contains(haystack, needle)) {
  console.log("Needle found.");
};

Twitter bootstrap progress bar animation on page load

In contribution to ellabeauty's answer. you can also use this dynamic percentage values

$('.bar').css('width',  function(){ return ($(this).attr('data-percentage')+'%')});

And probably add custom easing to your css

.bar {
 -webkit-transition: width 2.50s ease !important;
 -moz-transition: width 2.50s ease !important;
   -o-transition: width 2.50s ease !important;
      transition: width 2.50s ease !important;
 }

Parsing JSON with Unix tools

Someone who also has xml files, might want to look at my Xidel. It is a cli, dependency-free JSONiq processor. (i.e. it also supports XQuery for xml or json processing)

The example in the question would be:

 xidel -e 'json("http://twitter.com/users/username.json")("name")'

Or with my own, non standard extension syntax:

 xidel -e 'json("http://twitter.com/users/username.json").name'

CardView not showing Shadow in Android L

Card view can't show shadow because of your RelativeLayout is on the card view's shadow. To show the shadow add margins on your Card view. For example:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<android.support.v7.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginTop="4dp"
    android:layout_marginBottom="8dp">

</android.support.v7.widget.CardView>

</RelativeLayout>

MySQL show current connection info

There are MYSQL functions you can use. Like this one that resolves the user:

SELECT USER();

This will return something like root@localhost so you get the host and the user.

To get the current database run this statement:

SELECT DATABASE();

Other useful functions can be found here: http://dev.mysql.com/doc/refman/5.0/en/information-functions.html

Redirect to a page/URL after alert button is pressed

window.location = mypage.href is a direct command for the browser to dump it's contents and start loading up some more. So for better clarification, here's what's happening in your PHP script:

echo '<script type="text/javascript">'; 
echo 'alert("review your answer");'; 
echo 'window.location = "index.php";';
echo '</script>';

1) prepare to accept a modification or addition to the current Javascript cache. 2) show the alert 3) dump everything in browser memory and get ready for some more (albeit an older method of loading a new URL (AND NOTICE that there are no "\n" (new line) indicators between the lines and is therefore causing some havoc in the JS decoder.

Let me suggest that you do this another way..

echo '<script type="text/javascript">\n'; 
echo 'alert("review your answer");\n'; 
echo 'document.location.href = "index.php";\n';
echo '</script>\n';

1) prepare to accept a modification or addition to the current Javascript cache. 2) show the alert 3) dump everything in browser memory and get ready for some more (in a better fashion than before) And WOW - it all works because the JS decoder can see that each command is anow a new line.

Best of luck!

intellij incorrectly saying no beans of type found for autowired repository

I am using spring-boot 2.0, and intellij 2018.1.1 ultimate edition and I faced the same issue.

I solved by placing @EnableAutoConfiguration in the main application class

@SpringBootApplication
@EnableAutoConfiguration
class App{
/**/
}

Where does R store packages?

Thanks for the direction from the above two answerers. James Thompson's suggestion worked best for Windows users.

  1. Go to where your R program is installed. This is referred to as R_Home in the literature. Once you find it, go to the /etc subdirectory.

    C:\R\R-2.10.1\etc
    
  2. Select the file in this folder named Rprofile.site. I open it with VIM. You will find this is a bare-bones file with less than 20 lines of code. I inserted the following inside the code:

    # my custom library path
    .libPaths("C:/R/library")
    

    (The comment added to keep track of what I did to the file.)

  3. In R, typing the .libPaths() function yields the first target at C:/R/Library

NOTE: there is likely more than one way to achieve this, but other methods I tried didn't work for some reason.

Properties private set;

while(dr.read())
{
    returnPersonList.add( 
        new Person(dr.GetInt32(1), dr.GetInt32(0), dr.GetString(2)));
}

where:

public class Person
{
    public Person(int age, int id, string name) 
    {
        Age = age;
        Id = id;
        Name = name;
    }
}

View not attached to window manager crash

How to reproduce the bug:

  1. Enable this option on your device: Settings -> Developer Options -> Don't keep Activities.
  2. Press Home button while the AsyncTask is executing and the ProgressDialog is showing.

The Android OS will destroy an activity as soon as it is hidden. When onPostExecute is called the Activity will be in "finishing" state and the ProgressDialog will be not attached to Activity.

How to fix it:

  1. Check for the activity state in your onPostExecute method.
  2. Dismiss the ProgressDialog in onDestroy method. Otherwise, android.view.WindowLeaked exception will be thrown. This exception usually comes from dialogs that are still active when the activity is finishing.

Try this fixed code:

public class YourActivity extends Activity {

    private void showProgressDialog() {
        if (pDialog == null) {
            pDialog = new ProgressDialog(StartActivity.this);
            pDialog.setMessage("Loading. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
        }
        pDialog.show();
    }

    private void dismissProgressDialog() {
        if (pDialog != null && pDialog.isShowing()) {
            pDialog.dismiss();
        }
    }

    @Override
    protected void onDestroy() {
        dismissProgressDialog();
        super.onDestroy();
    }

    class LoadAllProducts extends AsyncTask<String, String, String> {

        // Before starting background thread Show Progress Dialog
        @Override
        protected void onPreExecute() {
            showProgressDialog();
        }

        //getting All products from url
        protected String doInBackground(String... args) {
            doMoreStuff("internet");
            return null;
        }

        // After completing background task Dismiss the progress dialog
        protected void onPostExecute(String file_url) {
            if (YourActivity.this.isDestroyed()) { // or call isFinishing() if min sdk version < 17
                return;
            }
            dismissProgressDialog();
            something(note);
        }
    }
}

PuTTY scripting to log onto host

I'm not sure why previous answers haven't suggested that the original poster set up a shell profile (bashrc, .tcshrc, etc.) that executed their commands automatically every time they log in on the server side.

The quest that brought me to this page for help was a bit different -- I wanted multiple PuTTY shortcuts for the same host that would execute different startup commands.

I came up with two solutions, both of which worked:

(background) I have a folder with a variety of PuTTY shortcuts, each with the "target" property in the shortcut tab looking something like:

"C:\Program Files (x86)\PuTTY\putty.exe" -load host01

with each load corresponding to a PuTTY profile I'd saved (with different hosts in the "Session" tab). (Mostly they only differ in color schemes -- I like to have each group of related tasks share a color scheme in the terminal window, with critical tasks, like logging in as root on a production system, performed only in distinctly colored windows.)

The folder's Windows properties are set to very clean and stripped down -- it functions as a small console with shortcut icons for each of my frequent remote PuTTY and RDP connections.

(solution 1) As mentioned in other answers the -m switch is used to configure a script on the Windows side to run, the -t switch is used to stay connected, but I found that it was order-sensitive if I wanted to get it to run without exiting

What I finally got to work after a lot of trial and error was:

(shortcut target field):

"C:\Program Files (x86)\PuTTY\putty.exe" -t -load "SSH Proxy" -m "C:\Users\[me]\Documents\hello-world-bash.txt"

where the file being executed looked like

echo "Hello, World!"
echo ""
export PUTTYVAR=PROXY
/usr/local/bin/bash

(no semicolons needed)

This runs the scripted command (in my case just printing "Hello, world" on the terminal) and sets a variable that my remote session can interact with.

Note for debugging: when you run PuTTY it loads the -m script, if you edit the script you need to re-launch PuTTY instead of just restarting the session.

(solution 2) This method feels a lot cleaner, as the brains are on the remote Unix side instead of the local Windows side:

From Putty master session (not "edit settings" from existing session) load a saved config and in the SSH tab set remote command to:

export PUTTYVAR=GREEN; bash -l

Then, in my .bashrc, I have a section that performs different actions based on that variable:

case ${PUTTYVAR} in
  "")
    echo "" 
    ;;
  "PROXY")
    # this is the session config with all the SSH tunnels defined in it
    echo "";
    echo "Special window just for holding tunnels open." ;
    echo "";
    PROMPT_COMMAND='echo -ne "\033]0;Proxy Session @master01\$\007"'
    alias temppass="ssh keyholder.example.com makeonetimepassword"
    alias | grep temppass
    ;;
  "GREEN")
    echo "";
    echo "It's not easy being green"
    ;;
  "GRAY")
    echo ""
    echo "The gray ghost"
    ;;
  *)
    echo "";
    echo "Unknown PUTTYVAR setting ${PUTTYVAR}"
    ;;
esac

(solution 3, untried)

It should also be possible to have bash skip my .bashrc and execute a different startup script, by putting this in the PuTTY SSH command field:

bash --rcfile .bashrc_variant -l 

Accessing a property in a parent Component

On Angular 6, I access parent properties by injecting the parent via constructor. Not the best solution but it works:

 constructor(@Optional() public parentComponentInjectionObject: ParentComponent){
    // And access like this:
    parentComponentInjectionObject.thePropertyYouWantToAccess;
}

Removing time from a Date object?

Date dateWithoutTime =
    new Date(myDate.getYear(),myDate.getMonth(),myDate.getDate()) 

This is deprecated, but the fastest way to do it.

Session unset, or session_destroy?

Something to be aware of, the $_SESSION variables are still set in the same page after calling session_destroy() where as this is not the case when using unset($_SESSION) or $_SESSION = array(). Also, unset($_SESSION) blows away the $_SESSION superglobal so only do this when you're destroying a session.

With all that said, it's best to do like the PHP docs has it in the first example for session_destroy().

Running AngularJS initialization code when view is loaded

I use the following template in my projects:

angular.module("AppName.moduleName", [])

/**
 * @ngdoc controller
 * @name  AppName.moduleName:ControllerNameController
 * @description Describe what the controller is responsible for.
 **/
    .controller("ControllerNameController", function (dependencies) {

        /* type */ $scope.modelName = null;
        /* type */ $scope.modelName.modelProperty1 = null;
        /* type */ $scope.modelName.modelPropertyX = null;

        /* type */ var privateVariable1 = null;
        /* type */ var privateVariableX = null;

        (function init() {
            // load data, init scope, etc.
        })();

        $scope.modelName.publicFunction1 = function () /* -> type  */ {
            // ...
        };

        $scope.modelName.publicFunctionX = function () /* -> type  */ {
            // ...
        };

        function privateFunction1() /* -> type  */ {
            // ...
        }

        function privateFunctionX() /* -> type  */ {
            // ...
        }

    });

<div> cannot appear as a descendant of <p>

If you are using ReactTooltip, to make the warning disappear, you can now add a wrapper prop with a value of span, like this:

<ReactTooltip wrapper="span" />

Since the span is an inline element, it should no longer complain.

Enabling CORS in Cloud Functions for Firebase

No CORS solutions worked for me... till now!

Not sure if anyone else ran into the same issue I did, but I set up CORS like 5 different ways from examples I found and nothing seemed to work. I set up a minimal example with Plunker to see if it was really a bug, but the example ran beautifully. I decided to check the firebase functions logs (found in the firebase console) to see if that could tell me anything. I had a couple errors in my node server code, not CORS related, that when I debugged released me of my CORS error message. I don't know why code errors unrelated to CORS returns a CORS error response, but it led me down the wrong rabbit hole for a good number of hours...

tl;dr - check your firebase function logs if no CORS solutions work and debug any errros you have

Get current date in Swift 3?

You can do it in this way with Swift 3.0:

let date = Date()
let calendar = Calendar.current
let components = calendar.dateComponents([.year, .month, .day], from: date)

let year =  components.year
let month = components.month
let day = components.day

print(year)
print(month)
print(day)

Pressed <button> selector

Maybe :active over :focus with :hover will help! Try

button {
background:lime;
}

button:hover {
background:green;
}

button:focus {
background:gray;
}

button:active {
background:red;
}

Then:

<button onkeydown="alerted_of_key_pressed()" id="button" title="Test button" href="#button">Demo</button>

Then:

<!--JAVASCRIPT-->
<script>
function alerted_of_key_pressed() { alert("You pressed a key when hovering over this button.") }
</script>
 Sorry about that last one. :) I was just showing you a cool function! 
Wait... did I just emphasize a code block? This is cool!!!

Convert StreamReader to byte[]

Just throw everything you read into a MemoryStream and get the byte array in the end. As noted, you should be reading from the underlying stream to get the raw bytes.

var bytes = default(byte[]);
using (var memstream = new MemoryStream())
{
    var buffer = new byte[512];
    var bytesRead = default(int);
    while ((bytesRead = reader.BaseStream.Read(buffer, 0, buffer.Length)) > 0)
        memstream.Write(buffer, 0, bytesRead);
    bytes = memstream.ToArray();
}

Or if you don't want to manage the buffers:

var bytes = default(byte[]);
using (var memstream = new MemoryStream())
{
    reader.BaseStream.CopyTo(memstream);
    bytes = memstream.ToArray();
}

How to make flutter app responsive according to different screen size?

My approach to the problem is similar to the way datayeah did it. I had a lot of hardcoded width and height values and the app looked fine on a specific device. So I got the screen height of the device and just created a factor to scale the hardcoded values.

double heightFactor = MediaQuery.of(context).size.height/708

where 708 is the height of the specific device.

HTML5 image icon to input placeholder

I don't know whether there's a better answer out there as time goes by but this is simple and it works;

input[type='email'] {
  background: white url(images/mail.svg) no-repeat ;
}
input[type='email']:focus {
  background-image: none;
}

Style it up to suit.

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

You can instruct tesseract to use only digits, and if that is not accurate enough then best chance of getting better results is to go trough training process: http://www.resolveradiologic.com/blog/2013/01/15/training-tesseract/

How do I create a batch file timer to execute / call another batch throughout the day

Below is a batch file that will wait for 1 minute, check the day, and then perform an action. It uses PING.EXE, but requires no files that aren't included with Windows.

@ECHO OFF

:LOOP
ECHO Waiting for 1 minute...
  PING -n 60 127.0.0.1>nul
  IF %DATE:~0,3%==Mon CALL SomeOtherFile.cmd
  IF %DATE:~0,3%==Tue CALL SomeOtherFile.cmd
  IF %DATE:~0,3%==Wed CALL SomeOtherFile.cmd
  IF %DATE:~0,3%==Thu CALL WootSomeOtherFile.cmd
  IF %DATE:~0,3%==Fri CALL SomeOtherFile.cmd
  IF %DATE:~0,3%==Sat ECHO Saturday...nothing to do.
  IF %DATE:~0,3%==Sun ECHO Sunday...nothing to do.
GOTO LOOP

It could be improved upon in many ways, but it might get you started.

Cast int to varchar

I solved a problem to comparing a integer Column x a varchar column with

where CAST(Column_name AS CHAR CHARACTER SET latin1 ) collate latin1_general_ci = varchar_column_name

What is the 'dynamic' type in C# 4.0 used for?

I am surprised that nobody mentioned multiple dispatch. The usual way to work around this is via Visitor pattern and that is not always possible so you end up with stacked is checks.

So here is a real life example of an application of my own. Instead of doing:

public static MapDtoBase CreateDto(ChartItem item)
{
    if (item is ElevationPoint) return CreateDtoImpl((ElevationPoint)item);
    if (item is MapPoint) return CreateDtoImpl((MapPoint)item);
    if (item is MapPolyline) return CreateDtoImpl((MapPolyline)item);
    //other subtypes follow
    throw new ObjectNotFoundException("Counld not find suitable DTO for " + item.GetType());
}

You do:

public static MapDtoBase CreateDto(ChartItem item)
{
    return CreateDtoImpl(item as dynamic);
}

private static MapDtoBase CreateDtoImpl(ChartItem item)
{
    throw new ObjectNotFoundException("Counld not find suitable DTO for " + item.GetType());
}

private static MapDtoBase CreateDtoImpl(MapPoint item)
{
    return new MapPointDto(item);
}

private static MapDtoBase CreateDtoImpl(ElevationPoint item)
{
    return new ElevationDto(item);
}

Note that in first case ElevationPoint is subclass of MapPoint and if it's not placed before MapPointit will never be reached. This is not the case with dynamic, as the closest matching method will be called.

As you might guess from the code, that feature came handy while I was performing translation from ChartItem objects to their serializable versions. I didn't want to pollute my code with visitors and I didn't want also to pollute my ChartItem objects with useless serialization specific attributes.

How to format date and time in Android?

This is my method, you can define and input and output format.

public static String formattedDateFromString(String inputFormat, String outputFormat, String inputDate){
    if(inputFormat.equals("")){ // if inputFormat = "", set a default input format.
        inputFormat = "yyyy-MM-dd hh:mm:ss";
    }
    if(outputFormat.equals("")){
        outputFormat = "EEEE d 'de' MMMM 'del' yyyy"; // if inputFormat = "", set a default output format.
    }
    Date parsed = null;
    String outputDate = "";

    SimpleDateFormat df_input = new SimpleDateFormat(inputFormat, java.util.Locale.getDefault());
    SimpleDateFormat df_output = new SimpleDateFormat(outputFormat, java.util.Locale.getDefault());

    // You can set a different Locale, This example set a locale of Country Mexico.
    //SimpleDateFormat df_input = new SimpleDateFormat(inputFormat, new Locale("es", "MX"));
    //SimpleDateFormat df_output = new SimpleDateFormat(outputFormat, new Locale("es", "MX"));

    try {
        parsed = df_input.parse(inputDate);
        outputDate = df_output.format(parsed);
    } catch (Exception e) { 
        Log.e("formattedDateFromString", "Exception in formateDateFromstring(): " + e.getMessage());
    }
    return outputDate;

}

How to make a JSON call to a url?

Because the URL isn't on the same domain as your website, you need to use JSONP.

For example: (In jQuery):

$.getJSON(
    'http://soundcloud.com/oembed?url=http%3A//soundcloud.com/forss/flickermood&format=js&callback=?', 
    function(data) { ... }
);

This works by creating a <script> tag like this one:

<script src="http://soundcloud.com/oembed?url=http%3A//soundcloud.com/forss/flickermood&format=js&callback=someFunction" type="text/javascript"></script>

Their server then emits Javascript that calls someFunction with the data to retrieve.
`someFunction is an internal callback generated by jQuery that then calls your callback.

How to get the mouse position without events (without moving the mouse)?

What you can do is create variables for the x and y coordinates of your cursor, update them whenever the mouse moves and call a function on an interval to do what you need with the stored position.

The downside to this of course is that at least one initial movement of the mouse is required to have it work. As long as the cursor updates its position at least once, we are able to find its position regardless of whether it moves again.

var cursor_x = -1;
var cursor_y = -1;
document.onmousemove = function(event)
{
 cursor_x = event.pageX;
 cursor_y = event.pageY;
}
setInterval(check_cursor, 1000);
function check_cursor(){console.log('Cursor at: '+cursor_x+', '+cursor_y);}

The preceding code updates once a second with a message of where your cursor is. I hope this helps.

Sorting a Dictionary in place with respect to keys

Due to this answers high search placing I thought the LINQ OrderBy solution is worth showing:

class Person
{
    public Person(string firstname, string lastname)
    {
        FirstName = firstname;
        LastName = lastname;
    }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

static void Main(string[] args)
{
    Dictionary<Person, int> People = new Dictionary<Person, int>();

    People.Add(new Person("John", "Doe"), 1);
    People.Add(new Person("Mary", "Poe"), 2);
    People.Add(new Person("Richard", "Roe"), 3);
    People.Add(new Person("Anne", "Roe"), 4);
    People.Add(new Person("Mark", "Moe"), 5);
    People.Add(new Person("Larry", "Loe"), 6);
    People.Add(new Person("Jane", "Doe"), 7);

    foreach (KeyValuePair<Person, int> person in People.OrderBy(i => i.Key.LastName))
    {
        Debug.WriteLine(person.Key.LastName + ", " + person.Key.FirstName + " - Id: " + person.Value.ToString());
    }
}

Output:

Doe, John - Id: 1
Doe, Jane - Id: 7
Loe, Larry - Id: 6
Moe, Mark - Id: 5
Poe, Mary - Id: 2
Roe, Richard - Id: 3
Roe, Anne - Id: 4

In this example it would make sense to also use ThenBy for first names:

foreach (KeyValuePair<Person, int> person in People.OrderBy(i => i.Key.LastName).ThenBy(i => i.Key.FirstName))

Then the output is:

Doe, Jane - Id: 7
Doe, John - Id: 1
Loe, Larry - Id: 6
Moe, Mark - Id: 5
Poe, Mary - Id: 2
Roe, Anne - Id: 4
Roe, Richard - Id: 3

LINQ also has the OrderByDescending and ThenByDescending for those that need it.

How to put space character into a string name in XML?

Space variants:

<string name="space_demo">|&#x20;|&#x2009;|&#x200A;|</string>

| SPACE | THIN SPACE | HAIR SPACE |

How to sort dates from Oldest to Newest in Excel?

Here's how to sort unsorted dates:

Drag down the column to select the dates you want to sort.

Click Home tab > arrow under Sort & Filter, and then click Sort Oldest to Newest, or Sort Newest to Oldest.

NOTE: If the results aren't what you expected, the column might have dates that are stored as text instead of dates. Convert dates stored as text to dates.

Set LIMIT with doctrine 2?

 $qb = $this->getDoctrine()->getManager()->createQueryBuilder();  
 $qb->select('p') ->from('Pandora\UserBundle\Entity\PhoneNumber', 'p');
$qb->where('p.number = :number');
$qb->OrWhere('p.validatedNumber=:number');
$qb->setMaxResults(1);
$qb->setParameter('number',$postParams['From'] );
$result = $qb->getQuery()->getResult();
 $data=$result[0];

How to get the employees with their managers

This is a classic self-join, try the following:

SELECT e.ename, e.empno, m.ename as manager, e.mgr
FROM
    emp e, emp m
WHERE e.mgr = m.empno

And if you want to include the president which has no manager then instead of an inner join use an outer join in Oracle syntax:

SELECT e.ename, e.empno, m.ename as manager, e.mgr
FROM
    emp e, emp m
WHERE e.mgr = m.empno(+)

Or in ANSI SQL syntax:

SELECT e.ename, e.empno, m.ename as manager, e.mgr
FROM
    emp e
    LEFT OUTER JOIN emp m
        ON e.mgr = m.empno

docker-compose up for only certain containers

I actually had a very similar challenge on my current project. That broght me to the idea of writing a small script which I called docker-compose-profile (or short: dcp). I published this today on GitLab as docker-compose-profile. So in short: I now can start several predefined docker-compose profiles using a command like dcp -p some-services "up -d". Feel free to try it out and give some feedback or suggestions for further improvements.

Changing WPF title bar background color

In WPF the titlebar is part of the non-client area, which can't be modified through the WPF window class. You need to manipulate the Win32 handles (if I remember correctly).
This article could be helpful for you: Custom Window Chrome in WPF.

What is a Maven artifact?

Maven organizes its build in projects.

An artifact in maven is a resource generated by a maven project. Each maven project can have exactly one artifact like a jar, war, ear, etc.
The project's configuration file "pom.xml" describes how the artifact is build, how unit tests are run, etc. Commonly a software project build with maven consists of many maven-projects that build artifacts (e.g. jars) that constitute the product.
E.g.

Root-Project   // produces no artifact, simply triggers the build of the other projects
  App-Project  // The application, that uses the libraries
  Lib1-Project // A project that creates a library (jar)
  Lib2-Project // Another library
  Doc-Project  // A project that generates the user documentation from some resources

Maven artifacts are not limited to java resources. You can generate whatever resource you need. E.g. documentation, project-site, zip-archives, native-libraries, etc.

Each maven project has a unique identifier consiting of [groupId, artifactId, version]. When a maven project requires resources of another project a dependency is configured in it's pom.xml using the above-mentioned identifier. Maven then automatically resolves the dependencies when a build is triggered. The artifacts of the required projects are then loaded either from the local repository, which is a simple directory in your user's home, or from other (remote) repositories specified in you pom.xml.

Changing datagridview cell color based on condition

I may suggest NOT looping over each rows EACH time CellFormating is called, because it is called everytime A SINGLE ROW need to be refreshed.

Private Sub dgv_DisplayData_Vertical_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles dgv_DisplayData_Vertical.CellFormatting
        Try

            If dgv_DisplayData_Vertical.Rows(e.RowIndex).Cells("LevelID").Value.ToString() = "6" Then

                e.CellStyle.BackColor = Color.DimGray
            End If
            If dgv_DisplayData_Vertical.Rows(e.RowIndex).Cells("LevelID").Value.ToString() = "5" Then
                e.CellStyle.BackColor = Color.DarkSlateGray
            End If
            If dgv_DisplayData_Vertical.Rows(e.RowIndex).Cells("LevelID").Value.ToString() = "4" Then
                e.CellStyle.BackColor = Color.SlateGray
            End If
            If dgv_DisplayData_Vertical.Rows(e.RowIndex).Cells("LevelID").Value.ToString() = "3" Then
                e.CellStyle.BackColor = Color.LightGray
            End If
            If dgv_DisplayData_Vertical.Rows(e.RowIndex).Cells("LevelID").Value.ToString() = "0" Then
                e.CellStyle.BackColor = Color.White
            End If

        Catch ex As Exception

        End Try

    End Sub

HTML table headers always visible at top of window when viewing a large table

If you use a full screen table you are maybe interested in setting th to display:fixed; and top:0; or try a very similar approach via css.

Update

Just quickly build up a working solution with iframes (html4.0). This example IS NOT standard conform, however you will easily be able to fix it:

outer.html

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">   
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">     
    <head>      
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />   
        <title>Outer</title>
  <body>
    <iframe src="test.html" width="200" height="100"></iframe>
    </body>
</html> 

test.html

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">   
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">     
    <head>      
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />   
        <title>Floating</title>
    <style type="text/css">
      .content{
        position:relative; 
      }

      thead{
        background-color:red;
        position:fixed; 
        top:0;
      }
    </style>
  <body>
    <div class="content">      
      <table>
        <thead>
          <tr class="top"><td>Title</td></tr>
        </head>
        <tbody>
          <tr><td>a</td></tr>
          <tr><td>b</td></tr>
          <tr><td>c</td></tr>
          <tr><td>d</td></tr>
          <tr><td>e</td></tr>
          <tr><td>e</td></tr>
          <tr><td>e</td></tr>
          <tr><td>e</td></tr>
          <tr><td>e</td></tr>
          <tr><td>e</td></tr>
        </tbody>
      </table>
    </div>
    </body>
</html> 

Creating a selector from a method name with parameters

SEL is a type that represents a selector in Objective-C. The @selector() keyword returns a SEL that you describe. It's not a function pointer and you can't pass it any objects or references of any kind. For each variable in the selector (method), you have to represent that in the call to @selector. For example:

-(void)methodWithNoParameters;
SEL noParameterSelector = @selector(methodWithNoParameters);

-(void)methodWithOneParameter:(id)parameter;
SEL oneParameterSelector = @selector(methodWithOneParameter:); // notice the colon here

-(void)methodWIthTwoParameters:(id)parameterOne and:(id)parameterTwo;
SEL twoParameterSelector = @selector(methodWithTwoParameters:and:); // notice the parameter names are omitted

Selectors are generally passed to delegate methods and to callbacks to specify which method should be called on a specific object during a callback. For instance, when you create a timer, the callback method is specifically defined as:

-(void)someMethod:(NSTimer*)timer;

So when you schedule the timer you would use @selector to specify which method on your object will actually be responsible for the callback:

@implementation MyObject

-(void)myTimerCallback:(NSTimer*)timer
{
    // do some computations
    if( timerShouldEnd ) {
      [timer invalidate];
    }
}

@end

// ...

int main(int argc, const char **argv)
{
    // do setup stuff
    MyObject* obj = [[MyObject alloc] init];
    SEL mySelector = @selector(myTimerCallback:);
    [NSTimer scheduledTimerWithTimeInterval:30.0 target:obj selector:mySelector userInfo:nil repeats:YES];
    // do some tear-down
    return 0;
}

In this case you are specifying that the object obj be messaged with myTimerCallback every 30 seconds.

How to make <label> and <input> appear on the same line on an HTML form?

For Bootstrap 4 it could be done with class="form-group" style="display: flex"

<div class="form-group" style="display: flex">
    <label>Topjava comment:</label>
    <input class="form-control" type="checkbox"/>
</div>

HttpClient 4.0.1 - how to release connection?

The recommended way, by Httpcomponents 4.1, is to close connection and release any underlying resources:

EntityUtils.consume(HttpEntity)

where HttpEntity passed is a response entity.

Could not open input file: artisan

After creating the project you should move in the folder before issuing the command

Convert ASCII TO UTF-8 Encoding

Using iconv looks like best solution but i my case I have Notice form this function: "Detected an illegal character in input string in" (without igonore). I use 2 functions to manipulate ASCII strings convert it to array of ASCII code and then serialize:

public static function ToAscii($string) {
    $strlen = strlen($string);
    $charCode = array();
    for ($i = 0; $i < $strlen; $i++) {
        $charCode[] = ord(substr($string, $i, 1));
    }
    $result = json_encode($charCode);
    return $result;
}

public static function fromAscii($string) {
    $charCode = json_decode($string);
    $result = '';
    foreach ($charCode as $code) {
        $result .= chr($code);
    };
    return $result;
}

How can I change the font size using seaborn FacetGrid?

The FacetGrid plot does produce pretty small labels. While @paul-h has described the use of sns.set as a way to the change the font scaling, it may not be the optimal solution since it will change the font_scale setting for all plots.

You could use the seaborn.plotting_context to change the settings for just the current plot:

with sns.plotting_context(font_scale=1.5):
    sns.factorplot(x, y ...)

AngularJS sorting rows by table header

Here is an example that sorts by the header. This table is dynamic and changes with the JSON size.

I was able to build a dynamic table off of some other people's examples and documentation. http://jsfiddle.net/lastlink/v7pszemn/1/

<tr>
    <th class="{{header}}" ng-repeat="(header, value) in items[0]" ng-click="changeSorting(header)">
    {{header}}
  <i ng-class="selectedCls2(header)"></i>
</tr>

<tbody>
    <tr ng-repeat="row in pagedItems[currentPage] | orderBy:sort.sortingOrder:sort.reverse">
        <td ng-repeat="cell in row">
              {{cell}}
       </td>
    </tr>

Although the columns are out of order, on my .NET project they are in order.

React Native: Getting the position of an element

This seems to have changed in the latest version of React Native when using refs to calculate.

Declare refs this way.

  <View
    ref={(image) => {
    this._image = image
  }}>

And find the value this way.

  _measure = () => {
    this._image._component.measure((width, height, px, py, fx, fy) => {
      const location = {
        fx: fx,
        fy: fy,
        px: px,
        py: py,
        width: width,
        height: height
      }
      console.log(location)
    })
  }

git rebase fatal: Needed a single revision

You need to provide the name of a branch (or other commit identifier), not the name of a remote to git rebase.

E.g.:

git rebase origin/master

not:

git rebase origin

Note, although origin should resolve to the the ref origin/HEAD when used as an argument where a commit reference is required, it seems that not every repository gains such a reference so it may not (and in your case doesn't) work. It pays to be explicit.

How to set a timeout on a http.request() in Node?

Elaborating on the answer @douwe here is where you would put a timeout on a http request.

// TYPICAL REQUEST
var req = https.get(http_options, function (res) {                                                                                                             
    var data = '';                                                                                                                                             

    res.on('data', function (chunk) { data += chunk; });                                                                                                                                                                
    res.on('end', function () {
        if (res.statusCode === 200) { /* do stuff with your data */}
        else { /* Do other codes */}
    });
});       
req.on('error', function (err) { /* More serious connection problems. */ }); 

// TIMEOUT PART
req.setTimeout(1000, function() {                                                                                                                              
    console.log("Server connection timeout (after 1 second)");                                                                                                                  
    req.abort();                                                                                                                                               
});

this.abort() is also fine.

How to UPSERT (MERGE, INSERT ... ON DUPLICATE UPDATE) in PostgreSQL?

WITH UPD AS (UPDATE TEST_TABLE SET SOME_DATA = 'Joe' WHERE ID = 2 
RETURNING ID),
INS AS (SELECT '2', 'Joe' WHERE NOT EXISTS (SELECT * FROM UPD))
INSERT INTO TEST_TABLE(ID, SOME_DATA) SELECT * FROM INS

Tested on Postgresql 9.3

How to compare files from two different branches?

If you want to make a diff against current branch you can ommit it and use:

git diff $BRANCH -- path/to/file

this way it will diff from current branch to the referenced branch ($BRANCH).

How do I get today's date in C# in mm/dd/yyyy format?

If you want it without the year:

DateTime.Now.ToString("MM/DD");

DateTime.ToString() has a lot of cool format strings:

http://msdn.microsoft.com/en-us/library/aa326721.aspx

How does inline Javascript (in HTML) work?

You've got it nearly correct, but you haven't accounted for the this value supplied to the inline code.

<a href="#" onclick="alert(this)">Click Me</a>

is actually closer to:

<a href="#" id="click_me">Click Me</a>
<script type="text/javascript">
document.getElementById('click_me').addEventListener("click", function(event) {
    (function(event) {
        alert(this);
    }).call(document.getElementById('click_me'), event);
});
</script>

Inline event handlers set this equal to the target of the event. You can also use anonymous function in inline script

<a href="#" onclick="(function(){alert(this);})()">Click Me</a>

define a List like List<int,string>?

With the new ValueTuple from C# 7 (VS 2017 and above), there is a new solution:

List<(int,string)> mylist= new List<(int,string)>();

Which creates a list of ValueTuple type. If you're targeting .Net Framework 4.7+ or .Net Core, it's native, otherwise you have to get the ValueTuple package from nuget.

It's a struct opposing to Tuple, which is a class. It also has the advantage over the Tuple class that you could create a named tuple, like this:

var mylist = new List<(int myInt, string myString)>();

That way you can access like mylist[0].myInt and mylist[0].myString

Making a mocked method return an argument that was passed to it

I use something similar (basically it's the same approach). Sometimes it's useful to have a mock object return pre-defined output for certain inputs. That goes like this:

private Hashtable<InputObject,  OutputObject> table = new Hashtable<InputObject, OutputObject>();
table.put(input1, ouput1);
table.put(input2, ouput2);

...

when(mockObject.method(any(InputObject.class))).thenAnswer(
       new Answer<OutputObject>()
       {
           @Override
           public OutputObject answer(final InvocationOnMock invocation) throws Throwable
           {
               InputObject input = (InputObject) invocation.getArguments()[0];
               if (table.containsKey(input))
               {
                   return table.get(input);
               }
               else
               {
                   return null; // alternatively, you could throw an exception
               }
           }
       }
       );

On linux SUSE or RedHat, how do I load Python 2.7

Execute the below commands to make yum work as well as python2.7

yum groupinstall -y development
yum groupinstall -y 'development tools'
yum install -y zlib-dev openssl-devel wget sqlite-devel bzip2-devel
yum -y install gcc gcc-c++ numpy python-devel scipy git boost*
yum install -y *lapack*
yum install -y gcc gcc-c++ make bison flex autoconf libtool memcached libevent libevent-devel uuidd libuuid-devel  boost boost-devel libcurl-dev libcurl curl gperf mysql-devel

cd
mkdir srk
cd srk 
wget http://www.python.org/ftp/python/2.7.6/Python-2.7.6.tar.xz
yum install xz-libs
xz -d Python-2.7.6.tar.xz
tar -xvf Python-2.7.6.tar
cd Python-2.7.6
./configure --prefix=/usr/local
make
make altinstall



echo "export PATH="/usr/local/bin:$PATH"" >> /etc/profile
source /etc/profile
mv /usr/bin/python /usr/bin/python.bak
update-alternatives --install /usr/bin/python python /usr/bin/python2.6 1
update-alternatives --install /usr/bin/python python /usr/local/bin/python2.7 2
update-alternatives --config python
sed -i "s/python/python2.6/g" /usr/bin/yum

How to import/include a CSS file using PHP code and not HTML code?

Just put

echo "<link rel='stylesheet' type='text/css' href='CSS/main.css'>";

inside the php code, then your style is incuded. Worked for me, I tried.

Conversion from byte array to base64 and back

The reason the encoded array is longer by about a quarter is that base-64 encoding uses only six bits out of every byte; that is its reason of existence - to encode arbitrary data, possibly with zeros and other non-printable characters, in a way suitable for exchange through ASCII-only channels, such as e-mail.

The way you get your original array back is by using Convert.FromBase64String:

 byte[] temp_backToBytes = Convert.FromBase64String(temp_inBase64);

Angular window resize event

all the solutions are not working with server-side or in angular universal

Properties file in python (similar to Java Properties)

if you don't have multi line properties and a very simple need, a few lines of code can solve it for you:

File t.properties:

a=b
c=d
e=f

Python code:

with open("t.properties") as f:
    l = [line.split("=") for line in f.readlines()]
    d = {key.strip(): value.strip() for key, value in l}

C# - Substring: index and length must refer to a location within the string

The second parameter in Substring is the length of the substring, not the end index.

You should probably include handling to check that it does indeed start with what you expect, end with what you expect, and is at least as long as you expect. And then if it doesn't match, you can either do something else or throw a meaningful error.

Here's some example code that validates that url contains your strings, that also is refactored a bit to make it easier to change the prefix/suffix to strip:

var prefix = "www.example.com/";
var suffix = ".jpg";
string url = "www.example.com/aaa/bbb.jpg";

if (url.StartsWith(prefix) && url.EndsWith(suffix) && url.Length >= (prefix.Length + suffix.Length))
{
    string newString = url.Substring(prefix.Length, url.Length - prefix.Length - suffix.Length);
    Console.WriteLine(newString);
}
else
    //handle invalid state

writing integer values to a file using out.write()

any of these should work

outf.write("%s" % num)

outf.write(str(num))

print >> outf, num

TSQL PIVOT MULTIPLE COLUMNS

Since you want to pivot multiple columns of data, I would first suggest unpivoting the result, score and grade columns so you don't have multiple columns but you will have multiple rows.

Depending on your version of SQL Server you can use the UNPIVOT function or CROSS APPLY. The syntax to unpivot the data will be similar to:

select ratio, col, value
from GRAND_TOTALS
cross apply
(
  select 'result', cast(result as varchar(10)) union all
  select 'score', cast(score as varchar(10)) union all
  select 'grade', grade
) c(col, value)

See SQL Fiddle with Demo. Once the data has been unpivoted, then you can apply the PIVOT function:

select ratio = col,
  [current ratio], [gearing ratio], [performance ratio], total
from
(
  select ratio, col, value
  from GRAND_TOTALS
  cross apply
  (
    select 'result', cast(result as varchar(10)) union all
    select 'score', cast(score as varchar(10)) union all
    select 'grade', grade
  ) c(col, value)
) d
pivot
(
  max(value)
  for ratio in ([current ratio], [gearing ratio], [performance ratio], total)
) piv;

See SQL Fiddle with Demo. This will give you the result:

|  RATIO | CURRENT RATIO | GEARING RATIO | PERFORMANCE RATIO |     TOTAL |
|--------|---------------|---------------|-------------------|-----------|
|  grade |          Good |          Good |      Satisfactory |      Good |
| result |       1.29400 |       0.33840 |           0.04270 |    (null) |
|  score |      60.00000 |      70.00000 |          50.00000 | 180.00000 |

How to hide a div from code (c#)

u can also try from yours design

    <div <%=If(True = True, "style='display: none;'", "")%> >True</div>
<div <%=If(True = False, "style='display: none;'", "")%> >False</div>
<div <%=If(Session.Item("NameExist") IsNot Nothing, "style='display: none;'", "")%> >NameExist</div>
<div <%=If(Session.Item("NameNotExist") IsNot Nothing, "style='display: none;'", "")%> >NameNotExist</div>

Output html

    <div style='display: none;' > True</div>
<div  >False</div>
<div style='display: none;' >NameExist</div>
<div  >NameNotExist</div>

How can I do an UPDATE statement with JOIN in SQL Server?

Try this one, I think this will works for you

update ud

set ud.assid = sale.assid

from ud 

Inner join sale on ud.id = sale.udid

where sale.udid is not null

invalid types 'int[int]' for array subscript

You are subscripting a three-dimensional array myArray[10][10][10] four times myArray[i][t][x][y]. You will probably need to add another dimension to your array. Also consider a container like Boost.MultiArray, though that's probably over your head at this point.

Warnings Your Apk Is Using Permissions That Require A Privacy Policy: (android.permission.READ_PHONE_STATE)

The dependencies you have in your project, will add their own permissions. Please do the below to find from where "READ_PHONE_STATE" is coming.

  1. Rebuild your android application
  2. Press "Ctrl+Shift+F" in android studio (basically do a search all in the editor of your preference).
  3. Search for "READ_PHONE_STATE", you would find the entry in a regenerated manifest file (not the one you originally created). By the path of it you can know, from which dependency the permission is getting added. enter image description here

How do I create a new branch?

Branches in SVN are essentially directories; you don't name the branch so much as choose the name of the directory to branch into.

The common way of 'naming' a branch is to place it under a directory called branches in your repository. In the "To URL:" portion of TortoiseSVN's Branch dialog, you would therefore enter something like:

(svn/http)://path-to-repo/branches/your-branch-name

The main branch of a project is referred to as the trunk, and is usually located in:

(svn/http)://path-to-repo/trunk

Automatic prune with Git fetch or pull

Since git 1.8.5 (Q4 2013):

"git fetch" (hence "git pull" as well) learned to check "fetch.prune" and "remote.*.prune" configuration variables and to behave as if the "--prune" command line option was given.

That means that, if you set remote.origin.prune to true:

git config remote.origin.prune true

Any git fetch or git pull will automatically prune.

Note: Git 2.12 (Q1 2017) will fix a bug related to this configuration, which would make git remote rename misbehave.
See "How do I rename a git remote?".


See more at commit 737c5a9:

Without "git fetch --prune", remote-tracking branches for a branch the other side already has removed will stay forever.
Some people want to always run "git fetch --prune".

To accommodate users who want to either prune always or when fetching from a particular remote, add two new configuration variables "fetch.prune" and "remote.<name>.prune":

  • "fetch.prune" allows to enable prune for all fetch operations.
  • "remote.<name>.prune" allows to change the behaviour per remote.

The latter will naturally override the former, and the --[no-]prune option from the command line will override the configured default.

Since --prune is a potentially destructive operation (Git doesn't keep reflogs for deleted references yet), we don't want to prune without users consent, so this configuration will not be on by default.

Why am I seeing net::ERR_CLEARTEXT_NOT_PERMITTED errors after upgrading to Cordova Android 8?

Adding the following attribute within the opening < widget > tag worked for me. Simple and live reloads correctly on a Android 9 emulator. xmlns:android="http://schemas.android.com/apk/res/android"

<widget id="com.my.awesomeapp" version="1.0.0" 
xmlns="http://www.w3.org/ns/widgets"
xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:cdv="http://cordova.apache.org/ns/1.0">

How to read files from resources folder in Scala?

For Scala 2.11, if getLines doesn't do exactly what you want you can also copy the a file out of the jar to the local file system.

Here's a snippit that reads a binary google .p12 format API key from /resources, writes it to /tmp, and then uses the file path string as an input to a spark-google-spreadsheets write.

In the world of sbt-native-packager and sbt-assembly, copying to local is also useful with scalatest binary file tests. Just pop them out of resources to local, run the tests, and then delete.

import java.io.{File, FileOutputStream}
import java.nio.file.{Files, Paths}

def resourceToLocal(resourcePath: String) = {
  val outPath = "/tmp/" + resourcePath
  if (!Files.exists(Paths.get(outPath))) {
    val resourceFileStream = getClass.getResourceAsStream(s"/${resourcePath}")
    val fos = new FileOutputStream(outPath)
    fos.write(
      Stream.continually(resourceFileStream.read).takeWhile(-1 !=).map(_.toByte).toArray
    )
    fos.close()
  }
  outPath
}

val filePathFromResourcesDirectory = "google-docs-key.p12"
val serviceAccountId = "[something]@drive-integration-[something].iam.gserviceaccount.com"
val googleSheetId = "1nC8Y3a8cvtXhhrpZCNAsP4MBHRm5Uee4xX-rCW3CW_4"
val tabName = "Favorite Cities"

import spark.implicits
val df = Seq(("Brooklyn", "New York"), 
          ("New York City", "New York"), 
          ("San Francisco", "California")).
          toDF("City", "State")

df.write.
  format("com.github.potix2.spark.google.spreadsheets").
  option("serviceAccountId", serviceAccountId).
  option("credentialPath", resourceToLocal(filePathFromResourcesDirectory)).
  save(s"${googleSheetId}/${tabName}")

How to compare two java objects

1) == evaluates reference equality in this case
2) im not too sure about the equals, but why not simply overriding the compare method and plant it inside MyClass?

How do I check the difference, in seconds, between two dates?

Here's the one that is working for me.

from datetime import datetime

date_format = "%H:%M:%S"

# You could also pass datetime.time object in this part and convert it to string.
time_start = str('09:00:00') 
time_end = str('18:00:00')

# Then get the difference here.    
diff = datetime.strptime(time_end, date_format) - datetime.strptime(time_start, date_format)

# Get the time in hours i.e. 9.60, 8.5
result = diff.seconds / 3600;

Hope this helps!

Android Fatal signal 11 (SIGSEGV) at 0x636f7d89 (code=1). How can it be tracked down?

I had this segmentation fault error because of Memory issues. My struct having many variables and arrays, had this Array of size 1024.

Reducing the size to 512, the error was gone.

P.S: This is a workaround and not a solution. It is necessary to find the struct size and dynamic memory allocation is a better option.

Convert a list of objects to an array of one of the object's properties

This should also work:

AggregateValues("hello", MyList.ConvertAll(c => c.Name).ToArray())

How to make a GridLayout fit screen size

I archive this using LinearLayout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:height="166dp"
            android:text="Tile1"
            android:gravity="center"
            android:background="#6f19e5"/>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:text="Tile2"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:height="126dp"
            android:gravity="center"
            android:layout_weight=".50"
            android:background="#f1d600"/>

        <TextView
            android:text="Tile3"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:height="126dp"
            android:gravity="center"
            android:layout_weight=".50"
            android:background="#e75548"/>

    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:text="Tile4"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:height="126dp"
            android:gravity="center"
            android:layout_weight=".50"
            android:background="#29d217"/>

        <TextView
            android:text="Tile5"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:height="126dp"
            android:gravity="center"
            android:layout_weight=".50"
            android:background="#e519cb"/>

    </LinearLayout>
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:height="176dp"
            android:text="Tile6"
            android:gravity="center"
            android:background="#09eadd"/>
    </LinearLayout>
</LinearLayout>

Here the modal

Will iOS launch my app into the background if it was force-quit by the user?

You can change your target's launch settings in "Manage Scheme" to Wait for <app>.app to be launched manually, which allows you debug by setting a breakpoint in application: didReceiveRemoteNotification: fetchCompletionHandler: and sending the push notification to trigger the background launch.

I'm not sure it'll solve the issue, but it may assist you with debugging for now.

screenshot

MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]

After trying EVERY solution google came up with on stack overflow, I found what my particular problem was. I had edited my hosts file a long time ago to allow me to access my localhost from my virtualbox.

Removing this entry solved it for me, along with the correct installation of mongoDB from the link given in the above solution, and including the correct promise handling code:

mongoose.connect('mongodb://localhost/testdb').then(() => {
console.log("Connected to Database");
}).catch((err) => {
    console.log("Not Connected to Database ERROR! ", err);
});

DateTime format to SQL format using C#

try this below

DateTime myDateTime = DateTime.Now;
string sqlFormattedDate = myDateTime.ToString("yyyy-MM-dd HH:mm:ss.fff");

Creating a div element in jQuery

You can use append (to add at last position of parent) or prepend (to add at fist position of parent):

$('#parent').append('<div>hello</div>');    
// or
$('<div>hello</div>').appendTo('#parent');

Alternatively, you can use the .html() or .add() as mentioned in a different answer.

Enums in Javascript with ES6

Whilst using Symbol as the enum value works fine for simple use cases, it can be handy to give properties to enums. This can be done by using an Object as the enum value containing the properties.

For example we can give each of the Colors a name and hex value:

/**
 * Enum for common colors.
 * @readonly
 * @enum {{name: string, hex: string}}
 */
const Colors = Object.freeze({
  RED:   { name: "red", hex: "#f00" },
  BLUE:  { name: "blue", hex: "#00f" },
  GREEN: { name: "green", hex: "#0f0" }
});

Including properties in the enum avoids having to write switch statements (and possibly forgetting new cases to the switch statements when an enum is extended). The example also shows the enum properties and types documented with the JSDoc enum annotation.

Equality works as expected with Colors.RED === Colors.RED being true, and Colors.RED === Colors.BLUE being false.

Multiple try codes in one block

Lets say each code is a function and its already written then the following can be used to iter through your coding list and exit the for-loop when a function is executed without error using the "break".

def a(): code a
def b(): code b
def c(): code c
def d(): code d

for func in [a, b, c, d]:  # change list order to change execution order.
   try:
       func()
       break
   except Exception as err:
       print (err)
       continue

I used "Exception " here so you can see any error printed. Turn-off the print if you know what to expect and you're not caring (e.g. in case the code returns two or three list items (i,j = msg.split('.')).

ASP.NET MVC: Html.EditorFor and multi-line text boxes

in your view, instead of:

@Html.EditorFor(model => model.Comments[0].Comment)

just use:

@Html.TextAreaFor(model => model.Comments[0].Comment, 5, 1, null)

In Oracle, is it possible to INSERT or UPDATE a record through a view?

Oracle has two different ways of making views updatable:-

  1. The view is "key preserved" with respect to what you are trying to update. This means the primary key of the underlying table is in the view and the row appears only once in the view. This means Oracle can figure out exactly which underlying table row to update OR
  2. You write an instead of trigger.

I would stay away from instead-of triggers and get your code to update the underlying tables directly rather than through the view.

How to prove that a problem is NP complete?

In order to prove that a problem L is NP-complete, we need to do the following steps:

  1. Prove your problem L belongs to NP (that is that given a solution you can verify it in polynomial time)
  2. Select a known NP-complete problem L'
  3. Describe an algorithm f that transforms L' into L
  4. Prove that your algorithm is correct (formally: x ? L' if and only if f(x) ? L )
  5. Prove that algo f runs in polynomial time

What is the memory consumption of an object in Java?

Each object has a certain overhead for its associated monitor and type information, as well as the fields themselves. Beyond that, fields can be laid out pretty much however the JVM sees fit (I believe) - but as shown in another answer, at least some JVMs will pack fairly tightly. Consider a class like this:

public class SingleByte
{
    private byte b;
}

vs

public class OneHundredBytes
{
    private byte b00, b01, ..., b99;
}

On a 32-bit JVM, I'd expect 100 instances of SingleByte to take 1200 bytes (8 bytes of overhead + 4 bytes for the field due to padding/alignment). I'd expect one instance of OneHundredBytes to take 108 bytes - the overhead, and then 100 bytes, packed. It can certainly vary by JVM though - one implementation may decide not to pack the fields in OneHundredBytes, leading to it taking 408 bytes (= 8 bytes overhead + 4 * 100 aligned/padded bytes). On a 64 bit JVM the overhead may well be bigger too (not sure).

EDIT: See the comment below; apparently HotSpot pads to 8 byte boundaries instead of 32, so each instance of SingleByte would take 16 bytes.

Either way, the "single large object" will be at least as efficient as multiple small objects - for simple cases like this.

JQuery/Javascript: check if var exists

It is impossible to determine whether a variable has been declared or not other than using try..catch to cause an error if it hasn't been declared. Test like:

if (typeof varName == 'undefined') 

do not tell you if varName is a variable in scope, only that testing with typeof returned undefined. e.g.

var foo;
typeof foo == 'undefined'; // true
typeof bar == 'undefined'; // true

In the above, you can't tell that foo was declared but bar wasn't. You can test for global variables using in:

var global = this;
...
'bar' in global;  // false

But the global object is the only variable object* you can access, you can't access the variable object of any other execution context.

The solution is to always declare variables in an appropriate context.

  • The global object isn't really a variable object, it just has properties that match global variables and provide access to them so it just appears to be one.

How to import a CSS file in a React Component

Using extract-css-chunks-webpack-plugin and css-loader loader work for me, see below:

webpack.config.js Import extract-css-chunks-webpack-plugin

const ExtractCssChunks = require('extract-css-chunks-webpack-plugin');

webpack.config.js Add the css rule, Extract css Chunks first then the css loader css-loader will embed them into the html document, ensure css-loader and extract-css-chunks-webpack-plugin are in the package.json dev dependencies

rules: [
      {
        test: /\.css$/,
        use: [
          {
            loader: ExtractCssChunks.loader,
          },
          'css-loader',
        ],
      }
]

webpack.config.js Make instance of the plugin

plugins: [
    new ExtractCssChunks({
      // Options similar to the same options in webpackOptions.output
      // both options are optional
      filename: '[name].css',
      chunkFilename: '[id].css'
    })
  ]

And now importing css is possible And now in a tsx file like index.tsx i can use import like this import './Tree.css' where Tree.css contains css rules like

body {
    background: red;
}

My app is using typescript and this works for me, check my repo for the source : https://github.com/nickjohngray/staticbackeditor

How to set selected index JComboBox by value

http://docs.oracle.com/javase/6/docs/api/javax/swing/JComboBox.html#setSelectedItem(java.lang.Object)

test.setSelectedItem("banana");

There are some caveats or potentially unexpected behavior as explained in the javadoc. Make sure to read that.

What is the purpose of XSD files?

XSD files are used to validate that XML files conform to a certain format.

In that respect they are similar to DTDs that existed before them.

The main difference between XSD and DTD is that XSD is written in XML and is considered easier to read and understand.

NuGet: 'X' already has a dependency defined for 'Y'

I tried the update, but it did not work for me. Helped:

  1. Uninstall NuGet => Tools => Extensions and update => Installed
  2. Install NuGet
  3. Reload Visual Studio

Change the image source on rollover using jQuery

Whilst looking for a solution some time back, I found a similar script to the below, which after some tweaking I got working for me.

It handles two images, that almost always default to "off", where the mouse is off the image (image-example_off.jpg), and the occasional "on", where for the times the mouse is hovered, the required alternative image (image-example_on.jpg) is displayed.

<script type="text/javascript">        
    $(document).ready(function() {        
        $("img", this).hover(swapImageIn, swapImageOut);

        function swapImageIn(e) {
            this.src = this.src.replace("_off", "_on");
        }
        function swapImageOut (e) {
            this.src = this.src.replace("_on", "_off");
        }
    });
</script>

How to allow CORS in react.js?

It is better to add CORS enabling code on Server Side. To enable CORS in NodeJS and ExpressJs based application following code should be included-

var app = express();

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

Do copyright dates need to be updated?

There is no reason at all for an individual to update the copyright year, because in the U.S. and Europe the life of copyright is the life of the author plus 70 years (50 years in some other countries like Canada and Australia). Extending the date does not extend the copyright. This also applies when a page has multiple contributors none of which are corporations.

As for corporations, Google doesn't update their copyright dates because they don't care whether some page they started in 1999 and updated this year falls into the public domain in 2094 or 2109. And if they don't, why should you? (As a Googler, now an ex-Googler, I was told this was the policy for internal source code as well.)

Emulate Samsung Galaxy Tab

I found under website.

http://developer.samsung.com/android/tools-sdks/Samsung-GALAXY-Tab-Emulator

Extract zip file to add-ons under android sdk path. then launch Android SDK Manager. under "extras" folder check "Android + Google APIs for GALAXY Tab, API 8, revision 1" item and install package.

That's all.

<meta charset="utf-8"> vs <meta http-equiv="Content-Type">

Another reason to go with the short one is that it matches other instances where you might specify a character set in markup. For example:

<script type="javascript" charset="UTF-8" src="/script.js"></script>

<p><a charset="UTF-8" href="http://example.com/">Example Site</a></p>

Consistency helps to reduce errors and make code more readable.

Note that the charset attribute is case-insensitive. You can use UTF-8 or utf-8, however UTF-8 is clearer, more readable, more accurate.

Also, there is absolutely no reason at all to use any value other than UTF-8 in the meta charset attribute or page header. UTF-8 is the default encoding for Web documents since HTML4 in 1999 and the only practical way to make modern Web pages.

Also you should not use HTML entities in UTF-8. Characters like the copyright symbol should be typed directly. The only entities you should use are for the 5 reserved markup characters: less than, greater than, ampersand, prime, double prime. Entities need an HTML parser, which you may not always want to use going forward, they introduce errors, make your code less readable, increase your file sizes, and sometimes decode incorrectly in various browsers depending on which entities you used. Learn how to type/insert copyright, trademark, open quote, close quote, apostrophe, em dash, en dash, bullet, Euro, and any other characters you encounter in your content, and use those actual characters in your code. The Mac has a Character Viewer that you can turn on in the Keyboard System Preference, and you can find and then drag and drop the characters you need, or use the matching Keyboard Viewer to see which keys to type. For example, trademark is Option+2. UTF-8 contains all of the characters and symbols from every written human language. So there is no excuse for using -- instead of an em dash. It is not a bad idea to learn the rules of punctuation and typography also ... for example, knowing that a period goes inside a close quote, not outside.

Using a tag for something like content-type and encoding is highly ironic, since without knowing those things, you couldn't parse the file to get the value of the meta tag.

No, that is not true. The browser starts out parsing the file as the browser's default encoding, either UTF-8 or ISO-8859-1. Since US-ASCII is a subset of both ISO-8859-1 and UTF-8, the browser can read just fine either way ... it is the same. When the browser encounters the meta charset tag, if the encoding is different than what the browser is already using, the browser reloads the page in the specified encoding. That is why we put the meta charset tag at the top, right after the head tag, before anything else, even the title. That way you can use UTF-8 characters in your title.

You must save your file(s) in UTF-8 encoding without BOM

That is not strictly true. If you only have US-ASCII characters in your document, you can Save it as US-ASCII and serve it as UTF-8, because it is a subset. But if there are Unicode characters, you are correct, you must Save as UTF-8 without BOM.

If you want a good text editor that will save your files in UTF-8, I recommend Notepad++.

On the Mac, use Bare Bones TextWrangler (free) from Mac App Store, or Bare Bones BBEdit which is at Mac App Store for $39.99 ... very cheap for such a great tool. In either app, there is a menu at the bottom of the document window where you specify the document encoding and you can easily choose "UTF-8 no BOM". And of course you can set that as the default for new documents in Preferences.

But if your Webserver serves the encoding in the HTTP header, which is recommended, both [meta tags] are needless.

That is incorrect. You should of course set the encoding in the HTTP header, but you should also set it in the meta charset attribute so that the page can be Saved by the user, out of the browser onto local storage and then Opened again later, in which case the only indication of the encoding that will be present is the meta charset attribute. You should also set a base tag for the same reason ... on the server, the base tag is unnecessary, but when opened from local storage, the base tag enables the page to work as if it is on the server, with all the assets in place and so on, no broken links.

AddDefaultCharset UTF-8

Or you can just change the encoding of particular file types like so:

AddType text/html;charset=utf-8 html

A tip for serving both UTF-8 and Latin-1 (ISO-8859-1) files is to give the UTF-8 files a "text" extension and Latin-1 files "txt."

AddType text/plain;charset=iso-8859-1 txt
AddType text/plain;charset=utf-8 text

Finally, consider Saving your documents with Unix line endings, not legacy DOS or (classic) Mac line endings, which don't help and may hurt, especially down the line as we get further and further from those legacy systems. An HTML document with valid HTML5, UTF-8 encoding, and Unix line endings is a job well done. You can share and edit and store and read and recover and rely on that document in many contexts. It's lingua franca. It's digital paper.

how to avoid extra blank page at end while printing?

Add this css to same page to extend css file.

<style type="text/css">
   <!--
   html, body {
    height: 95%; 
    margin: 0 0 0 0;
     }
   -->
</style>

What's the difference between nohup and ampersand

The nohup command is a signal masking utility and catches the hangup signal. Where as ampersand doesn’t catch the hang up signals. The shell will terminate the sub command with the hang up signal when running a command using & and exiting the shell. This can be prevented by using nohup, as it catches the signal. Nohup command accept hang up signal which can be sent to a process by the kernel and block them. Nohup command is helpful in when a user wants to start long running application log out or close the window in which the process was initiated. Either of these actions normally prompts the kernel to hang up on the application, but a nohup wrapper will allow the process to continue. Using the ampersand will run the command in a child process and this child of the current bash session. When you exit the session, all of the child processes of that process will be killed. The ampersand relates to job control for the active shell. This is useful for running a process in a session in the background.

getElementById returns null?

There could be many reason why document.getElementById doesn't work

  • You have an invalid ID

    ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods ("."). (resource: What are valid values for the id attribute in HTML?)

  • you used some id that you already used as <meta> name in your header (e.g. copyright, author... ) it looks weird but happened to me: if your 're using IE take a look at (resource: http://www.phpied.com/getelementbyid-description-in-ie/)

  • you're targeting an element inside a frame or iframe. In this case if the iframe loads a page within the same domain of the parent you should target the contentdocument before looking for the element (resource: Calling a specific id inside a frame)

  • you're simply looking to an element when the node is not effectively loaded in the DOM, or maybe it's a simple misspelling

I doubt you used same ID twice or more: in that case document.getElementById should return at least the first element

Limit to 2 decimal places with a simple pipe

Simple solution

{{ orderTotal | number : '1.2-2'}}

//output like this

// public orderTotal = 220.45892221

//   {{ orderTotal | number : '1.2-2'}} 

// final Output
//  220.45

Two Radio Buttons ASP.NET C#

In order to make it work, you have to set property GroupName of both radio buttons to the same value:

<asp:RadioButton id="rbMetric" runat="server" GroupName="measurementSystem"></asp:RadioButton>
<asp:RadioButton id="rbUS" runat="server" GroupName="measurementSystem"></asp:RadioButton>

Personally, I prefer to use a RadioButtonList:

<asp:RadioButtonList ID="rblMeasurementSystem" runat="server">
    <asp:ListItem Text="Metric" Value="metric" />
    <asp:ListItem Text="US" Value="us" />
</asp:RadioButtonList>

Where do I find the Instagram media ID of a image

For a period I had to extract the Media ID myself quite frequently, so I wrote my own script (very likely it's based on some of the examples here). Together with other small scripts I used frequently, I started to upload them on www.findinstaid.com for my own quick access.

I added the option to enter a username to get the media ID of the 12 most recent posts, or to enter a URL to get the media ID of a specific post.

If it's convenient, everyone can use the link (I don't have any adds or any other monetary interests in the website - I only have a referral link on the 'Audit' tab to www.auditninja.io which I do also own, but also on this site, there are no adds or monetary interests - just hobby projects).

How do I decode a string with escaped unicode?

I don't have enough rep to put this under comments to the existing answers:

unescape is only deprecated for working with URIs (or any encoded utf-8) which is probably the case for most people's needs. encodeURIComponent converts a js string to escaped UTF-8 and decodeURIComponent only works on escaped UTF-8 bytes. It throws an error for something like decodeURIComponent('%a9'); // error because extended ascii isn't valid utf-8 (even though that's still a unicode value), whereas unescape('%a9'); // © So you need to know your data when using decodeURIComponent.

decodeURIComponent won't work on "%C2" or any lone byte over 0x7f because in utf-8 that indicates part of a surrogate. However decodeURIComponent("%C2%A9") //gives you © Unescape wouldn't work properly on that // © AND it wouldn't throw an error, so unescape can lead to buggy code if you don't know your data.

How to execute a .bat file from a C# windows form app?

For the problem you're having about the batch file asking the user if the destination is a folder or file, if you know the answer in advance, you can do as such:

If destination is a file: echo f | [batch file path]

If folder: echo d | [batch file path]

It will essentially just pipe the letter after "echo" to the input of the batch file.

How do I exit from a function?

return; // Prematurely return from the method (same keword works in VB, by the way)

How to detect Adblock on my website?

I know this is already answered, but I looked at the suggested sample site, and I see they do it like this:

<script type="text/javascript">
if(document.getElementsByTagName("iframe").item(0) == null) {
    document.write("<div style="width: 160px; height: 600px; padding-top: 280px; margin-left: 5px; border: 1px solid #666666; color: #FFF; background-color: #666; text-align:center; font-family: Maven Pro, century gothic, arial, helvetica, sans-serif; padding-left: 5px; padding-right: 5px; border-radius: 7px; font-size: 18px;">Advertising seems to be blocked by your browser.<br><br><span style="font-size: 12px;">Please notice that advertising helps us to host the project.<br><br>If you find these ads intrusive or inappropriate, please contact me.</span><br><img src="http://www.playonlinux.com/images/abp.png" alt="Adblock Plus"></div>");
};
</script>

"Least Astonishment" and the Mutable Default Argument

Why don't you introspect?

I'm really surprised no one has performed the insightful introspection offered by Python (2 and 3 apply) on callables.

Given a simple little function func defined as:

>>> def func(a = []):
...    a.append(5)

When Python encounters it, the first thing it will do is compile it in order to create a code object for this function. While this compilation step is done, Python evaluates* and then stores the default arguments (an empty list [] here) in the function object itself. As the top answer mentioned: the list a can now be considered a member of the function func.

So, let's do some introspection, a before and after to examine how the list gets expanded inside the function object. I'm using Python 3.x for this, for Python 2 the same applies (use __defaults__ or func_defaults in Python 2; yes, two names for the same thing).

Function Before Execution:

>>> def func(a = []):
...     a.append(5)
...     

After Python executes this definition it will take any default parameters specified (a = [] here) and cram them in the __defaults__ attribute for the function object (relevant section: Callables):

>>> func.__defaults__
([],)

O.k, so an empty list as the single entry in __defaults__, just as expected.

Function After Execution:

Let's now execute this function:

>>> func()

Now, let's see those __defaults__ again:

>>> func.__defaults__
([5],)

Astonished? The value inside the object changes! Consecutive calls to the function will now simply append to that embedded list object:

>>> func(); func(); func()
>>> func.__defaults__
([5, 5, 5, 5],)

So, there you have it, the reason why this 'flaw' happens, is because default arguments are part of the function object. There's nothing weird going on here, it's all just a bit surprising.

The common solution to combat this is to use None as the default and then initialize in the function body:

def func(a = None):
    # or: a = [] if a is None else a
    if a is None:
        a = []

Since the function body is executed anew each time, you always get a fresh new empty list if no argument was passed for a.


To further verify that the list in __defaults__ is the same as that used in the function func you can just change your function to return the id of the list a used inside the function body. Then, compare it to the list in __defaults__ (position [0] in __defaults__) and you'll see how these are indeed refering to the same list instance:

>>> def func(a = []): 
...     a.append(5)
...     return id(a)
>>>
>>> id(func.__defaults__[0]) == func()
True

All with the power of introspection!


* To verify that Python evaluates the default arguments during compilation of the function, try executing the following:

def bar(a=input('Did you just see me without calling the function?')): 
    pass  # use raw_input in Py2

as you'll notice, input() is called before the process of building the function and binding it to the name bar is made.

Passing parameters to a JQuery function

Do you want to pass parameters to another page or to the function only?

If only the function, you don't need to add the $.ajax() tvanfosson added. Just add your function content instead. Like:

function DoAction (id, name ) {
    // ...
    // do anything you want here
    alert ("id: "+id+" - name: "+name);
    //...
}

This will return an alert box with the id and name values.

How to color the Git console?

Add to your .gitconfig file next code:

[color]
    ui = auto
[color "branch"]
    current = yellow reverse
    local = yellow
    remote = green
[color "diff"]
    meta = yellow bold
    frag = magenta bold
    old = red bold
    new = green bold
[color "status"]
    added = yellow
    changed = green
    untracked = cyan

Foreach loop in java for a custom object list

You can fix your example with the iterator pattern by changing the parametrization of the class:

List<Room> rooms = new ArrayList<Room>();
rooms.add(room1);
rooms.add(room2);
for(Iterator<Room> i = rooms.iterator(); i.hasNext(); ) {
  String item = i.next();
  System.out.println(item);
}

or much simpler way:

List<Room> rooms = new ArrayList<Room>();
rooms.add(room1);
rooms.add(room2);
for(Room room : rooms) {
  System.out.println(room);
}

Do you recommend using semicolons after every statement in JavaScript?

Yes, you should always use semicolons. Why? Because if you end up using a JavaScript compressor, all your code will be on one line, which will break your code.

Try http://www.jslint.com/; it will hurt your feelings, but show you many ways to write better JavaScript (and one of the ways is to always use semicolons).

Python 'list indices must be integers, not tuple"

To create list of lists, you need to separate them with commas, like this

coin_args = [
    ["pennies", '2.5', '50.0', '.01'],
    ["nickles", '5.0', '40.0', '.05'],
    ["dimes", '2.268', '50.0', '.1'],
    ["quarters", '5.67', '40.0', '.25']
]

What are the most-used vim commands/keypresses?

Put this in your .bashrc to open vim with last edited file at last edited line

alias vil="vim  +\"'\"0"

Add new field to every document in a MongoDB collection

Same as the updating existing collection field, $set will add a new fields if the specified field does not exist.

Check out this example:

> db.foo.find()
> db.foo.insert({"test":"a"})
> db.foo.find()
{ "_id" : ObjectId("4e93037bbf6f1dd3a0a9541a"), "test" : "a" }
> item = db.foo.findOne()
{ "_id" : ObjectId("4e93037bbf6f1dd3a0a9541a"), "test" : "a" }
> db.foo.update({"_id" :ObjectId("4e93037bbf6f1dd3a0a9541a") },{$set : {"new_field":1}})
> db.foo.find()
{ "_id" : ObjectId("4e93037bbf6f1dd3a0a9541a"), "new_field" : 1, "test" : "a" }

EDIT:

In case you want to add a new_field to all your collection, you have to use empty selector, and set multi flag to true (last param) to update all the documents

db.your_collection.update(
  {},
  { $set: {"new_field": 1} },
  false,
  true
)

EDIT:

In the above example last 2 fields false, true specifies the upsert and multi flags.

Upsert: If set to true, creates a new document when no document matches the query criteria.

Multi: If set to true, updates multiple documents that meet the query criteria. If set to false, updates one document.

This is for Mongo versions prior to 2.2. For latest versions the query is changed a bit

db.your_collection.update({},
                          {$set : {"new_field":1}},
                          {upsert:false,
                          multi:true}) 

Python: printing a file to stdout

f = open('file.txt', 'r')
print f.read()
f.close()

From http://docs.python.org/tutorial/inputoutput.html

To read a file’s contents, call f.read(size), which reads some quantity of data and returns it as a string. size is an optional numeric argument. When size is omitted or negative, the entire contents of the file will be read and returned; it’s your problem if the file is twice as large as your machine’s memory. Otherwise, at most size bytes are read and returned. If the end of the file has been reached, f.read() will return an empty string ("").

how to set JAVA_OPTS for Tomcat in Windows?

Apparently the correct form is without the ""

As in

set JAVA_OPTS=-Xms512M -Xmx1024M

jQuery - If element has class do this

First, you're missing some parentheses in your conditional:

if ($("#about").hasClass("opened")) {
  $("#about").animate({right: "-700px"}, 2000);
}

But you can also simplify this to:

$('#about.opened').animate(...);

If #about doesn't have the opened class, it won't animate.

If the problem is with the animation itself, we'd need to know more about your element positioning (absolute? absolute inside relative parent? does the parent have layout?)

Adding multiple class using ng-class

For the ternary operator notation:

<div ng-class="expression1? 'class1 class2' : 'class3 class4'">

Finish all previous activities

If you are using startActivityForResult() in your previous activities, just override OnActivityResult() and call the finish(); method inside it in all activities.. This will do the job...

Is it possible to use Java 8 for Android development?

Yes, Android Supports Java 8 Now (24.1.17)

Now it is possible

But you will need to have your device rom run on java 1.8 and enable "jackOptions" to run it. Jack is the name for the new Android compiler that runs Java 8

https://developer.android.com/guide/platform/j8-jack.html

add these lines to build_gradle

    android {
  ...
  defaultConfig {
    ...
    jackOptions {
      enabled true
    }
  }
  compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }
}

Java 8 seem to be the running java engine of Android studio 2.0, But it still does not accept the syntax of java 8 after I checked, and you cannot chose a compiler from android studio now. However, you can use the scala plugin if you need functional programming mechanism in your android client.

enter image description here

Retrieving Android API version programmatically

As described in the Android documentation, the SDK level (integer) the phone is running is available in:

android.os.Build.VERSION.SDK_INT

The class corresponding to this int is in the android.os.Build.VERSION_CODES class.

Code example:

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP){
    // Do something for lollipop and above versions
} else{
    // do something for phones running an SDK before lollipop
}

Edit: This SDK_INT is available since Donut (android 1.6 / API4) so make sure your application is not retro-compatible with Cupcake (android 1.5 / API3) when you use it or your application will crash (thanks to Programmer Bruce for the precision).

Corresponding android documentation is here and here

Getting all file names from a folder using C#

DirectoryInfo d = new DirectoryInfo(@"D:\Test");//Assuming Test is your Folder
FileInfo[] Files = d.GetFiles("*.txt"); //Getting Text files
string str = "";
foreach(FileInfo file in Files )
{
  str = str + ", " + file.Name;
}

Hope this will help...

onclick on a image to navigate to another page using Javascript

I'd set up your HTML like so:

<img src="../images/bottle.jpg" alt="bottle" class="thumbnails" id="bottle" />

Then use the following code:

<script>
var images = document.getElementsByTagName("img");
for(var i = 0; i < images.length; i++) {
    var image = images[i];
    image.onclick = function(event) {
         window.location.href = this.id + '.html';
    };
}
</script>

That assigns an onclick event handler to every image on the page (this may not be what you want, you can limit it further if necessary) that changes the current page to the value of the images id attribute plus the .html extension. It's essentially the pure Javascript implementation of @JanPöschko's jQuery answer.

Unique constraint on multiple columns

By using the constraint definition on table creation, you can specify one or multiple constraints that span multiple columns. The syntax, simplified from technet's documentation, is in the form of:

CONSTRAINT constraint_name UNIQUE [ CLUSTERED | NONCLUSTERED ] 
(
    column [ ASC | DESC ] [ ,...n ]
)

Therefore, the resuting table definition would be:

CREATE TABLE [dbo].[user](
    [userID] [int] IDENTITY(1,1) NOT NULL,
    [fcode] [int] NULL,
    [scode] [int] NULL,
    [dcode] [int] NULL,
    [name] [nvarchar](50) NULL,
    [address] [nvarchar](50) NULL,
    CONSTRAINT [PK_user_1] PRIMARY KEY CLUSTERED 
    (
        [userID] ASC
    ),
    CONSTRAINT [UQ_codes] UNIQUE NONCLUSTERED
    (
        [fcode], [scode], [dcode]
    )
) ON [PRIMARY]

Strip HTML from Text JavaScript

A safer way to strip the html with jQuery is to first use jQuery.parseHTML to create a DOM, ignoring any scripts, before letting jQuery build an element and then retrieving only the text.

function stripHtml(unsafe) {
    return $($.parseHTML(unsafe)).text();
}

Can safely strip html from:

<img src="unknown.gif" onerror="console.log('running injections');">

And other exploits.

nJoy!

C++ variable has initializer but incomplete type?

I got a similar error and hit this page while searching the solution.

With Qt this error can happen if you forget to add the QT_WRAP_CPP( ... ) step in your build to run meta object compiler (moc). Including the Qt header is not sufficient.

Execute bash script from URL

Just combining amra and user77115's answers:

wget -qO- https://raw.githubusercontent.com/lingtalfi/TheScientist/master/_bb_autoload/bbstart.sh | bash -s -- -v -v

It executes the bbstart.sh distant script passing it the -v -v options.

Getting the source of a specific image element with jQuery

var src = $('img.conversation_img[alt="example"]').attr('src');

If you have multiple matching elements only the src of the first one will be returned.

Reload activity in Android

i used this and it works fine without finish()

startActivity(getIntent());

Passing on command line arguments to runnable JAR

Why not ?

Just modify your Main-Class to receive arguments and act upon the argument.

public class wiki2txt {

    public static void main(String[] args) {

          String fileName = args[0];

          // Use FileInputStream, BufferedReader etc here.

    }
}

Specify the full path in the commandline.

java -jar wiki2txt /home/bla/enwiki-....xml

Show a number to two decimal places

You can use number_format():

return number_format((float)$number, 2, '.', '');

Example:

$foo = "105";
echo number_format((float)$foo, 2, '.', '');  // Outputs -> 105.00

This function returns a string.

Git fast forward VS no fast forward merge

When we work on development environment and merge our code to staging/production branch then Git no fast forward can be a better option. Usually when we work in development branch for a single feature we tend to have multiple commits. Tracking changes with multiple commits can be inconvenient later on. If we merge with staging/production branch using Git no fast forward then it will have only 1 commit. Now anytime we want to revert the feature, just revert that commit. Life is easy.

Oracle sqlldr TRAILING NULLCOLS required, but why?

Last column in your input file must have some data in it (be it space or char, but not null). I guess, 1st record contains null after last ',' which sqlldr won't recognize unless specifically asked to recognize nulls using TRAILING NULLCOLS option. Alternatively, if you don't want to use TRAILING NULLCOLS, you will have to take care of those NULLs before you pass the file to sqlldr. Hope this helps

Why an interface can not implement another interface?

implements means a behaviour will be defined for abstract methods (except for abstract classes obviously), you define the implementation.

extends means that a behaviour is inherited.

With interfaces it is possible to say that one interface should have that the same behaviour as another, there is not even an actual implementation. That's why it makes more sense for an interface to extends another interface instead of implementing it.


On a side note, remember that even if an abstract class can define abstract methods (the sane way an interface does), it is still a class and still has to be inherited (extended) and not implemented.

Difference between & and && in Java?

& is bitwise. && is logical.

& evaluates both sides of the operation.
&& evaluates the left side of the operation, if it's true, it continues and evaluates the right side.

Versioning SQL Server database

It's a very old question, however, many people are trying to solve this even now. All they have to do is to research about Visual Studio Database Projects. Without this, any database development looks very feeble. From code organization to deployment to versioning, it simplifies everything.

Can I get JSON to load into an OrderedDict?

Simple version for Python 2.7+

my_ordered_dict = json.loads(json_str, object_pairs_hook=collections.OrderedDict)

Or for Python 2.4 to 2.6

import simplejson as json
import ordereddict

my_ordered_dict = json.loads(json_str, object_pairs_hook=ordereddict.OrderedDict)

Is it possible to specify proxy credentials in your web.config?

Yes, it is possible to specify your own credentials without modifying the current code. It requires a small piece of code from your part though.

Create an assembly called SomeAssembly.dll with this class :

namespace SomeNameSpace
{
    public class MyProxy : IWebProxy
    {
        public ICredentials Credentials
        {
            get { return new NetworkCredential("user", "password"); }
            //or get { return new NetworkCredential("user", "password","domain"); }
            set { }
        }

        public Uri GetProxy(Uri destination)
        {
            return new Uri("http://my.proxy:8080");
        }

        public bool IsBypassed(Uri host)
        {
            return false;
        }
    }
}

Add this to your config file :

<defaultProxy enabled="true" useDefaultCredentials="false">
  <module type = "SomeNameSpace.MyProxy, SomeAssembly" />
</defaultProxy>

This "injects" a new proxy in the list, and because there are no default credentials, the WebRequest class will call your code first and request your own credentials. You will need to place the assemble SomeAssembly in the bin directory of your CMS application.

This is a somehow static code, and to get all strings like the user, password and URL, you might either need to implement your own ConfigurationSection, or add some information in the AppSettings, which is far more easier.

How can I count the occurrences of a list item?

If you can use pandas, then value_counts is there for rescue.

>>> import pandas as pd
>>> a = [1, 2, 3, 4, 1, 4, 1]
>>> pd.Series(a).value_counts()
1    3
4    2
3    1
2    1
dtype: int64

It automatically sorts the result based on frequency as well.

If you want the result to be in a list of list, do as below

>>> pd.Series(a).value_counts().reset_index().values.tolist()
[[1, 3], [4, 2], [3, 1], [2, 1]]

XML Serialize generic list of serializable objects

I have an solution for a generic List<> with dynamic binded items.

class PersonalList it's the root element

[XmlRoot("PersonenListe")]
[XmlInclude(typeof(Person))] // include type class Person
public class PersonalList
{
    [XmlArray("PersonenArray")]
    [XmlArrayItem("PersonObjekt")]
    public List<Person> Persons = new List<Person>();

    [XmlElement("Listname")]
    public string Listname { get; set; }

    // Konstruktoren 
    public PersonalList() { }

    public PersonalList(string name)
    {
        this.Listname = name;
    }

    public void AddPerson(Person person)
    {
        Persons.Add(person);
    }
}

class Person it's an single list element

[XmlType("Person")] // define Type
[XmlInclude(typeof(SpecialPerson)), XmlInclude(typeof(SuperPerson))]  
        // include type class SpecialPerson and class SuperPerson
public class Person
{
    [XmlAttribute("PersID", DataType = "string")]
    public string ID { get; set; }

    [XmlElement("Name")]
    public string Name { get; set; }

    [XmlElement("City")]
    public string City { get; set; }

    [XmlElement("Age")]
    public int Age { get; set; }

    // Konstruktoren 
    public Person() { }

    public Person(string name, string city, int age, string id)
    {
        this.Name = name;
        this.City = city;
        this.Age = age;
        this.ID = id;
    }
}

class SpecialPerson inherits Person

[XmlType("SpecialPerson")] // define Type
public class SpecialPerson : Person
{
    [XmlElement("SpecialInterests")]
    public string Interests { get; set; }

    public SpecialPerson() { }

    public SpecialPerson(string name, string city, int age, string id, string interests)
    {
        this.Name = name;
        this.City = city;
        this.Age = age;
        this.ID = id;
        this.Interests = interests;
    }
}

class SuperPerson inherits Person

[XmlType("SuperPerson")] // define Type
public class SuperPerson : Person
{
    [XmlArray("Skills")]
    [XmlArrayItem("Skill")]
    public List<String> Skills { get; set; }

    [XmlElement("Alias")]
    public string Alias { get; set; }

    public SuperPerson() 
    {
        Skills = new List<String>();
    }

    public SuperPerson(string name, string city, int age, string id, string[] skills, string alias)
    {
        Skills = new List<String>();

        this.Name = name;
        this.City = city;
        this.Age = age;
        this.ID = id;
        foreach (string item in skills)
        {
            this.Skills.Add(item);   
        }
        this.Alias = alias;
    }
}

and the main test Source

static void Main(string[] args)
{
    PersonalList personen = new PersonalList(); 
    personen.Listname = "Friends";

    // normal person
    Person normPerson = new Person();
    normPerson.ID = "0";
    normPerson.Name = "Max Man";
    normPerson.City = "Capitol City";
    normPerson.Age = 33;

    // special person
    SpecialPerson specPerson = new SpecialPerson();
    specPerson.ID = "1";
    specPerson.Name = "Albert Einstein";
    specPerson.City = "Ulm";
    specPerson.Age = 36;
    specPerson.Interests = "Physics";

    // super person
    SuperPerson supPerson = new SuperPerson();
    supPerson.ID = "2";
    supPerson.Name = "Superman";
    supPerson.Alias = "Clark Kent";
    supPerson.City = "Metropolis";
    supPerson.Age = int.MaxValue;
    supPerson.Skills.Add("fly");
    supPerson.Skills.Add("strong");

    // Add Persons
    personen.AddPerson(normPerson);
    personen.AddPerson(specPerson);
    personen.AddPerson(supPerson);

    // Serialize 
    Type[] personTypes = { typeof(Person), typeof(SpecialPerson), typeof(SuperPerson) };
    XmlSerializer serializer = new XmlSerializer(typeof(PersonalList), personTypes); 
    FileStream fs = new FileStream("Personenliste.xml", FileMode.Create); 
    serializer.Serialize(fs, personen); 
    fs.Close(); 
    personen = null;

    // Deserialize 
    fs = new FileStream("Personenliste.xml", FileMode.Open); 
    personen = (PersonalList)serializer.Deserialize(fs); 
    serializer.Serialize(Console.Out, personen);
    Console.ReadLine();
}

Important is the definition and includes of the diffrent types.

What are functional interfaces used for in Java 8?

As others have said, a functional interface is an interface which exposes one method. It may have more than one method, but all of the others must have a default implementation. The reason it's called a "functional interface" is because it effectively acts as a function. Since you can pass interfaces as parameters, it means that functions are now "first-class citizens" like in functional programming languages. This has many benefits, and you'll see them quite a lot when using the Stream API. Of course, lambda expressions are the main obvious use for them.

Cannot use object of type stdClass as array?

As the Php Manual say,

print_r — Prints human-readable information about a variable

When we use json_decode();, we get an object of type stdClass as return type. The arguments, which are to be passed inside of print_r() should either be an array or a string. Hence, we cannot pass an object inside of print_r(). I found 2 ways to deal with this.

  1. Cast the object to array.
    This can be achieved as follows.

    $a = (array)$object;
    
  2. By accessing the key of the Object
    As mentioned earlier, when you use json_decode(); function, it returns an Object of stdClass. you can access the elements of the object with the help of -> Operator.

    $value = $object->key;
    

One, can also use multiple keys to extract the sub elements incase if the object has nested arrays.

$value = $object->key1->key2->key3...;

Their are other options to print_r() as well, like var_dump(); and var_export();

P.S : Also, If you set the second parameter of the json_decode(); to true, it will automatically convert the object to an array();
Here are some references:
http://php.net/manual/en/function.print-r.php
http://php.net/manual/en/function.var-dump.php
http://php.net/manual/en/function.var-export.php

T-SQL STOP or ABORT command in SQL Server

No, there isn't one - you have a couple of options:

  1. Wrap the whole script in a big if/end block that is simply ensured to not be true (i.e. "if 1=2 begin" - this will only work however if the script doesn't include any GO statements (as those indicate a new batch)

  2. Use the return statement at the top (again, limited by the batch separators)

  3. Use a connection based approach, which will ensure non-execution for the entire script (entire connection to be more accurate) - use something like a 'SET PARSEONLY ON' or 'SET NOEXEC ON' at the top of the script. This will ensure all statements in the connection (or until said set statement is turned off) will not execute and will instead be parsed/compiled only.

  4. Use a comment block to comment out the entire script (i.e. /* and */)

EDIT: Demonstration that the 'return' statement is batch specific - note that you will continue to see result-sets after the returns:

select 1
return
go
select 2
return
select 3
go
select 4
return
select 5
select 6
go

How to change the CHARACTER SET (and COLLATION) throughout a database?

Beware that in Mysql, the utf8 character set is only a subset of the real UTF8 character set. In order to save one byte of storage, the Mysql team decided to store only three bytes of a UTF8 characters instead of the full four-bytes. That means that some east asian language and emoji aren't fully supported. To make sure you can store all UTF8 characters, use the utf8mb4 data type, and utf8mb4_bin or utf8mb4_general_ci in Mysql.

How to skip to next iteration in jQuery.each() util?

Javascript sort of has the idea of 'truthiness' and 'falsiness'. If a variable has a value then, generally 9as you will see) it has 'truthiness' - null, or no value tends to 'falsiness'. The snippets below might help:

var temp1; 
if ( temp1 )...  // false

var temp2 = true;
if ( temp2 )...  // true

var temp3 = "";
if ( temp3 ).... // false

var temp4 = "hello world";
if ( temp4 )...  // true

Hopefully that helps?

Also, its worth checking out these videos from Douglas Crockford

update: thanks @cphpython for spotting the broken links - I've updated to point at working versions now

The Javascript language

Javascript - The Good Parts

Correct use for angular-translate in controllers

Actually, you should use the translate directive for such stuff instead.

<h1 translate="{{pageTitle}}"></h1>

The directive takes care of asynchronous execution and is also clever enough to unwatch translation ids on the scope if the translation has no dynamic values.

However, if there's no way around and you really have to use $translate service in the controller, you should wrap the call in a $translateChangeSuccess event using $rootScope in combination with $translate.instant() like this:

.controller('foo', function ($rootScope, $scope, $translate) {
  $rootScope.$on('$translateChangeSuccess', function () {
    $scope.pageTitle = $translate.instant('PAGE.TITLE');
  });
})

So why $rootScope and not $scope? The reason for that is, that in angular-translate's events are $emited on $rootScope rather than $broadcasted on $scope because we don't need to broadcast through the entire scope hierarchy.

Why $translate.instant() and not just async $translate()? When $translateChangeSuccess event is fired, it is sure that the needed translation data is there and no asynchronous execution is happening (for example asynchronous loader execution), therefore we can just use $translate.instant() which is synchronous and just assumes that translations are available.

Since version 2.8.0 there is also $translate.onReady(), which returns a promise that is resolved as soon as translations are ready. See the changelog.

Multiple types were found that match the controller named 'Home'

I have found this error can occur with traditional ASP.NET website when you create the Controller in non App_Code directory (sometimes Visual Studio prevents this).

It sets the file type to "Compile" whereas any code added to "App_Code" is set to "Content". If you copy or move the file into App_Code then it is still set as "Compile".

I suspect it has something to with Website Project operation as website projects do not have any build operation.Clearing the bin folder and changing to "Content" seems to fix it.

Iterate over a Javascript associative array in sorted order

You cannot iterate over them directly, but you can find all the keys and then just sort them.

var a = new Array();
a['b'] = 1;
a['z'] = 1;
a['a'] = 1;    

function keys(obj)
{
    var keys = [];

    for(var key in obj)
    {
        if(obj.hasOwnProperty(key))
        {
            keys.push(key);
        }
    }

    return keys;
}

keys(a).sort(); // ["a", "b", "z"]

However there is no need to make the variable 'a' an array. You are really just using it as an object and should create it like this:

var a = {};
a["key"] = "value";

How to add text inside the doughnut chart using Chart.js?

This is also working at my end...

<div style="width: 100px; height: 100px; float: left; position: relative;">
    <div
        style="width: 100%; height: 40px; position: absolute; top: 50%; left: 0; margin-top: -20px; line-height:19px; text-align: center; z-index: 999999999999999">
        99%<Br />
        Total
    </div>
    <canvas id="chart-area" width="100" height="100" />
</div>

enter image description here

How do I get java logging output to appear on a single line?

Eclipse config

Per screenshot, in Eclipse select "run as" then "Run Configurations..." and add the answer from Trevor Robinson with double quotes instead of quotes. If you miss the double quotes you'll get "could not find or load main class" errors.

How do I get the Session Object in Spring?

i made my own utils. it is handy. :)

package samples.utils;

import java.util.Arrays;
import java.util.Collection;
import java.util.Locale;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.MessageSource;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.ui.context.Theme;
import org.springframework.util.ClassUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.ThemeResolver;
import org.springframework.web.servlet.support.RequestContextUtils;


/**
 * SpringMVC????
 * 
 * @author ??([email protected])
 *
 */
public final class WebContextHolder {

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

    private static WebContextHolder INSTANCE = new WebContextHolder();

    public WebContextHolder get() {
        return INSTANCE;
    }

    private WebContextHolder() {
        super();
    }

    // --------------------------------------------------------------------------------------------------------------

    public HttpServletRequest getRequest() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        return attributes.getRequest();
    }

    public HttpSession getSession() {
        return getSession(true);
    }

    public HttpSession getSession(boolean create) {
        return getRequest().getSession(create);
    }

    public String getSessionId() {
        return getSession().getId();
    }

    public ServletContext getServletContext() {
        return getSession().getServletContext();    // servlet2.3
    }

    public Locale getLocale() {
        return RequestContextUtils.getLocale(getRequest());
    }

    public Theme getTheme() {
        return RequestContextUtils.getTheme(getRequest());
    }

    public ApplicationContext getApplicationContext() {
        return WebApplicationContextUtils.getWebApplicationContext(getServletContext());
    }

    public ApplicationEventPublisher getApplicationEventPublisher() {
        return (ApplicationEventPublisher) getApplicationContext();
    }

    public LocaleResolver getLocaleResolver() {
        return RequestContextUtils.getLocaleResolver(getRequest());
    }

    public ThemeResolver getThemeResolver() {
        return RequestContextUtils.getThemeResolver(getRequest());
    }

    public ResourceLoader getResourceLoader() {
        return (ResourceLoader) getApplicationContext();
    }

    public ResourcePatternResolver getResourcePatternResolver() {
        return (ResourcePatternResolver) getApplicationContext();
    }

    public MessageSource getMessageSource() {
        return (MessageSource) getApplicationContext();
    }

    public ConversionService getConversionService() {
        return getBeanFromApplicationContext(ConversionService.class);
    }

    public DataSource getDataSource() {
        return getBeanFromApplicationContext(DataSource.class);
    }

    public Collection<String> getActiveProfiles() {
        return Arrays.asList(getApplicationContext().getEnvironment().getActiveProfiles());
    }

    public ClassLoader getBeanClassLoader() {
        return ClassUtils.getDefaultClassLoader();
    }

    private <T> T getBeanFromApplicationContext(Class<T> requiredType) {
        try {
            return getApplicationContext().getBean(requiredType);
        } catch (NoUniqueBeanDefinitionException e) {
            LOGGER.error(e.getMessage(), e);
            throw e;
        } catch (NoSuchBeanDefinitionException e) {
            LOGGER.warn(e.getMessage());
            return null;
        }
    }

}

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

Here's a sample program that reads stdin into a memory buffer that grows as needed. It's simple enough that it should give some insight in how you might handle this kind of thing. One thing that's would probably be done differently in a real program is how must the array grows in each allocation - I kept it small here to help keep things simpler if you wanted to step through in a debugger. A real program would probably use a much larger allocation increment (often, the allocation size is doubled, but if you're going to do that you should probably 'cap' the increment at some reasonable size - it might not make sense to double the allocation when you get into the hundreds of megabytes).

Also, I used indexed access to the buffer here as an example, but in a real program I probably wouldn't do that.

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


void fatal_error(void);

int main( int argc, char** argv)
{
    int buf_size = 0;
    int buf_used = 0;

    char* buf = NULL;
    char* tmp = NULL;    

    char c;
    int i = 0;

    while ((c = getchar()) != EOF) {
        if (buf_used == buf_size) {
             //need more space in the array

             buf_size += 20;
             tmp = realloc(buf, buf_size); // get a new larger array
             if (!tmp) fatal_error();

             buf = tmp;
        }

        buf[buf_used] = c; // pointer can be indexed like an array
        ++buf_used;
    }

    puts("\n\n*** Dump of stdin ***\n");

    for (i = 0; i < buf_used; ++i) {
        putchar(buf[i]);
    }

    free(buf);

    return 0;
}

void fatal_error(void)
{
    fputs("fatal error - out of memory\n", stderr);
    exit(1);
}

This example combined with examples in other answers should give you an idea of how this kind of thing is handled at a low level.

How do I make Git use the editor of my choice for commits?

This provides an answer for people who arrive at this Question that may want to link an editor other than vim.

The linked resource, by Github,is likely to be kept up to date, when editors are updated, even if answers on SO (including this one) are not.

Associating Text Editors with git

Github's post shows exactly what to type in to your command line for various editors, including the options/flags specific to each editor for it to work best with git.

Notepad++:
git config --global core.editor "'C:/Program Files (x86)/Notepad++/notepad++.exe' -multiInst -notabbar -nosession -noPlugin"

Sublime Text:
git config --global core.editor "'c:/Program Files/sublime text 3/subl.exe' -w"

Atom:
git config --global core.editor "atom --wait"

The commands above assume your editor has been installed in the default directory for a windows machine.

The commands basically add the text between double-quotes to .gitconfig in your home directory.
On a windows machine home is likely to be C:\Users\your-user-name, where your-user-name is your login name.
From the command line, you can reach this directory by typing in cd ~.

for example, a command above would be add the following line under the [core] section like so:
[core] editor = 'C:/Program Files/sublime text 3/subl.exe' -w

If you have a different editor, just replace with the path to your editor, using either method above. (and hope no flags are needed for optimal usage.)

How to allow only numbers in textbox in mvc4 razor

Here is the javascript that will allows you to enter only numbers.

Subscribe to onkeypress event for textbox.

@Html.TextBoxFor(m=>m.Phone,new { @onkeypress="OnlyNumeric(this);"})

Here is the javascript for it:

<script type="text/javascript">
function OnlyNumeric(e) {
            if ((e.which < 48 || e.which > 57)) {
                if (e.which == 8 || e.which == 46 || e.which == 0) {
                    return true;
                }
                else {
                    return false;
                }
            }
        }
</script>

Hope it helps you.

Jquery ajax call click event submit button

You did not add # before id of the button. You do not have right selector in your jquery code. So jquery is never execute in your button click. its submitted your form directly not passing any ajax request.

See documentation: http://api.jquery.com/category/selectors/
its your friend.

Try this:

It seems that id: $("#Shareitem").val() is wrong if you want to pass the value of

<input type="hidden" name="id" value="" id="id">

you need to change this line:

id: $("#Shareitem").val()

by

id: $("#id").val()

All together:

 <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
    <script>
    $(document).ready(function(){
      $("#Shareitem").click(function(e){
          e.preventDefault();
        $.ajax({type: "POST",
                url: "/imball-reagens/public/shareitem",
                data: { id: $("#Shareitem").val(), access_token: $("#access_token").val() },
                success:function(result){
          $("#sharelink").html(result);
        }});
      });
    });
    </script>

Preserve line breaks in angularjs

Try:

<div ng-repeat="item in items">
  <pre>{{item.description}}</pre>
</div>

The <pre> wrapper will print text with \n as text

also if you print the json, for better look use json filter, like:

<div ng-repeat="item in items">
  <pre>{{item.description|json}}</pre>
</div>

Demo

I agree with @Paul Weber that white-space: pre-wrap; is better approach, anyways using <pre> - the quick way mostly for debug some stuff (if you don't want to waste time on styling)

What's an appropriate HTTP status code to return by a REST API service for a validation failure?

There's a little bit more information about the semantics of these errors in RFC 2616, which documents HTTP 1.1.

Personally, I would probably use 400 Bad Request, but this is just my personal opinion without any factual support.

What are the obj and bin folders (created by Visual Studio) used for?

Be careful with setup projects if you're using them; Visual Studio setup projects Primary Output pulls from the obj folder rather than the bin.

I was releasing applications I thought were obfuscated and signed in msi setups for quite a while before I discovered that the deployed application files were actually neither obfuscated nor signed as I as performing the post-build procedure on the bin folder assemblies and should have been targeting the obj folder assemblies instead.

This is far from intuitive imho, but the general setup approach is to use the Primary Output of the project and this is the obj folder. I'd love it if someone could shed some light on this btw.

How to calculate the 95% confidence interval for the slope in a linear regression model in R

Let's fit the model:

> library(ISwR)
> fit <- lm(metabolic.rate ~ body.weight, rmr)
> summary(fit)

Call:
lm(formula = metabolic.rate ~ body.weight, data = rmr)

Residuals:
    Min      1Q  Median      3Q     Max 
-245.74 -113.99  -32.05  104.96  484.81 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept) 811.2267    76.9755  10.539 2.29e-13 ***
body.weight   7.0595     0.9776   7.221 7.03e-09 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 

Residual standard error: 157.9 on 42 degrees of freedom
Multiple R-squared: 0.5539, Adjusted R-squared: 0.5433 
F-statistic: 52.15 on 1 and 42 DF,  p-value: 7.025e-09 

The 95% confidence interval for the slope is the estimated coefficient (7.0595) ± two standard errors (0.9776).

This can be computed using confint:

> confint(fit, 'body.weight', level=0.95)
               2.5 % 97.5 %
body.weight 5.086656 9.0324

How to search text using php if ($text contains "World")

If you are looking an algorithm to rank search results based on relevance of multiple words here comes a quick and easy way of generating search results with PHP only.

Implementation of the vector space model in PHP

function get_corpus_index($corpus = array(), $separator=' ') {

    $dictionary = array();
    $doc_count = array();

    foreach($corpus as $doc_id => $doc) {
        $terms = explode($separator, $doc);
        $doc_count[$doc_id] = count($terms);

        // tf–idf, short for term frequency–inverse document frequency, 
        // according to wikipedia is a numerical statistic that is intended to reflect 
        // how important a word is to a document in a corpus

        foreach($terms as $term) {
            if(!isset($dictionary[$term])) {
                $dictionary[$term] = array('document_frequency' => 0, 'postings' => array());
            }
            if(!isset($dictionary[$term]['postings'][$doc_id])) {
                $dictionary[$term]['document_frequency']++;
                $dictionary[$term]['postings'][$doc_id] = array('term_frequency' => 0);
            }

            $dictionary[$term]['postings'][$doc_id]['term_frequency']++;
        }

        //from http://phpir.com/simple-search-the-vector-space-model/

    }

    return array('doc_count' => $doc_count, 'dictionary' => $dictionary);
}

function get_similar_documents($query='', $corpus=array(), $separator=' '){

    $similar_documents=array();

    if($query!=''&&!empty($corpus)){

        $words=explode($separator,$query);
        $corpus=get_corpus_index($corpus);
        $doc_count=count($corpus['doc_count']);

        foreach($words as $word) {
            $entry = $corpus['dictionary'][$word];
            foreach($entry['postings'] as $doc_id => $posting) {

                //get term frequency–inverse document frequency
                $score=$posting['term_frequency'] * log($doc_count + 1 / $entry['document_frequency'] + 1, 2);

                if(isset($similar_documents[$doc_id])){
                    $similar_documents[$doc_id]+=$score;
                }
                else{
                    $similar_documents[$doc_id]=$score;
                }

            }
        }

        // length normalise
        foreach($similar_documents as $doc_id => $score) {
            $similar_documents[$doc_id] = $score/$corpus['doc_count'][$doc_id];
        }

        // sort fro  high to low
        arsort($similar_documents);
    }   
    return $similar_documents;
}

IN YOUR CASE

$query = 'world';

$corpus = array(
    1 => 'hello world',
);

$match_results=get_similar_documents($query,$corpus);
echo '<pre>';
    print_r($match_results);
echo '</pre>';

RESULTS

Array
(
    [1] => 0.79248125036058
)

MATCHING MULTIPLE WORDS AGAINST MULTIPLE PHRASES

$query = 'hello world';

$corpus = array(
    1 => 'hello world how are you today?',
    2 => 'how do you do world',
    3 => 'hello, here you are! how are you? Are we done yet?'
);

$match_results=get_similar_documents($query,$corpus);
echo '<pre>';
    print_r($match_results);
echo '</pre>';

RESULTS

Array
(
    [1] => 0.74864218272161
    [2] => 0.43398500028846
)

from How do I check if a string contains a specific word in PHP?

Get the device width in javascript

Ya mybe u can use document.documentElement.clientWidth to get the device width of client and keep tracking the device width by put on setInterval

just like

setInterval(function(){
        width = document.documentElement.clientWidth;
        console.log(width);
    }, 1000);

How to return value from function which has Observable subscription inside?

For example this is my html template:

<select class="custom-select d-block w-100" id="genre" name="genre"
                  [(ngModel)]="film.genre"
                  #genreInput="ngModel"
                  required>
            <option value="">Choose...</option>
            <option *ngFor="let genre of genres;" [value]="genre.value">{{genre.name}}</option>
          </select>

This is the field that binded with template from my Component:

  // Genres of films like action or drama that will populate dropdown list.
  genres: Genre[];

I fetch genres of films from server dynamically. In order do communicate with server I have created FilmService

This is the method which communicate server:

 fetchGenres(): Observable<Genre[]> {
    return this.client.get(WebUtils.RESOURCE_HOST_API + 'film' + '/genre') as Observable<Genre[]>;
  }

Why this method returns Observable<Genre[]> not something like Genre[]?

JavaScript is async and it does not wait for a method to return value after an expensive process. With expensive I mean a process that take a time to return value. Like fetching data from server. So you have to return reference of Observable and subscribe it.

For example in my Component :

ngOnInit() {
    this.filmService.fetchGenres().subscribe(
      val => this.genres = val
    );
  }

react hooks useEffect() cleanup for only componentWillUnmount?

useEffect are isolated within its own scope and gets rendered accordingly. Image from https://reactjs.org/docs/hooks-custom.html

enter image description here

Right to Left support for Twitter Bootstrap 3

We Announce the AryaBootstrap,

The last version is based on bootstrap 4.3.1

AryaBootstrap is a bootstrap with dual layout align support and, used for LTR and RTL web design.

add "dir" to html, thats the only action you need to do.

Checkout the AryaBootstrap Website at: http://abs.aryavandidad.com/

AryaBootstrap at GitHub: https://github.com/mRizvandi/AryaBootstrap

What's a clean way to stop mongod on Mac OS X?

I prefer to stop the MongoDB server using the port command itself.

sudo port unload mongodb

And to start it again.

sudo port load mongodb

How do I increase the RAM and set up host-only networking in Vagrant?

I could not get any of these answers to work. Here's what I ended up putting at the very top of my Vagrantfile, before the Vagrant::Config.run do block:

Vagrant.configure("2") do |config|
  config.vm.provider "virtualbox" do |vb|
    vb.customize ["modifyvm", :id, "--memory", "1024"]
  end
end

I noticed that the shortcut accessor style, "vb.memory = 1024", didn't seem to work.

Loading a properties file from Java package

Assuming your using the Properties class, via its load method, and I guess you are using the ClassLoader getResourceAsStream to get the input stream.

How are you passing in the name, it seems it should be in this form: /com/al/common/email/templates/foo.properties

In Excel, sum all values in one column in each row where another column is a specific value

You should be able to use the IF function for that. the syntax is =IF(condition, value_if_true, value_if_false). To add an extra column with only the non-reimbursed amounts, you would use something like:

=IF(B1="No", A1, 0)

and sum that. There's probably a way to include it in a single cell below the column as well, but off the top of my head I can't think of anything simple.

Extract month and year from a zoo::yearmon object

You can use format:

library(zoo)
x <- as.yearmon(Sys.time())
format(x,"%b")
[1] "Mar"
format(x,"%Y")
[1] "2012"

Multiple conditions in a C 'for' loop

There is an operator in C called the comma operator. It executes each expression in order and returns the value of the last statement. It's also a sequence point, meaning each expression is guaranteed to execute in completely and in order before the next expression in the series executes, similar to && or ||.

Include jQuery in the JavaScript Console

Copy everything from:
https://code.jquery.com/jquery-3.4.1.min.js

And paste it into console. Works perfectly.

CSS background image to fit height, width should auto-scale in proportion

try

.something { 
    background: url(images/bg.jpg) no-repeat center center fixed; 
    width: 100%;
    height: 100%;
    position: fixed;
    top: 0;
    left: 0;
    z-index: -100;  
}

Different font size of strings in the same TextView

The best way to do that is Html without substring your text and fully dynamique For example :

  public static String getTextSize(String text,int size) {
         return "<span style=\"size:"+size+"\" >"+text+"</span>";

    }

and you can use color attribut etc... if the other hand :

size.setText(Html.fromHtml(getTextSize(ls.numProducts,100) + " " + mContext.getString(R.string.products));  

How do I remove a comma off the end of a string?

If you're concatenating something in the loop, you can do it in this way too:

$coma = "";
foreach($a as $b){
    $string .= $coma.$b;
    $coma = ",";
}

IntelliJ IDEA 13 uses Java 1.5 despite setting to 1.7

In your command line(Unix terminal) Go to your project root folder, and do this

find . -type f -name '*.iml' -exec sed -i '' s/JDK_1_5/JDK_1_8/g {} +

This will change the language level property in all your project .iml files from java 1.5 to java 1.8.

Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory

I solved this problem via creating storage\framework\sessions folder.

If statement within Where clause

CASE might help you out:

SELECT t.first_name,
       t.last_name,
       t.employid,
       t.status
  FROM employeetable t
 WHERE t.status = (CASE WHEN status_flag = STATUS_ACTIVE THEN 'A'
                        WHEN status_flag = STATUS_INACTIVE THEN 'T'
                        ELSE null END)
   AND t.business_unit = (CASE WHEN source_flag = SOURCE_FUNCTION THEN 'production'
                               WHEN source_flag = SOURCE_USER THEN 'users'
                               ELSE null END)
   AND t.first_name LIKE firstname
   AND t.last_name LIKE lastname
   AND t.employid LIKE employeeid;

The CASE statement evaluates multiple conditions to produce a single value. So, in the first usage, I check the value of status_flag, returning 'A', 'T' or null depending on what it's value is, and compare that to t.status. I do the same for the business_unit column with a second CASE statement.

How can I divide two integers stored in variables in Python?

The 1./2 syntax works because 1. is a float. It's the same as 1.0. The dot isn't a special operator that makes something a float. So, you need to either turn one (or both) of the operands into floats some other way -- for example by using float() on them, or by changing however they were calculated to use floats -- or turn on "true division", by using from __future__ import division at the top of the module.

Accessing the web page's HTTP Headers in JavaScript

Using mootools, you can use this.xhr.getAllResponseHeaders()