Programs & Examples On #8051

The 8051 is a Harvard architecture, single chip microcontroller (µC) which was developed by Intel in 1980 for use in embedded systems. The 8051 family of microcontrollers and derivatives continue to remain popular with a vast community of hobbyists and professionals.

Differences between TCP sockets and web sockets, one more time

WebSocket is basically an application protocol (with reference to the ISO/OSI network stack), message-oriented, which makes use of TCP as transport layer.

The idea behind the WebSocket protocol consists of reusing the established TCP connection between a Client and Server. After the HTTP handshake the Client and Server start speaking WebSocket protocol by exchanging WebSocket envelopes. HTTP handshaking is used to overcome any barrier (e.g. firewalls) between a Client and a Server offering some services (usually port 80 is accessible from anywhere, by anyone). Client and Server can switch over speaking HTTP in any moment, making use of the same TCP connection (which is never released).

Behind the scenes WebSocket rebuilds the TCP frames in consistent envelopes/messages. The full-duplex channel is used by the Server to push updates towards the Client in an asynchronous way: the channel is open and the Client can call any futures/callbacks/promises to manage any asynchronous WebSocket received message.

To put it simply, WebSocket is a high level protocol (like HTTP itself) built on TCP (reliable transport layer, on per frame basis) that makes possible to build effective real-time application with JS Clients (previously Comet and long-polling techniques were used to pull updates from the Server before WebSockets were implemented. See Stackoverflow post: Differences between websockets and long polling for turn based game server ).

Time in milliseconds in C

A couple of things might affect the results you're seeing:

  1. You're treating clock_t as a floating-point type, I don't think it is.
  2. You might be expecting (1^4) to do something else than compute the bitwise XOR of 1 and 4., i.e. it's 5.
  3. Since the XOR is of constants, it's probably folded by the compiler, meaning it doesn't add a lot of work at runtime.
  4. Since the output is buffered (it's just formatting the string and writing it to memory), it completes very quickly indeed.

You're not specifying how fast your machine is, but it's not unreasonable for this to run very quickly on modern hardware, no.

If you have it, try adding a call to sleep() between the start/stop snapshots. Note that sleep() is POSIX though, not standard C.

Java: Date from unix timestamp

For kotlin

fun unixToDate(timeStamp: Long) : String? {
    val time = java.util.Date(timeStamp as Long * 1000)
    val sdf = SimpleDateFormat("yyyy-MM-dd")
    return sdf.format(time)

}

Change the Value of h1 Element within a Form with JavaScript

You can use this: document.getElementById('h1_id').innerHTML = 'the new text';

How to insert selected columns from a CSV file to a MySQL database using LOAD DATA INFILE

For those who have the following error:

Error Code: 1290. The MySQL server is running with the --secure-file-priv option so it cannot execute this statement

You can simply run this command to see which folder can load files from:

SHOW VARIABLES LIKE "secure_file_priv";

After that, you have to copy the files in that folder and run the query with LOAD DATA LOCAL INFILE instead of LOAD DATA INFILE.

getResourceAsStream returns null

What you really need is a full absolute classPath for the file. So instead of guessing it, try to find out the ROOT and then move the file to a better location base one <.war> file structures...

URL test1 = getClass().getResource("/");
URL test2 = getClass().getClassLoader().getResource("/");            
URL test3 = getClass().getClassLoader().getResource("../");

logger.info(test1.getPath()); 
logger.info(test2.getPath());
logger.info(test3.getPath());

Chmod recursively

Try to change all the persmissions at the same time:

chmod -R +xr

Determine path of the executing script

I've made a package for this as of 2020-12-03 available on CRAN called "this.path".

Install it using:

install.packages("this.path")

and then use it by:

this.path::this.path()

or

library(this.path)

this.path()

I still have my original answer below, though it is less functional than the version in the package. On a Unix-alike OS, strange characters (such as " ") in the 'Rscript' command-line argument 'file' are replaced (such as "~+~"). R does this so that it is easier to use that filename for other system commands, but this isn't what we want. Given that we want a path usable in R, any such strange character sequences must be replaced.

Original Answer:

My answer is an improvement upon Jerry T's answer. The issue I found is that he is guessing whether a source call was made by checking if variable ofile is found in the first frame on the stack. This will not work with nested source calls, nor source calls made from a non-global environment. Additionally, a source call must be looked for before checking the command-line arguments, that has also been fixed. Here is my solution:

this.path <- function (verbose = getOption("verbose"))
{
    where <- function(x) if (verbose)
        cat("Source: ", x, "\n", sep = "")


    # loop through functions that lead here from most recent to earliest looking
    #     for an appropriate source call (a call to function base::source or base::sys.source)
    # an appropriate source call is a source call in which
    #     argument 'file' has been evaluated (forced)
    # this means, for example, the following is an inappropriate source call:
    #     source(this.path())
    # the argument 'file' is stored as a promise
    #     containing the expression "this.path()"
    # when the value of 'file' is requested, it assigns the value
    #     returned by evaluating "this.path()" to variable 'file'
    # there are two functions on the calling stack at
    #     this point being 'source' and 'this.path'
    # clearly, you don't want to request the 'file' argument from that source
    #     call because the value of 'file' is under evaluation right now!
    # the trick is to ask if variable ('ofile' for base::source, 'exprs' for base::sys.source)
    #     exists in that function's evaluation environment. this is because that
    #     variable is created AFTER argument 'file' has been forced
    # if that variable does exist, then argument 'file' has been forced and the
    #     source call is deemed appropriate. For base::source, the filename we want
    #     is the variable 'ofile' from that function's evaluation environment. For
    #     base::sys.source, the filename we want is the variable 'file' from that
    #     function's evaluation environment.
    # if that variable does NOT exist, then argument 'file' hasn't been forced and
    #     the source call is deemed inappropriate. The 'for' loop moves to the next
    #     function up the calling stack (if available)
    #
    # unfortunately, there is no way to check the argument 'fileName' has been forced
    #     for 'debugSource' since all the work is done internally in C. Instead,
    #     we have to use a 'tryCatch' statement. When we ask for an object by name
    #     using 'get', R is capable of realizing if a variable is asking for its
    #     own definition (a recursive definition). The exact error is "promise already
    #     under evaluation" which indicates that the promise evaluation is requesting
    #     its own value. So we use the 'tryCatch' to get the argument 'fileName'
    #     from the evaluation environment of 'debugSource', and if it does not raise
    #     an error, then we are safe to return that value. If not, the condition
    #     returns false and the 'for' loop moves to the next function up the calling
    #     stack (if available)


    if (.Platform$GUI == "RStudio")
        dbs <- get("debugSource", mode = "function", "tools:rstudio",
            inherits = FALSE)
    for (n in seq.int(sys.nframe(), 1L)[-1L]) {
        if (identical(sys.function(n), base::source) &&
            exists("ofile", envir = sys.frame(n), inherits = FALSE)) {
            path <- get("ofile", envir = sys.frame(n), inherits = FALSE)
            if (!is.character(path))
                path <- summary.connection(path)$description
            where("call to function source")
            return(normalizePath(path, mustWork = TRUE))
        }
        else if (identical(sys.function(n), base::sys.source) &&
            exists("exprs", envir = sys.frame(n), inherits = FALSE)) {
            path <- get("file", envir = sys.frame(n), inherits = FALSE)
            where("call to function sys.source")
            return(normalizePath(path, mustWork = TRUE))
        }
        else if (.Platform$GUI == "RStudio" && identical(sys.function(n), dbs) &&
            tryCatch({
                path <- get("fileName", envir = sys.frame(n), inherits = FALSE)
                TRUE
            }, error = function(c) {
                FALSE
            })) {
            where("call to function debugSource in RStudio")
            return(normalizePath(path, mustWork = TRUE))
        }
    }


    # if the for loop is passed, no appropriate
    #     source call was found up the calling stack
    # next, check if the user is running R from the command-line
    #     on a Windows OS, the GUI is "RTerm"
    #     on a Unix    OS, the GUI is "X11"


    if (.Platform$OS.type == "windows" && .Platform$GUI == "RTerm" ||  # running from Windows command-line
        .Platform$OS.type == "unix" && .Platform$GUI == "X11") {       # running from Unix command-line


        # get all command-line arguments that start with "--file="
        # check the number of command-line arguments starting with "--file="
        #     in case more or less than one were supplied


        path <- grep("^--file=", commandArgs(), value = TRUE)
        if (length(path) == 1L) {
            path <- sub("^--file=", "", path)
            where("Command-line argument 'file'")
            return(normalizePath(path, mustWork = TRUE))
        }
        else if (length(path)) {
            stop("'this.path' used in an inappropriate fashion\n",
                "* no appropriate source call was found up the calling stack\n",
                "* R is being run from the command-line and formal argument \"--file=\" matched by multiple actual arguments\n")
        }
        else stop("'this.path' used in an inappropriate fashion\n",
            "* no appropriate source call was found up the calling stack\n",
            "* R is being run from the command-line and argument \"--file=\" is missing\n")
    }
    else if (.Platform$GUI == "RStudio") {  # running R from 'RStudio'


        # function ".rs.api.getActiveDocumentContext" from the environment "tools:rstudio"
        #     returns a list of information about the document where your cursor is located
        #
        # function ".rs.api.getSourceEditorContext" from the environment "tools:rstudio"
        #     returns a list of information about the document open in the current tab
        #
        # element 'id' is a character string, an identification for the document
        # element 'path' is a character string, the path of the document


        adc <- get(".rs.api.getActiveDocumentContext",
            mode = "function", "tools:rstudio", inherits = FALSE)()
        if (adc$id != "#console") {
            path <- adc$path
            if (nzchar(path)) {
                where("active document in RStudio")
                return(normalizePath(path, mustWork = TRUE))
            }
            else stop("'this.path' used in an inappropriate fashion\n",
                "* no appropriate source call was found up the calling stack\n",
                "* active document in RStudio does not exist\n")
        }


        sec <- get(".rs.api.getSourceEditorContext", mode = "function",
            "tools:rstudio", inherits = FALSE)()
        if (!is.null(sec)) {
            path <- sec$path
            if (nzchar(path)) {
                where("source document in RStudio")
                return(normalizePath(path, mustWork = TRUE))
            }
            else stop("'this.path' used in an inappropriate fashion\n",
                "* no appropriate source call was found up the calling stack\n",
                "* source document in RStudio does not exist\n")
        }
        else stop("'this.path' used in an inappropriate fashion\n",
            "* no appropriate source call was found up the calling stack\n",
            "* R is being run from RStudio with no documents open\n")
    }
    else if (.Platform$OS.type == "windows" && .Platform$GUI == "Rgui") {  # running R from 'RGui' on Windows


        # on a Windows OS only, the function "getWindowsHandles" from the base
        # package "utils" returns a list of external pointers containing the windows
        # handles. The thing of interest are the names of this list, these should
        # be the names of the windows belonging to the current R process. Since
        # RGui can have files besides R scripts open (such as images), a regular
        # expression is used to subset only windows handles with names that exactly
        # match the string "R Console" or end with " - R Editor". I highly suggest
        # that you NEVER end a document's filename with " - R Editor". From there,
        # similar checks are done as in the above section for 'RStudio'


        wh <- names(utils::getWindowsHandles(pattern = "^R Console$| - R Editor$",
            minimized = TRUE))


        if (!length(wh))
            stop("this error SHOULD be unreachable, as far as I know it's impossible to have an R\n",
                "  process running without the R Console open. If you reached this error, please\n",
                "  send a bug report to the package maintainer")


        path <- wh[1L]
        if (path != "R Console") {
            path <- sub(" - R Editor$", "", path)
            if (path != "Untitled") {
                where("active document in RGui")
                return(normalizePath(path, mustWork = TRUE))
            }
            else stop("'this.path' used in an inappropriate fashion\n",
                "* no appropriate source call was found up the calling stack\n",
                "* active document in RGui does not exist\n")
        }


        path <- wh[2L]
        if (!is.na(path)) {
            path <- sub(" - R Editor$", "", path)
            if (path != "Untitled") {
                where("source document in RGui")
                return(normalizePath(path, mustWork = TRUE))
            }
            else stop("'this.path' used in an inappropriate fashion\n",
                "* no appropriate source call was found up the calling stack\n",
                "* source document in RGui does not exist\n")
        }
        else stop("'this.path' used in an inappropriate fashion\n",
            "* no appropriate source call was found up the calling stack\n",
            "* R is being run from RGui with no documents open\n")
    }
    else if (.Platform$OS.type == "unix" && .Platform$GUI == "AQUA") {  # running R from 'RGui' on Unix
        stop("'this.path' used in an inappropriate fashion\n",
            "* no appropriate source call was found up the calling stack\n",
            "* R is being run from AQUA which requires a source call on the calling stack\n")
    }
    else stop("'this.path' used in an inappropriate fashion\n",
        "* no appropriate source call was found up the calling stack\n",
        "* R is being run in an unrecognized manner\n")
}

How do I force "git pull" to overwrite local files?

WARNING: git clean deletes all your untracked files/directories and can't be undone.


Sometimes just clean -f does not help. In case you have untracked DIRECTORIES, -d option also needed:

# WARNING: this can't be undone!

git reset --hard HEAD
git clean -f -d
git pull

WARNING: git clean deletes all your untracked files/directories and can't be undone.

Consider using -n (--dry-run) flag first. This will show you what will be deleted without actually deleting anything:

git clean -n -f -d

Example output:

Would remove untracked-file-1.txt
Would remove untracked-file-2.txt
Would remove untracked/folder
...

UnicodeDecodeError: 'utf8' codec can't decode byte 0x9c

I have resolved this problem using this code

df = pd.read_csv(gdp_path, engine='python')

javascript check for not null

This should work fine..

   if(val!= null)
    {
       alert("value is "+val.length); //-- this returns 4
    }
    else
    {
       alert("value* is null");
    }

Why doesn't C++ have a garbage collector?

When we compare C++ with Java, we see that C++ was not designed with implicit Garbage Collection in mind, while Java was.

Having things like arbitrary pointers in C-Style is not only bad for GC-implementations, but it would also destroy backward compatibility for a large amount of C++-legacy-code.

In addition to that, C++ is a language that is intended to run as standalone executable instead of having a complex run-time environment.

All in all: Yes it might be possible to add Garbage Collection to C++, but for the sake of continuity it is better not to do so.

Are global variables bad?

I'd answer this question with another question: Do you use singeltons/ Are singeltons bad?

Because (almost all) singelton usage is a glorified global variable.

How can I change the class of an element with jQuery>

I like to write a small plugin to make things cleaner:

$.fn.setClass = function(classes) {
    this.attr('class', classes);
    return this;
};

That way you can simply do

$('button').setClass('btn btn-primary');

How to get the top 10 values in postgresql?

For this you can use limit

select *
from scores
order by score desc
limit 10

If performance is important (when is it not ;-) look for an index on score.


Starting with version 8.4, you can also use the standard (SQL:2008) fetch first

select *
from scores
order by score desc
fetch first 10 rows only

As @Raphvanns pointed out, this will give you the first 10 rows literally. To remove duplicate values, you have to select distinct rows, e.g.

select distinct *
from scores
order by score desc
fetch first 10 rows only

SQL Fiddle

How to programmatically set the ForeColor of a label to its default?

The default (when created with the designer) is:

label.ForeColor = SystemColors.ControlText;

This should respect the system color settings (e.g. these "high contrast" schemes for visual impaired).

How to configure PHP to send e-mail?

You need to have a smtp service setup in your local machine in order to send emails. There are many available freely just search on google.

If you own a server or VPS upload the script and it will work fine.

How to get a list of user accounts using the command line in MySQL?

Login to mysql as root and type following query

select User from mysql.user;

+------+
| User |
+------+
| amon |
| root |
| root |
+------+

How to display svg icons(.svg files) in UI using React Component?

For some reasons above mentioned approaches did now work for me, before I followed the advice to add .default like this:

<div>
  <img src={require('../../mySvgImage.svg').default} alt='mySvgImage' />
</div>

getCurrentPosition() and watchPosition() are deprecated on insecure origins

I know that the geoLocation API is better but for people whom can't use an SSL, you can still use some sort of services such as geopluginService.

as specified in the documentation you simply send a request with the ip to the service url http://www.geoplugin.net/php.gp?ip=xx.xx.xx.xx the output is a serialized array so you must need to unserialize it before using it.

Remember this service is not very accurate as the geoLocation is, but it is still an easy and fast solution.

jQuery get value of selected radio button

To get the value of the selected Radio Button, Use RadioButtonName and the Form Id containing the RadioButton.

$('input[name=radioName]:checked', '#myForm').val()

OR by only

$('form input[type=radio]:checked').val();

How to set css style to asp.net button?

You can assign a class to your ASP.NET Button and then apply the desired style to it.

<asp:Button class="mybtn" Text="Button" runat="server"></asp:Button>

CSS:

.mybtn
{
   border:1px solid Red;
   //some more styles
}

SQL Server ORDER BY date and nulls last

Use desc and multiply by -1 if necessary. Example for ascending int ordering with nulls last:

select * 
from
(select null v union all select 1 v union all select 2 v) t
order by -t.v desc

Pass table as parameter into sql server UDF

    create table Project (ProjectId int, Description varchar(50));
    insert into Project values (1, 'Chase tail, change directions');
    insert into Project values (2, 'ping-pong ball in clothes dryer');

    create table ProjectResource (ProjectId int, ResourceId int, Name varchar(15));
    insert into ProjectResource values (1, 1, 'Adam');
    insert into ProjectResource values (1, 2, 'Kerry');
    insert into ProjectResource values (1, 3, 'Tom');
    insert into ProjectResource values (2, 4, 'David');
    insert into ProjectResource values (2, 5, 'Jeff');


    SELECT *, 
      (SELECT Name + ' ' AS [text()] 
       FROM ProjectResource pr 
       WHERE pr.ProjectId = p.ProjectId 
       FOR XML PATH ('')) 
    AS ResourceList 
    FROM Project p

-- ProjectId    Description                        ResourceList
-- 1            Chase tail, change directions      Adam Kerry Tom 
-- 2            ping-pong ball in clothes dryer    David Jeff 

Print "hello world" every X seconds

I figure it out with a timer, hope it helps. I have used a timer from java.util.Timer and TimerTask from the same package. See below:

TimerTask task = new TimerTask() {

    @Override
    public void run() {
        System.out.println("Hello World");
    }
};

Timer timer = new Timer();
timer.schedule(task, new Date(), 3000);

How to resize an image to a specific size in OpenCV?

You can use cvResize. Or better use c++ interface (eg cv::Mat instead of IplImage and cv::imread instead of cvLoadImage) and then use cv::resize which handles memory allocation and deallocation itself.

How to disable a button when an input is empty?

You'll need to keep the current value of the input in state (or pass changes in its value up to a parent via a callback function, or sideways, or <your app's state management solution here> such that it eventually gets passed back into your component as a prop) so you can derive the disabled prop for the button.

Example using state:

_x000D_
_x000D_
<meta charset="UTF-8">_x000D_
<script src="https://fb.me/react-0.13.3.js"></script>_x000D_
<script src="https://fb.me/JSXTransformer-0.13.3.js"></script>_x000D_
<div id="app"></div>_x000D_
<script type="text/jsx;harmony=true">void function() { "use strict";_x000D_
_x000D_
var App = React.createClass({_x000D_
  getInitialState() {_x000D_
    return {email: ''}_x000D_
  },_x000D_
  handleChange(e) {_x000D_
    this.setState({email: e.target.value})_x000D_
  },_x000D_
  render() {_x000D_
    return <div>_x000D_
      <input name="email" value={this.state.email} onChange={this.handleChange}/>_x000D_
      <button type="button" disabled={!this.state.email}>Button</button>_x000D_
    </div>_x000D_
  }_x000D_
})_x000D_
_x000D_
React.render(<App/>, document.getElementById('app'))_x000D_
_x000D_
}()</script>
_x000D_
_x000D_
_x000D_

CSS3 transform not working

In webkit-based browsers(Safari and Chrome), -webkit-transform is ignored on inline elements.. Set display: inline-block; to make it work. For demonstration/testing purposes, you may also want to use a negative angle or a transformation-origin lest the text is rotated out of the visible area.

Refresh page after form submitting

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"> <!-- notice the updated action -->
<textarea cols="30" rows="4" name="update" id="update" maxlength="200" ></textarea>
<br />
<input name="submit_button" type="submit"  value=" Update "  id="update_button"  class="update_button"/> <!-- notice added name="" -->
</form>

on your full page, you could have this

<?php

// check if the form was submitted
if ($_POST['submit_button']) {
    // this means the submit button was clicked, and the form has refreshed the page
    // to access the content in text area, you would do this
    $a = $_POST['update'];

    // now $a contains the data from the textarea, so you can do whatever with it
    // this will echo the data on the page
    echo $a;
}
else {
    // form not submitted, so show the form

?>

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"> <!-- notice the updated action -->
<textarea cols="30" rows="4" name="update" id="update" maxlength="200" ></textarea>
<br />
<input name="submit_button" type="submit"  value=" Update "  id="update_button"  class="update_button"/> <!-- notice added name="" -->
</form>

<?php

} // end "else" loop

?>

How to create empty folder in java?

Looks file you use the .mkdirs() method on a File object: http://www.roseindia.net/java/beginners/java-create-directory.shtml

// Create a directory; all non-existent ancestor directories are
// automatically created
success = (new File("../potentially/long/pathname/without/all/dirs")).mkdirs();
if (!success) {
    // Directory creation failed
}

How to use (install) dblink in PostgreSQL?

# or even faster copy paste answer if you have sudo on the host 
sudo su - postgres  -c "psql template1 -c 'CREATE EXTENSION IF NOT EXISTS \"dblink\";'"

How do I set proxy for chrome in python webdriver?

from selenium import webdriver

PROXY = "23.23.23.23:3128" # IP:PORT or HOST:PORT

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--proxy-server=%s' % PROXY)

chrome = webdriver.Chrome(options=chrome_options)
chrome.get("http://whatismyipaddress.com")

Error: expected type-specifier before 'ClassName'

For future people struggling with a similar problem, the situation is that the compiler simply cannot find the type you are using (even if your Intelisense can find it).

This can be caused in many ways:

  • You forgot to #include the header that defines it.
  • Your inclusion guards (#ifndef BLAH_H) are defective (your #ifndef BLAH_H doesn't match your #define BALH_H due to a typo or copy+paste mistake).
  • Your inclusion guards are accidentally used twice (two separate files both using #define MYHEADER_H, even if they are in separate directories)
  • You forgot that you are using a template (eg. new Vector() should be new Vector<int>())
  • The compiler is thinking you meant one scope when really you meant another (For example, if you have NamespaceA::NamespaceB, AND a <global scope>::NamespaceB, if you are already within NamespaceA, it'll look in NamespaceA::NamespaceB and not bother checking <global scope>::NamespaceB) unless you explicitly access it.
  • You have a name clash (two entities with the same name, such as a class and an enum member).

To explicitly access something in the global namespace, prefix it with ::, as if the global namespace is a namespace with no name (e.g. ::MyType or ::MyNamespace::MyType).

Amazon S3 boto - how to create a folder?

It's really easy to create folders. Actually it's just creating keys.

You can see my below code i was creating a folder with utc_time as name.

Do remember ends the key with '/' like below, this indicates it's a key:

Key='folder1/' + utc_time + '/'

client = boto3.client('s3')
utc_timestamp = time.time()


def lambda_handler(event, context):

    UTC_FORMAT = '%Y%m%d'
    utc_time = datetime.datetime.utcfromtimestamp(utc_timestamp)
    utc_time = utc_time.strftime(UTC_FORMAT)
    print 'start to create folder for => ' + utc_time

    putResponse = client.put_object(Bucket='mybucketName',
                                    Key='folder1/' + utc_time + '/')

    print putResponse

Bootstrap 3 grid with no gap

Generalizing on martinedwards and others' ideas, you can glue a bunch of columns together (not just a pair) by adjusting padding of even and odd column children. Adding this definition of a class, .no-gutter, and placing it on your .row element

.row.no-gutter > [class*='col-']:nth-child(2n+1) {
    padding-right: 0;
 } 

.row.no-gutter > [class*='col-']:nth-child(2n) {
    padding-left: 0;
}

Or in SCSS:

.no-gutter  {
    > [class*='col-'] {
        &:nth-child(2n+1) {
            padding-right: 0;
        }
        &:nth-child(2n) {
            padding-left: 0;
        }
    }
}

Handling Dialogs in WPF with MVVM

I think the view could have code to handle the event from the view model.

Depending on the event/scenario, it could also have an event trigger that subscribes to view model events, and one or more actions to invoke in response.

What are the differences and similarities between ffmpeg, libav, and avconv?

Confusing messages

These messages are rather misleading and understandably a source of confusion. Older Ubuntu versions used Libav which is a fork of the FFmpeg project. FFmpeg returned in Ubuntu 15.04 "Vivid Vervet".

The fork was basically a non-amicable result of conflicting personalities and development styles within the FFmpeg community. It is worth noting that the maintainer for Debian/Ubuntu switched from FFmpeg to Libav on his own accord due to being involved with the Libav fork.

The real ffmpeg vs the fake one

For a while both Libav and FFmpeg separately developed their own version of ffmpeg.

Libav then renamed their bizarro ffmpeg to avconv to distance themselves from the FFmpeg project. During the transition period the "not developed anymore" message was displayed to tell users to start using avconv instead of their counterfeit version of ffmpeg. This confused users into thinking that FFmpeg (the project) is dead, which is not true. A bad choice of words, but I can't imagine Libav not expecting such a response by general users.

This message was removed upstream when the fake "ffmpeg" was finally removed from the Libav source, but, depending on your version, it can still show up in Ubuntu because the Libav source Ubuntu uses is from the ffmpeg-to-avconv transition period.

In June 2012, the message was re-worded for the package libav - 4:0.8.3-0ubuntu0.12.04.1. Unfortunately the new "deprecated" message has caused additional user confusion.

Starting with Ubuntu 15.04 "Vivid Vervet", FFmpeg's ffmpeg is back in the repositories again.

libav vs Libav

To further complicate matters, Libav chose a name that was historically used by FFmpeg to refer to its libraries (libavcodec, libavformat, etc). For example the libav-user mailing list, for questions and discussions about using the FFmpeg libraries, is unrelated to the Libav project.

How to tell the difference

If you are using avconv then you are using Libav. If you are using ffmpeg you could be using FFmpeg or Libav. Refer to the first line in the console output to tell the difference: the copyright notice will either mention FFmpeg or Libav.

Secondly, the version numbering schemes differ. Each of the FFmpeg or Libav libraries contains a version.h header which shows a version number. FFmpeg will end in three digits, such as 57.67.100, and Libav will end in one digit such as 57.67.0. You can also view the library version numbers by running ffmpeg or avconv and viewing the console output.

If you want to use the real ffmpeg

Ubuntu 15.04 "Vivid Vervet" or newer

The real ffmpeg is in the repository, so you can install it with:

apt-get install ffmpeg

For older Ubuntu versions

Your options are:

These methods are non-intrusive, reversible, and will not interfere with the system or any repository packages.

Another possible option is to upgrade to Ubuntu 15.04 "Vivid Vervet" or newer and just use ffmpeg from the repository.

Also see

For an interesting blog article on the situation, as well as a discussion about the main technical differences between the projects, see The FFmpeg/Libav situation.

Match groups in Python

Less efficient, but simpler-looking:

m0 = re.match("I love (\w+)", statement)
m1 = re.match("Ich liebe (\w+)", statement)
m2 = re.match("Je t'aime (\w+)", statement)
if m0:
  print "He loves",m0.group(1)
elif m1:
  print "Er liebt",m1.group(1)
elif m2:
  print "Il aime",m2.group(1)

The problem with the Perl stuff is the implicit updating of some hidden variable. That's simply hard to achieve in Python because you need to have an assignment statement to actually update any variables.

The version with less repetition (and better efficiency) is this:

pats = [
    ("I love (\w+)", "He Loves {0}" ),
    ("Ich liebe (\w+)", "Er Liebe {0}" ),
    ("Je t'aime (\w+)", "Il aime {0}")
 ]
for p1, p3 in pats:
    m= re.match( p1, statement )
    if m:
        print p3.format( m.group(1) )
        break

A minor variation that some Perl folk prefer:

pats = {
    "I love (\w+)" : "He Loves {0}",
    "Ich liebe (\w+)" : "Er Liebe {0}",
    "Je t'aime (\w+)" : "Il aime {0}",
}
for p1 in pats:
    m= re.match( p1, statement )
    if m:
        print pats[p1].format( m.group(1) )
        break

This is hardly worth mentioning except it does come up sometimes from Perl programmers.

How to replace a whole line with sed?

This might work for you:

cat <<! | sed '/aaa=\(bbb\|ccc\|ddd\)/!s/\(aaa=\).*/\1xxx/'
> aaa=bbb
> aaa=ccc
> aaa=ddd
> aaa=[something else]
!
aaa=bbb
aaa=ccc
aaa=ddd
aaa=xxx

How to confirm RedHat Enterprise Linux version?

Avoid /etc/*release* files and run this command instead, it is far more reliable and gives more details:

rpm -qia '*release*'

How to remove listview all items

You can do this:

listView.setAdapter(null);

Cross Domain Form POSTing

Same origin policy has nothing to do with sending request to another url (different protocol or domain or port).

It is all about restricting access to (reading) response data from another url. So JavaScript code within a page can post to arbitrary domain or submit forms within that page to anywhere (unless the form is in an iframe with different url).

But what makes these POST requests inefficient is that these requests lack antiforgery tokens, so are ignored by the other url. Moreover, if the JavaScript tries to get that security tokens, by sending AJAX request to the victim url, it is prevented to access that data by Same Origin Policy.

A good example: here

And a good documentation from Mozilla: here

how to find array size in angularjs

Just use the length property of a JavaScript array like so:

$scope.names.length

Also, I don't see a starting <script> tag in your code.

If you want the length inside your view, do it like so:

{{ names.length }}

Which is the preferred way to concatenate a string in Python?

Using in place string concatenation by '+' is THE WORST method of concatenation in terms of stability and cross implementation as it does not support all values. PEP8 standard discourages this and encourages the use of format(), join() and append() for long term use.

As quoted from the linked "Programming Recommendations" section:

For example, do not rely on CPython's efficient implementation of in-place string concatenation for statements in the form a += b or a = a + b. This optimization is fragile even in CPython (it only works for some types) and isn't present at all in implementations that don't use refcounting. In performance sensitive parts of the library, the ''.join() form should be used instead. This will ensure that concatenation occurs in linear time across various implementations.

How might I schedule a C# Windows Service to perform a task daily?

Does it have to be an actual service? Can you just use the built in scheduled tasks in the windows control panel.

How to execute a stored procedure inside a select query

Functions are easy to call inside a select loop, but they don't let you run inserts, updates, deletes, etc. They are only useful for query operations. You need a stored procedure to manipulate the data.

So, the real answer to this question is that you must iterate through the results of a select statement via a "cursor" and call the procedure from within that loop. Here's an example:

DECLARE @myId int;
DECLARE @myName nvarchar(60);
DECLARE myCursor CURSOR FORWARD_ONLY FOR
    SELECT Id, Name FROM SomeTable;
OPEN myCursor;
FETCH NEXT FROM myCursor INTO @myId, @myName;
WHILE @@FETCH_STATUS = 0 BEGIN
    EXECUTE dbo.myCustomProcedure @myId, @myName;
    FETCH NEXT FROM myCursor INTO @myId, @myName;
END;
CLOSE myCursor;
DEALLOCATE myCursor;

Note that @@FETCH_STATUS is a standard variable which gets updated for you. The rest of the object names here are custom.

HTML table with fixed headers and a fixed column?

The jQuery DataTables plug-in is one excellent way to achieve excel-like fixed column(s) and headers.

Note the examples section of the site and the "extras".
http://datatables.net/examples/
http://datatables.net/extras/

The "Extras" section has tools for fixed columns and fixed headers.

Fixed Columns
http://datatables.net/extras/fixedcolumns/
(I believe the example on this page is the one most appropriate for your question.)

Fixed Header
http://datatables.net/extras/fixedheader/
(Includes an example with a full page spreadsheet style layout: http://datatables.net/release-datatables/extras/FixedHeader/top_bottom_left_right.html)

Setting up redirect in web.config file

In case that you need to add the http redirect in many sites, you could use it as a c# console program:

   class Program
{
    static int Main(string[] args)
    {
        if (args.Length < 3)
        {
            Console.WriteLine("Please enter an argument: for example insert-redirect ./web.config http://stackoverflow.com");
            return 1;
        }

        if (args.Length == 3)
        {
            if (args[0].ToLower() == "-insert-redirect")
            {
                var path = args[1];
                var value = args[2];

                if (InsertRedirect(path, value))
                    Console.WriteLine("Redirect added.");
                return 0;
            }
        }

        Console.WriteLine("Wrong parameters.");
        return 1;

    }

    static bool InsertRedirect(string path, string value)
    {
        try
        {
            XmlDocument doc = new XmlDocument();

            doc.Load(path);

            // This should find the appSettings node (should be only one):
            XmlNode nodeAppSettings = doc.SelectSingleNode("//system.webServer");

            var existNode = nodeAppSettings.SelectSingleNode("httpRedirect");
            if (existNode != null)
                return false;

            // Create new <add> node
            XmlNode nodeNewKey = doc.CreateElement("httpRedirect");

            XmlAttribute attributeEnable = doc.CreateAttribute("enabled");
            XmlAttribute attributeDestination = doc.CreateAttribute("destination");
            //XmlAttribute attributeResponseStatus = doc.CreateAttribute("httpResponseStatus");

            // Assign values to both - the key and the value attributes:

            attributeEnable.Value = "true";
            attributeDestination.Value = value;
            //attributeResponseStatus.Value = "Permanent";

            // Add both attributes to the newly created node:
            nodeNewKey.Attributes.Append(attributeEnable);
            nodeNewKey.Attributes.Append(attributeDestination);
            //nodeNewKey.Attributes.Append(attributeResponseStatus);

            // Add the node under the 
            nodeAppSettings.AppendChild(nodeNewKey);
            doc.Save(path);

            return true;
        }
        catch (Exception e)
        {
            Console.WriteLine($"Exception adding redirect: {e.Message}");
            return false;
        }
    }
}

git: fatal unable to auto-detect email address

If git config --global user.email "[email protected]" git config --global user.name "github_username"

Dont work like in my case, you can use:

git config --replace-all user.email "[email protected]"
git config --replace-all user.name "github_username"

How to set DialogFragment's width and height?

When I need to make the DialogFragment a bit wider I'm setting minWidth:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:minWidth="320dp"
    ... />

openCV program compile error "libopencv_core.so.2.4: cannot open shared object file: No such file or directory" in ubuntu 12.04

Add this link:

/usr/local/lib/*.so.*

The total is:

g++ -o main.out main.cpp -I /usr/local/include -I /usr/local/include/opencv -I /usr/local/include/opencv2 -L /usr/local/lib /usr/local/lib/*.so /usr/local/lib/*.so.*

Generate your own Error code in swift 3

You can create a protocol, conforming to the Swift LocalizedError protocol, with these values:

protocol OurErrorProtocol: LocalizedError {

    var title: String? { get }
    var code: Int { get }
}

This then enables us to create concrete errors like so:

struct CustomError: OurErrorProtocol {

    var title: String?
    var code: Int
    var errorDescription: String? { return _description }
    var failureReason: String? { return _description }

    private var _description: String

    init(title: String?, description: String, code: Int) {
        self.title = title ?? "Error"
        self._description = description
        self.code = code
    }
}

Entity Framework and SQL Server View

I was able to resolve this using the designer.

  1. Open the Model Browser.
  2. Find the view in the diagram.
  3. Right click on the primary key, and make sure "Entity Key" is checked.
  4. Multi-select all the non-primary keys. Use Ctrl or Shift keys.
  5. In the Properties window (press F4 if needed to see it), change the "Entity Key" drop-down to False.
  6. Save changes.
  7. Close Visual Studio and re-open it. I am using Visual Studio 2013 with EF 6 and I had to do this to get the warnings to go away.

I did not have to change my view to use the ISNULL, NULLIF, or COALESCE workarounds. If you update your model from the database, the warnings will re-appear, but will go away if you close and re-open VS. The changes you made in the designer will be preserved and not affected by the refresh.

How to differ sessions in browser-tabs?

You shouldn't. If you want to do such a thing either you need to force user to use a single instance of your application by writing URLs on the fly use a sessionID alike (not sessionid it won't work) id and pass it in every URL.

I don't know why you need it but unless you need make a totally unusable application don't do it.

Perform a Shapiro-Wilk Normality Test

You failed to specify the exact columns (data) to test for normality. Use this instead

shapiro.test(heisenberg$HWWIchg)

Where/how can I download (and install) the Microsoft.Jet.OLEDB.4.0 for Windows 8, 64 bit?

On modern Windows this driver isn't available by default anymore, but you can download as Microsoft Access Database Engine 2010 Redistributable on the MS site. If your app is 32 bits be sure to download and install the 32 bits variant because to my knowledge the 32 and 64 bit variant cannot coexist.

Depending on how your app locates its db driver, that might be all that's needed. However, if you use an UDL file there's one extra step - you need to edit that file. Unfortunately, on a 64bits machine the wizard used to edit UDL files is 64 bits by default, it won't see the JET driver and just slap whatever driver it finds first in the UDL file. There are 2 ways to solve this issue:

  1. start the 32 bits UDL wizard like this: C:\Windows\syswow64\rundll32.exe "C:\Program Files (x86)\Common Files\System\Ole DB\oledb32.dll",OpenDSLFile C:\path\to\your.udl. Note that I could use this technique on a Win7 64 Pro, but it didn't work on a Server 2008R2 (could be my mistake, just mentioning)
  2. open the UDL file in Notepad or another text editor, it should more or less have this format:

[oledb] ; Everything after this line is an OLE DB initstring Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Path\To\The\database.mdb;Persist Security Info=False

That should allow your app to start correctly.

Initialize a vector array of strings

If you are using cpp11 (enable with the -std=c++0x flag if needed), then you can simply initialize the vector like this:

// static std::vector<std::string> v;
v = {"haha", "hehe"};

Why javascript getTime() is not a function?

To use this function/method,you need an instance of the class Date .

This method is always used in conjunction with a Date object.

See the code below :

var d = new Date();
d.getTime();

Link : http://www.w3schools.com/jsref/jsref_getTime.asp

Calculating a 2D Vector's Cross Product

Implementation 1 returns the magnitude of the vector that would result from a regular 3D cross product of the input vectors, taking their Z values implicitly as 0 (i.e. treating the 2D space as a plane in the 3D space). The 3D cross product will be perpendicular to that plane, and thus have 0 X & Y components (thus the scalar returned is the Z value of the 3D cross product vector).

Note that the magnitude of the vector resulting from 3D cross product is also equal to the area of the parallelogram between the two vectors, which gives Implementation 1 another purpose. In addition, this area is signed and can be used to determine whether rotating from V1 to V2 moves in an counter clockwise or clockwise direction. It should also be noted that implementation 1 is the determinant of the 2x2 matrix built from these two vectors.

Implementation 2 returns a vector perpendicular to the input vector still in the same 2D plane. Not a cross product in the classical sense but consistent in the "give me a perpendicular vector" sense.

Note that 3D euclidean space is closed under the cross product operation--that is, a cross product of two 3D vectors returns another 3D vector. Both of the above 2D implementations are inconsistent with that in one way or another.

Hope this helps...

Border in shape xml

It looks like you forgot the prefix on the color attribute. Try

 <stroke android:width="2dp" android:color="#ff00ffff"/>

jQuery get value of select onChange

Let me share an example which I developed with BS4, thymeleaf and Spring boot.

I am using two SELECTs, where the second ("subtopic") gets filled by an AJAX call based on the selection of the first("topic").

First, the thymeleaf snippet:

 <div class="form-group">
     <label th:for="topicId" th:text="#{label.topic}">Topic</label>
     <select class="custom-select"
             th:id="topicId" th:name="topicId"
             th:field="*{topicId}"
             th:errorclass="is-invalid" required>
         <option value="" selected
                 th:text="#{option.select}">Select
         </option>
         <optgroup th:each="topicGroup : ${topicGroups}"
                   th:label="${topicGroup}">
             <option th:each="topicItem : ${topics}"
                     th:if="${topicGroup == topicItem.grp} "
                     th:value="${{topicItem.baseIdentity.id}}"
                     th:text="${topicItem.name}"
                     th:selected="${{topicItem.baseIdentity.id==topicId}}">
             </option>
         </optgroup>
         <option th:each="topicIter : ${topics}"
                 th:if="${topicIter.grp == ''} "
                 th:value="${{topicIter.baseIdentity.id}}"
                 th:text="${topicIter.name}"
                 th:selected="${{topicIter.baseIdentity?.id==topicId}}">
         </option>
     </select>
     <small id="topicHelp" class="form-text text-muted"
            th:text="#{label.topic.tt}">select</small>
</div><!-- .form-group -->

<div class="form-group">
    <label for="subtopicsId" th:text="#{label.subtopicsId}">subtopics</label>
    <select class="custom-select"
            id="subtopicsId" name="subtopicsId"
            th:field="*{subtopicsId}"
            th:errorclass="is-invalid" multiple="multiple">
        <option value="" disabled
                th:text="#{option.multiple.optional}">Select
        </option>
        <option th:each="subtopicsIter : ${subtopicsList}"
                th:value="${{subtopicsIter.baseIdentity.id}}"
                th:text="${subtopicsIter.name}">
        </option>
    </select>
    <small id="subtopicsHelp" class="form-text text-muted"
           th:unless="${#fields.hasErrors('subtopicsId')}"
           th:text="#{label.subtopics.tt}">select</small>
    <small id="subtopicsIdError" class="invalid-feedback"
           th:if="${#fields.hasErrors('subtopicsId')}"
           th:errors="*{subtopicsId}">Errors</small>
</div><!-- .form-group -->

I am iterating over a list of topics that is stored in the model context, showing all groups with their topics, and after that all topics that do not have a group. BaseIdentity is an @Embedded composite key BTW.

Now, here's the jQuery that handles changes:

$('#topicId').change(function () {
    selectedOption = $(this).val();
    if (selectedOption === "") {
        $('#subtopicsId').prop('disabled', 'disabled').val('');
        $("#subtopicsId option").slice(1).remove(); // keep first
    } else {
        $('#subtopicsId').prop('disabled', false)
        var orig = $(location).attr('origin');
        var url = orig + "/getsubtopics/" + selectedOption;
        $.ajax({
            url: url,
           success: function (response) {
                  var len = response.length;
                    $("#subtopicsId option[value!='']").remove(); // keep first 
                    for (var i = 0; i < len; i++) {
                        var id = response[i]['baseIdentity']['id'];
                        var name = response[i]['name'];
                        $("#subtopicsId").append("<option value='" + id + "'>" + name + "</option>");
                    }
                },
                error: function (e) {
                    console.log("ERROR : ", e);
                }
        });
    }
}).change(); // and call it once defined

The initial call of change() makes sure it will be executed on page re-load or if a value has been preselected by some initialization in the backend.

BTW: I am using "manual" form validation (see "is-valid"/"is-invalid"), because I (and users) didn't like that BS4 marks non-required empty fields as green. But that's byond scope of this Q and if you are interested then I can post it also.

Why do I have to run "composer dump-autoload" command to make migrations work in laravel?

Short answer: classmaps are static while PSR autoloading is dynamic.

If you don't want to use classmaps, use PSR autoloading instead.

How to align an input tag to the center without specifying the width?

you can use this two simple line code :

_x000D_
_x000D_
    display: block;
    margin:auto;
_x000D_
_x000D_
_x000D_

RAW POST using cURL in PHP

I just found the solution, kind of answering to my own question in case anyone else stumbles upon it.

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL,            "http://url/url/url" );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_POST,           1 );
curl_setopt($ch, CURLOPT_POSTFIELDS,     "body goes here" ); 
curl_setopt($ch, CURLOPT_HTTPHEADER,     array('Content-Type: text/plain')); 

$result=curl_exec ($ch);

Can not run Java Applets in Internet Explorer 11 using JRE 7u51

  1. Go to Control panel.
  2. Double click on Java.
  3. Go to Security tab.
  4. Change security from high to medium.

Your applets will run.

If they are still not running then you have to add that website name in exception site list of Security tab of Java in Control panel.

Eclipse Java error: This selection cannot be launched and there are no recent launches

Check, you might have written this statement wrong.

public static void main(String Args[])

I have also just started java and was facing the same error and it was occuring as i didn't put [] after args. so check ur statment.

How to select the nth row in a SQL database table?

In Oracle 12c, You may use OFFSET..FETCH..ROWS option with ORDER BY

For example, to get the 3rd record from top:

SELECT * 
FROM   sometable
ORDER BY column_name
OFFSET 2 ROWS FETCH NEXT 1 ROWS ONLY;

How to make Java work with SQL Server?

The driver you are using is the MS SQL server 2008 driver (sqljdbc4.jar). As stated in the MSDN page it requires Java 6+ to work.

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

sqljdbc4.jar class library requires a Java Runtime Environment (JRE) of version 6.0 or later.

I'd suggest using the 2005 driver which I beleive is in (sqljdbc.jar) or as Oxbow_Lakes says try the jTDS driver (http://jtds.sourceforge.net/).

What is the correct "-moz-appearance" value to hide dropdown arrow of a <select> element

Update: this was fixed in Firefox v35. See the full gist for details.


== how to hide the select arrow in Firefox ==

Just figured out how to do it. The trick is to use a mix of -prefix-appearance, text-indent and text-overflow. It is pure CSS and requires no extra markup.

select {
    -moz-appearance: none;
    text-indent: 0.01px;
    text-overflow: '';
}

Long story short, by pushing it a tiny bit to the right, the overflow gets rid of the arrow. Pretty neat, huh?

More details on this gist I just wrote. Tested on Ubuntu, Mac and Windows, all with recent Firefox versions.

Compression/Decompression string with C#

I like @fubo's answer the best but I think this is much more elegant.

This method is more compatible because it doesn't manually store the length up front.

Also I've exposed extensions to support compression for string to string, byte[] to byte[], and Stream to Stream.

public static class ZipExtensions
{
    public static string CompressToBase64(this string data)
    {
        return Convert.ToBase64String(Encoding.UTF8.GetBytes(data).Compress());
    }

    public static string DecompressFromBase64(this string data)
    {
        return Encoding.UTF8.GetString(Convert.FromBase64String(data).Decompress());
    }
    
    public static byte[] Compress(this byte[] data)
    {
        using (var sourceStream = new MemoryStream(data))
        using (var destinationStream = new MemoryStream())
        {
            sourceStream.CompressTo(destinationStream);
            return destinationStream.ToArray();
        }
    }

    public static byte[] Decompress(this byte[] data)
    {
        using (var sourceStream = new MemoryStream(data))
        using (var destinationStream = new MemoryStream())
        {
            sourceStream.DecompressTo(destinationStream);
            return destinationStream.ToArray();
        }
    }
    
    public static void CompressTo(this Stream stream, Stream outputStream)
    {
        using (var gZipStream = new GZipStream(outputStream, CompressionMode.Compress))
        {
            stream.CopyTo(gZipStream);
            gZipStream.Flush();
        }
    }

    public static void DecompressTo(this Stream stream, Stream outputStream)
    {
        using (var gZipStream = new GZipStream(stream, CompressionMode.Decompress))
        {
            gZipStream.CopyTo(outputStream);
        }
    }
}

DataTables: Uncaught TypeError: Cannot read property 'defaults' of undefined

<script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"defer</script>

Add Defer to the end of your Script tag, it worked for me (;

Everything needs to be loaded in the correct order (:

Maintain aspect ratio of div but fill screen width and height in CSS?

My original question for this was how to both have an element of a fixed aspect, but to fit that within a specified container exactly, which makes it a little fiddly. If you simply want an individual element to maintain its aspect ratio it is a lot easier.

The best method I've come across is by giving an element zero height and then using percentage padding-bottom to give it height. Percentage padding is always proportional to the width of an element, and not its height, even if its top or bottom padding.

W3C Padding Properties

So utilising that you can give an element a percentage width to sit within a container, and then padding to specify the aspect ratio, or in other terms, the relationship between its width and height.

.object {
    width: 80%; /* whatever width here, can be fixed no of pixels etc. */
    height: 0px;
    padding-bottom: 56.25%;
}
.object .content {
    position: absolute;
    top: 0px;
    left: 0px;
    height: 100%;
    width: 100%;
    box-sizing: border-box;
    -moz-box-sizing: border-box;
    padding: 40px;
}

So in the above example the object takes 80% of the container width, and then its height is 56.25% of that value. If it's width was 160px then the bottom padding, and thus the height would be 90px - a 16:9 aspect.

The slight problem here, which may not be an issue for you, is that there is no natural space inside your new object. If you need to put some text in for example and that text needs to take it's own padding values you need to add a container inside and specify the properties in there.

Also vw and vh units aren't supported on some older browsers, so the accepted answer to my question might not be possible for you and you might have to use something more lo-fi.

"cannot be used as a function error"

#include "header.h"

int estimatedPopulation (int currentPopulation, float growthRate)
{
    return currentPopulation + currentPopulation * growthRate  / 100;
}

awk - concatenate two string variable and assign to a third

Concatenating strings in awk can be accomplished by the print command AWK manual page, and you can do complicated combination. Here I was trying to change the 16 char to A and used string concatenation:

echo    CTCTCTGAAATCACTGAGCAGGAGAAAGATT | awk -v w=15 -v BA=A '{OFS=""; print substr($0, 1, w), BA, substr($0,w+2)}'
Output: CTCTCTGAAATCACTAAGCAGGAGAAAGATT

I used the substr function to extract a portion of the input (STDIN). I passed some external parameters (here I am using hard-coded values) that are usually shell variable. In the context of shell programming, you can write -v w=$width -v BA=$my_charval. The key is the OFS which stands for Output Field Separate in awk. Print function take a list of values and write them to the STDOUT and glue them with the OFS. This is analogous to the perl join function.

It looks that in awk, string can be concatenated by printing variable next to each other:

echo xxx | awk -v a="aaa" -v b="bbb" '{ print a b $1 "string literal"}'
# will produce: aaabbbxxxstring literal

Get Absolute URL from Relative path (refactored method)

This has always been my approach to this little nuisance. Note the use of VirtualPathUtility.ToAbsolute(relativeUrl) allows the method to be declared as an extension in a static class.

/// <summary>
/// Converts the provided app-relative path into an absolute Url containing the 
/// full host name
/// </summary>
/// <param name="relativeUrl">App-Relative path</param>
/// <returns>Provided relativeUrl parameter as fully qualified Url</returns>
/// <example>~/path/to/foo to http://www.web.com/path/to/foo</example>
public static string ToAbsoluteUrl(this string relativeUrl) {
    if (string.IsNullOrEmpty(relativeUrl))
        return relativeUrl;

    if (HttpContext.Current == null)
        return relativeUrl;

    if (relativeUrl.StartsWith("/"))
        relativeUrl = relativeUrl.Insert(0, "~");
    if (!relativeUrl.StartsWith("~/"))
        relativeUrl = relativeUrl.Insert(0, "~/");

    var url = HttpContext.Current.Request.Url;
    var port = url.Port != 80 ? (":" + url.Port) : String.Empty;

    return String.Format("{0}://{1}{2}{3}",
        url.Scheme, url.Host, port, VirtualPathUtility.ToAbsolute(relativeUrl));
}

How to clear APC cache entries?

I know it's not for everyone but: why not to do a graceful Apache restart?

For e.g. in case of Centos/RedHat Linux:

sudo service httpd graceful

Ubuntu:

sudo service apache2 graceful

RuntimeWarning: invalid value encountered in divide

Python indexing starts at 0 (rather than 1), so your assignment "r[1,:] = r0" defines the second (i.e. index 1) element of r and leaves the first (index 0) element as a pair of zeros. The first value of i in your for loop is 0, so rr gets the square root of the dot product of the first entry in r with itself (which is 0), and the division by rr in the subsequent line throws the error.

Check file size before upload

Client side Upload Canceling

On modern browsers (FF >= 3.6, Chrome >= 19.0, Opera >= 12.0, and buggy on Safari), you can use the HTML5 File API. When the value of a file input changes, this API will allow you to check whether the file size is within your requirements. Of course, this, as well as MAX_FILE_SIZE, can be tampered with so always use server side validation.

<form method="post" enctype="multipart/form-data" action="upload.php">
    <input type="file" name="file" id="file" />
    <input type="submit" name="submit" value="Submit" />
</form>

<script>
document.forms[0].addEventListener('submit', function( evt ) {
    var file = document.getElementById('file').files[0];

    if(file && file.size < 10485760) { // 10 MB (this size is in bytes)
        //Submit form        
    } else {
        //Prevent default and display error
        evt.preventDefault();
    }
}, false);
</script>

Server Side Upload Canceling

On the server side, it is impossible to stop an upload from happening from PHP because once PHP has been invoked the upload has already completed. If you are trying to save bandwidth, you can deny uploads from the server side with the ini setting upload_max_filesize. The trouble with this is this applies to all uploads so you'll have to pick something liberal that works for all of your uploads. The use of MAX_FILE_SIZE has been discussed in other answers. I suggest reading the manual on it. Do know that it, along with anything else client side (including the javascript check), can be tampered with so you should always have server side (PHP) validation.

PHP Validation

On the server side you should validate that the file is within the size restrictions (because everything up to this point except for the INI setting could be tampered with). You can use the $_FILES array to find out the upload size. (Docs on the contents of $_FILES can be found below the MAX_FILE_SIZE docs)

upload.php

<?php
if(isset($_FILES['file'])) {
    if($_FILES['file']['size'] > 10485760) { //10 MB (size is also in bytes)
        // File too big
    } else {
        // File within size restrictions
    }
}

Can you do greater than comparison on a date in a Rails 3 search?

Note.
  where(:user_id => current_user.id, :notetype => p[:note_type]).
  where("date > ?", p[:date]).
  order('date ASC, created_at ASC')

or you can also convert everything into the SQL notation

Note.
  where("user_id = ? AND notetype = ? AND date > ?", current_user.id, p[:note_type], p[:date]).
  order('date ASC, created_at ASC')

Can't find SDK folder inside Android studio path, and SDK manager not opening

If you don't have it at C:\Users\%USERNAME%\AppData\Local\Android (this is where most people have it) than it is possible you don't have it installed. Go to Tools > Android > SDK Manager and then click on "Android SDK." On the top of the SDK Manager it will list the SDK Location. Click edit. If you don't have Android SDK installed, it will give you the option to install it in certain location. Install it, and Android Studio should work!

Is it safe to use Project Lombok?

I know I'm late, but I can't resist the temptation: anybody liking Lombok should also have a look at Scala. Many good ideas that you find in Lombok are part of the Scala language.

On your question: it's definitely easier to get your developers trying Lombok than Scala. Give it a try and if they like it, try Scala.

Just as a disclaimer: I like Java, too!

Assign format of DateTime with data annotations?

Apply DataAnnotation like:

[DisplayFormat(DataFormatString = "{0:MMM dd, yyyy}")]

Show Console in Windows Application?

Disclaimer

There is a way to achieve this which is quite simple, but I wouldn't suggest it is a good approach for an app you are going to let other people see. But if you had some developer need to show the console and windows forms at the same time, it can be done quite easily.

This method also supports showing only the Console window, but does not support showing only the Windows Form - i.e. the Console will always be shown. You can only interact (i.e. receive data - Console.ReadLine(), Console.Read()) with the console window if you do not show the windows forms; output to Console - Console.WriteLine() - works in both modes.

This is provided as is; no guarantees this won't do something horrible later on, but it does work.

Project steps

Start from a standard Console Application.

Mark the Main method as [STAThread]

Add a reference in your project to System.Windows.Forms

Add a Windows Form to your project.

Add the standard Windows start code to your Main method:

End Result

You will have an application that shows the Console and optionally windows forms.

Sample Code

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ConsoleApplication9 {
    class Program {

        [STAThread]
        static void Main(string[] args) {

            if (args.Length > 0 && args[0] == "console") {
                Console.WriteLine("Hello world!");
                Console.ReadLine();
            }
            else {
                Application.EnableVisualStyles(); 
                Application.SetCompatibleTextRenderingDefault(false); 
                Application.Run(new Form1());
            }
        }
    }
}

Form1.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ConsoleApplication9 {
    public partial class Form1 : Form {
        public Form1() {
            InitializeComponent();
        }

        private void Form1_Click(object sender, EventArgs e) {
            Console.WriteLine("Clicked");
        }
    }
}

"Expected BEGIN_OBJECT but was STRING at line 1 column 1"

I had a similar problem recently and found an interesting solution. Basically I needed to deserialize following nested JSON String into my POJO:

"{\"restaurant\":{\"id\":\"abc-012\",\"name\":\"good restaurant\",\"foodType\":\"American\",\"phoneNumber\":\"123-456-7890\",\"currency\":\"USD\",\"website\":\"website.com\",\"location\":{\"address\":{\"street\":\" Good Street\",\"city\":\"Good City\",\"state\":\"CA\",\"country\":\"USA\",\"postalCode\":\"12345\"},\"coordinates\":{\"latitude\":\"00.7904692\",\"longitude\":\"-000.4047208\"}},\"restaurantUser\":{\"firstName\":\"test\",\"lastName\":\"test\",\"email\":\"[email protected]\",\"title\":\"server\",\"phone\":\"0000000000\"}}}"

I ended up using regex to remove the open quotes from beginning and the end of JSON and then used apache.commons unescapeJava() method to unescape it. Basically passed the unclean JSON into following method to get back a cleansed one:

private String removeQuotesAndUnescape(String uncleanJson) {
    String noQuotes = uncleanJson.replaceAll("^\"|\"$", "");

    return StringEscapeUtils.unescapeJava(noQuotes);
}

then used Google GSON to parse it into my own Object:

MyObject myObject = new.Gson().fromJson(this.removeQuotesAndUnescape(uncleanJson));

How to repeat a char using printf?

#include <stdio.h>
#include <string.h>

void repeat_char(unsigned int cnt, char ch) {
    char buffer[cnt + 1];
    /*assuming you want to repeat the c character 30 times*/
    memset(buffer,ch,cnd); buffer[cnt]='\0';
    printf("%s",buffer)
}

How to overwrite the output directory in spark

The documentation for the parameter spark.files.overwrite says this: "Whether to overwrite files added through SparkContext.addFile() when the target file exists and its contents do not match those of the source." So it has no effect on saveAsTextFiles method.

You could do this before saving the file:

val hadoopConf = new org.apache.hadoop.conf.Configuration()
val hdfs = org.apache.hadoop.fs.FileSystem.get(new java.net.URI("hdfs://localhost:9000"), hadoopConf)
try { hdfs.delete(new org.apache.hadoop.fs.Path(filepath), true) } catch { case _ : Throwable => { } }

Aas explained here: http://apache-spark-user-list.1001560.n3.nabble.com/How-can-I-make-Spark-1-0-saveAsTextFile-to-overwrite-existing-file-td6696.html

Selecting default item from Combobox C#

this is the correct form:

comboBox1.Text = comboBox1.Items[0].ToString();

U r welcome

REST API - Use the "Accept: application/json" HTTP Header

Here's a handy site to test out your headers. You can see your browser headers and also use cURL to reflect back whatever headers you send.

For example, you can validate the content negotiation like this.

This Accept header prefers plain text so returns in that format:-

$ curl -H "Accept: application/json;q=0.9,text/plain" http://gethttp.info/Accept
application/json;q=0.9,text/plain

Whereas this one prefers JSON and so returns in that format:-

$ curl -H "Accept: application/json,text/*;q=0.99" http://gethttp.info/Accept
{
   "Accept": "application/json,text/*;q=0.99"
}

How to debug "ImagePullBackOff"?

I was facing the similar problem, but instead of one all of my pods were not ready and displaying Ready status 0/1 Something like enter image description here

I tried a lot of things but at last i found that the context was not correctly set. Please use following command and ensure you are in correct context

kubectl config get-contexts

How to resolve cURL Error (7): couldn't connect to host?

In my case I had something like cURL Error (7): ... Operation Timed Out. I'm using the network connection of the company I'm working for. I needed to create some environment variables. The next worked for me:

In Linux terminal:

$ export https_proxy=yourProxy:80
$ export http_proxy=yourProxy:80  

In windows I created (the same) environment variables in the windows way.

I hope it helps!

Regards!

Getting datarow values into a string?

Your rows object holds an Item attribute where you can find the values for each of your columns. You can not expect the columns to concatenate themselves when you do a .ToString() on the row. You should access each column from the row separately, use a for or a foreach to walk the array of columns.

Here, take a look at the class:

http://msdn.microsoft.com/en-us/library/system.data.datarow.aspx

Clear data in MySQL table with PHP?

TRUNCATE TABLE mytable

Be careful with it though.

JavaScript validation for empty input field

if(document.getElementById("question").value.length == 0)
{
    alert("empty")
}

How to have Java method return generic list of any type?

No need to even pass the class:

public <T> List<T> magicalListGetter() {
    return new ArrayList<T>();
}

Failing to run jar file from command line: “no main manifest attribute”

In Eclipse: right-click on your project -> Export -> JAR file

At last page with options (when there will be no Next button active) you will see settings for Main class:. You need to set here class with main method which should be executed by default (like when JAR file will be double-clicked).

ICommand MVVM implementation

I have written this article about the ICommand interface.

The idea - creating a universal command that takes two delegates: one is called when ICommand.Execute (object param) is invoked, the second checks the status of whether you can execute the command (ICommand.CanExecute (object param)).

Requires the method to switching event CanExecuteChanged. It is called from the user interface elements for switching the state CanExecute() command.

public class ModelCommand : ICommand
{
    #region Constructors

    public ModelCommand(Action<object> execute)
        : this(execute, null) { }

    public ModelCommand(Action<object> execute, Predicate<object> canExecute)
    {
        _execute = execute;
        _canExecute = canExecute;
    }

    #endregion

    #region ICommand Members

    public event EventHandler CanExecuteChanged;

    public bool CanExecute(object parameter)
    {
        return _canExecute != null ? _canExecute(parameter) : true;
    }

    public void Execute(object parameter)
    {
        if (_execute != null)
            _execute(parameter);
    }

    public void OnCanExecuteChanged()
    {
        CanExecuteChanged(this, EventArgs.Empty);
    }

    #endregion

    private readonly Action<object> _execute = null;
    private readonly Predicate<object> _canExecute = null;
}

How to commit to remote git repository

just type "git push" if this doesn't give you a positive replay, then check if you are connected with your repository correctly.

How do I make a new line in swift

You can do this

textView.text = "Name: \(string1) \n" + "Phone Number: \(string2)"

The output will be

Name: output of string1 Phone Number: output of string2

ngrok command not found

For Linux :https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-amd64.zip

For Mac :https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-darwin-amd64.zip

For Windows:https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-windows-amd64.zip

unzip it for linux and mac users move file to /usr/local/bin and execute ngrok http 80 command in the terminal

I don't have any idea about windows

How to crop a CvMat in OpenCV?

OpenCV has region of interest functions which you may find useful. If you are using the cv::Mat then you could use something like the following.

// You mention that you start with a CVMat* imagesource
CVMat * imagesource;

// Transform it into the C++ cv::Mat format
cv::Mat image(imagesource); 

// Setup a rectangle to define your region of interest
cv::Rect myROI(10, 10, 100, 100);

// Crop the full image to that image contained by the rectangle myROI
// Note that this doesn't copy the data
cv::Mat croppedImage = image(myROI);

Documentation for extracting sub image

How to bind Close command to a button

For .NET 4.5 SystemCommands class will do the trick (.NET 4.0 users can use WPF Shell Extension google - Microsoft.Windows.Shell or Nicholas Solution).

    <Window.CommandBindings>
        <CommandBinding Command="{x:Static SystemCommands.CloseWindowCommand}" 
                        CanExecute="CloseWindow_CanExec" 
                        Executed="CloseWindow_Exec" />
    </Window.CommandBindings>
    <!-- Binding Close Command to the button control -->
    <Button ToolTip="Close Window" Content="Close" Command="{x:Static SystemCommands.CloseWindowCommand}"/>

In the Code Behind you can implement the handlers like this:

    private void CloseWindow_CanExec(object sender, CanExecuteRoutedEventArgs e)
    {
        e.CanExecute = true;
    }

    private void CloseWindow_Exec(object sender, ExecutedRoutedEventArgs e)
    {
        SystemCommands.CloseWindow(this);
    }

Pandas index column title or name

The solution for multi-indexes is inside jezrael's cyclopedic answer, but it took me a while to find it so I am posting a new answer:

df.index.names gives the names of a multi-index (as a Frozenlist).

start/play embedded (iframe) youtube-video on click of an image

You can do this simply like this

$('#image_id').click(function() {
  $("#some_id iframe").attr('src', $("#some_id iframe", parent).attr('src') + '?autoplay=1'); 
});

where image_id is your image id you are clicking and some_id is id of div in which iframe is also you can use iframe id directly.

Display Last Saved Date on worksheet

This might be an alternative solution. Paste the following code into the new module:

Public Function ModDate()
ModDate = 
Format(FileDateTime(ThisWorkbook.FullName), "m/d/yy h:n ampm") 
End Function

Before saving your module, make sure to save your Excel file as Excel Macro-Enabled Workbook.

Paste the following code into the cell where you want to display the last modification time:

=ModDate()

I'd also like to recommend an alternative to Excel allowing you to add creation and last modification time easily. Feel free to check on RowShare and this article I wrote: https://www.rowshare.com/blog/en/2018/01/10/Displaying-Last-Modification-Time-in-Excel

Cannot download Docker images behind a proxy

On Ubuntu you need to set the http_proxy for the Docker daemon, not the client process. This is done in /etc/default/docker (see here).

PHP - Move a file into a different folder on the server

Use the rename() function.

rename("user/image1.jpg", "user/del/image1.jpg");

iPhone viewWillAppear not firing

ViewWillAppear is an override method of UIViewController class so adding a subView will not call viewWillAppear, but when you present, push , pop, show , setFront Or popToRootViewController from a viewController then viewWillAppear for presented viewController will get called.

How do I request a file but not save it with Wget?

You can use -O- (uppercase o) to redirect content to the stdout (standard output) or to a file (even special files like /dev/null /dev/stderr /dev/stdout )

wget -O- http://yourdomain.com

Or:

wget -O- http://yourdomain.com > /dev/null

Or: (same result as last command)

wget -O/dev/null http://yourdomain.com

Vue-router redirect on page not found (404)

@mani's Original answer is all you want, but if you'd also like to read it in official way, here's

Reference to Vue's official page:

https://router.vuejs.org/guide/essentials/history-mode.html#caveat

CSS Progress Circle

What about that?

HTML

<div class="chart" id="graph" data-percent="88"></div>

Javascript

var el = document.getElementById('graph'); // get canvas

var options = {
    percent:  el.getAttribute('data-percent') || 25,
    size: el.getAttribute('data-size') || 220,
    lineWidth: el.getAttribute('data-line') || 15,
    rotate: el.getAttribute('data-rotate') || 0
}

var canvas = document.createElement('canvas');
var span = document.createElement('span');
span.textContent = options.percent + '%';

if (typeof(G_vmlCanvasManager) !== 'undefined') {
    G_vmlCanvasManager.initElement(canvas);
}

var ctx = canvas.getContext('2d');
canvas.width = canvas.height = options.size;

el.appendChild(span);
el.appendChild(canvas);

ctx.translate(options.size / 2, options.size / 2); // change center
ctx.rotate((-1 / 2 + options.rotate / 180) * Math.PI); // rotate -90 deg

//imd = ctx.getImageData(0, 0, 240, 240);
var radius = (options.size - options.lineWidth) / 2;

var drawCircle = function(color, lineWidth, percent) {
        percent = Math.min(Math.max(0, percent || 1), 1);
        ctx.beginPath();
        ctx.arc(0, 0, radius, 0, Math.PI * 2 * percent, false);
        ctx.strokeStyle = color;
        ctx.lineCap = 'round'; // butt, round or square
        ctx.lineWidth = lineWidth
        ctx.stroke();
};

drawCircle('#efefef', options.lineWidth, 100 / 100);
drawCircle('#555555', options.lineWidth, options.percent / 100);

and CSS

div {
    position:relative;
    margin:80px;
    width:220px; height:220px;
}
canvas {
    display: block;
    position:absolute;
    top:0;
    left:0;
}
span {
    color:#555;
    display:block;
    line-height:220px;
    text-align:center;
    width:220px;
    font-family:sans-serif;
    font-size:40px;
    font-weight:100;
    margin-left:5px;
}

http://jsfiddle.net/Aapn8/3410/

Basic code was taken from Simple PIE Chart http://rendro.github.io/easy-pie-chart/

Secure hash and salt for PHP passwords

Google says SHA256 is available to PHP.

You should definitely use a salt. I'd recommend using random bytes (and not restrict yourself to characters and numbers). As usually, the longer you choose, the safer, slower it gets. 64 bytes ought to be fine, i guess.

In C#, what's the difference between \n and \r\n?

\n is Unix, \r is Mac, \r\n is Windows.

Sometimes it's giving trouble especially when running code cross platform. You can bypass this by using Environment.NewLine.

Please refer to What is the difference between \r, \n and \r\n ?! for more information. Happy reading

Why do I have to "git push --set-upstream origin <branch>"?

If you forgot to add the repository HTTPS link then put it with git push <repo HTTPS>

how to update the multiple rows at a time using linq to sql?

To update one column here are some syntax options:

Option 1

var ls=new int[]{2,3,4};
using (var db=new SomeDatabaseContext())
{
    var some= db.SomeTable.Where(x=>ls.Contains(x.friendid)).ToList();
    some.ForEach(a=>a.status=true);
    db.SubmitChanges();
}

Option 2

using (var db=new SomeDatabaseContext())
{
     db.SomeTable
       .Where(x=>ls.Contains(x.friendid))
       .ToList()
       .ForEach(a=>a.status=true);

     db.SubmitChanges();
}

Option 3

using (var db=new SomeDatabaseContext())
{
    foreach (var some in db.SomeTable.Where(x=>ls.Contains(x.friendid)).ToList())
    {
        some.status=true;
    }
    db.SubmitChanges();
}

Update

As requested in the comment it might make sense to show how to update multiple columns. So let's say for the purpose of this exercise that we want not just to update the status at ones. We want to update name and status where the friendid is matching. Here are some syntax options for that:

Option 1

var ls=new int[]{2,3,4};
var name="Foo";
using (var db=new SomeDatabaseContext())
{
    var some= db.SomeTable.Where(x=>ls.Contains(x.friendid)).ToList();
    some.ForEach(a=>
                    {
                        a.status=true;
                        a.name=name;
                    }
                );
    db.SubmitChanges();
}

Option 2

using (var db=new SomeDatabaseContext())
{
    db.SomeTable
        .Where(x=>ls.Contains(x.friendid))
        .ToList()
        .ForEach(a=>
                    {
                        a.status=true;
                        a.name=name;
                    }
                );
    db.SubmitChanges();
}

Option 3

using (var db=new SomeDatabaseContext())
{
    foreach (var some in db.SomeTable.Where(x=>ls.Contains(x.friendid)).ToList())
    {
        some.status=true;
        some.name=name;
    }
    db.SubmitChanges();
}

Update 2

In the answer I was using LINQ to SQL and in that case to commit to the database the usage is:

db.SubmitChanges();

But for Entity Framework to commit the changes it is:

db.SaveChanges()

Fixing npm path in Windows 8 and 10

I have used the cmdlet and navigate to the path you want to switch your npm files to. Type in npm root -g to see what the current path your npm is installed to. Next use npm config set prefix and your npm path will be changed to whatever directory you are currently on.

How to set environment via `ng serve` in Angular 6

Use this command for Angular 6 to build

ng build --prod --configuration=dev

How to dynamic new Anonymous Class?

Anonymous types are just regular types that are implicitly declared. They have little to do with dynamic.

Now, if you were to use an ExpandoObject and reference it through a dynamic variable, you could add or remove fields on the fly.

edit

Sure you can: just cast it to IDictionary<string, object>. Then you can use the indexer.

You use the same casting technique to iterate over the fields:

dynamic employee = new ExpandoObject();
employee.Name = "John Smith";
employee.Age = 33;

foreach (var property in (IDictionary<string, object>)employee)
{
    Console.WriteLine(property.Key + ": " + property.Value);
}
// This code example produces the following output:
// Name: John Smith
// Age: 33

The above code and more can be found by clicking on that link.

Print PDF directly from JavaScript

you can download the pdf file using fetch, and print it with print.js

                          fetch("url")
                            .then(function (response) {

                                response.blob().then(function (blob) {
                                    var reader = new FileReader();
                                    reader.onload = function () {

                                        //Remove the data:application/pdf;base64,
                                        printJS({
                                            printable: reader.result.substring(28),
                                            type: 'pdf',
                                            base64: true
                                        });
                                    };
                                    reader.readAsDataURL(blob);
                                })
                            });

Mockito - NullpointerException when stubbing Method

None of these answers worked for me. This answer doesn't solve OP's issue but since this post is the only one that shows up on googling this issue, I'm sharing my answer here.

I came across this issue while writing unit tests for Android. The issue was that the activity that I was testing extended AppCompatActivity instead of Activity. To fix this, I was able to just replace AppCompatActivity with Activity since I didn't really need it. This might not be a viable solution for everyone, but hopefully knowing the root cause will help someone.

How to reposition Chrome Developer Tools

If you use Windows, there some shortcuts, while devtools are opened:

Pressing Ctrl+Shift+D will dock all devtools to left, right, bottom in turn.

Press Ctrl+Shift+F if your JS console disappeared, and you want it docked back to bottom within dev tools.

Pagination using MySQL LIMIT, OFFSET

A dozen pages is not a big deal when using OFFSET. But when you have hundreds of pages, you will find that OFFSET is bad for performance. This is because all the skipped rows need to be read each time.

It is better to remember where you left off.

numpy array TypeError: only integer scalar arrays can be converted to a scalar index

I ran into the problem when venturing to use numpy.concatenate to emulate a C++ like pushback for 2D-vectors; If A and B are two 2D numpy.arrays, then numpy.concatenate(A,B) yields the error.

The fix was to simply to add the missing brackets: numpy.concatenate( ( A,B ) ), which are required because the arrays to be concatenated constitute to a single argument

multiple packages in context:component-scan, spring config

You can add multiple base packages (see axtavt's answer), but you can also filter what's scanned inside the base package:

<context:component-scan base-package="x.y.z">
   <context:include-filter type="regex" expression="(service|controller)\..*"/>
</context:component-scan>

Username and password in command for git push

It is possible but, before git 2.9.3 (august 2016), a git push would print the full url used when pushing back to the cloned repo.
That would include your username and password!

But no more: See commit 68f3c07 (20 Jul 2016), and commit 882d49c (14 Jul 2016) by Jeff King (peff).
(Merged by Junio C Hamano -- gitster -- in commit 71076e1, 08 Aug 2016)

push: anonymize URL in status output

Commit 47abd85 (fetch: Strip usernames from url's before storing them, 2009-04-17, Git 1.6.4) taught fetch to anonymize URLs.
The primary purpose there was to avoid sticking passwords in merge-commit messages, but as a side effect, we also avoid printing them to stderr.

The push side does not have the merge-commit problem, but it probably should avoid printing them to stderr. We can reuse the same anonymizing function.

Note that for this to come up, the credentials would have to appear either on the command line or in a git config file, neither of which is particularly secure.
So people should be switching to using credential helpers instead, which makes this problem go away.

But that's no excuse not to improve the situation for people who for whatever reason end up using credentials embedded in the URL.

Using Linq select list inside list

After my previous answer disaster, I'm going to try something else.

List<Model> usrList  = 
(list.Where(n => n.application == "applicationame").ToList());
usrList.ForEach(n => n.users.RemoveAll(n => n.surname != "surname"));

Calculating bits required to store decimal number

Assuming that the question is asking what's the minimum bits required for you to store

  1. 3 digits number

My approach to this question would be:

  • what's the maximum number of 3 digits number we need to store? Ans: 999
  • what's the minimum amount of bits required for me to store this number?

This problem can be solved this way by dividing 999 by 2 recursively. However, it's simpler to use the power of maths to help us. Essentially, we're solving n for the equation below:

2^n = 999
nlog2 = log999
n ~ 10

You'll need 10 bits to store 3 digit number.

Use similar approach to solve the other subquestions!

Hope this helps!

How to declare variable and use it in the same Oracle SQL script?

There are a several ways of declaring variables in SQL*Plus scripts.

The first is to use VAR, to declare a bind variable. The mechanism for assigning values to a VAR is with an EXEC call:

SQL> var name varchar2(20)
SQL> exec :name := 'SALES'

PL/SQL procedure successfully completed.

SQL> select * from dept
  2  where dname = :name
  3  /

    DEPTNO DNAME          LOC
---------- -------------- -------------
        30 SALES          CHICAGO

SQL>

A VAR is particularly useful when we want to call a stored procedure which has OUT parameters or a function.

Alternatively we can use substitution variables. These are good for interactive mode:

SQL> accept p_dno prompt "Please enter Department number: " default 10
Please enter Department number: 20
SQL> select ename, sal
  2  from emp
  3  where deptno = &p_dno
  4  /
old   3: where deptno = &p_dno
new   3: where deptno = 20

ENAME             SAL
---------- ----------
CLARKE            800
ROBERTSON        2975
RIGBY            3000
KULASH           1100
GASPAROTTO       3000

SQL>

When we're writing a script which calls other scripts it can be useful to DEFine the variables upfront. This snippet runs without prompting me to enter a value:

SQL> def p_dno = 40
SQL> select ename, sal
  2  from emp
  3  where deptno = &p_dno
  4  /
old   3: where deptno = &p_dno
new   3: where deptno = 40

no rows selected

SQL>

Finally there's the anonymous PL/SQL block. As you see, we can still assign values to declared variables interactively:

SQL> set serveroutput on size unlimited
SQL> declare
  2      n pls_integer;
  3      l_sal number := 3500;
  4      l_dno number := &dno;
  5  begin
  6      select count(*)
  7      into n
  8      from emp
  9      where sal > l_sal
 10      and deptno = l_dno;
 11      dbms_output.put_line('top earners = '||to_char(n));
 12  end;
 13  /
Enter value for dno: 10
old   4:     l_dno number := &dno;
new   4:     l_dno number := 10;
top earners = 1

PL/SQL procedure successfully completed.

SQL>

window.onunload is not working properly in Chrome browser. Can any one help me?

Armin's answer is so useful, thank you. #2 is what's most important to know when trying to set up unload events that work in most browsers: you cannot alert() or confirm(), but returning a string will generate a confirm modal.

But I found that even with just returning a string, I had some cross-browser issues specific to Mootools (using version 1.4.5 in this instance). This Mootools-specific implementation worked great in Firefox, but did not result in a confirm popup in Chrome or Safari:

window.addEvent("beforeunload", function() {
    return "Are you sure you want to leave this page?";
});

So in order to get my onbeforeonload event to work across browsers, I had to use the JavaScript native call:

window.onbeforeunload = function() {
    return "Are you sure you want to leave this page?";
}

Not sure why this is the case, or if it's been fixed in later versions of Mootools.

How to find which columns contain any NaN value in Pandas dataframe

UPDATE: using Pandas 0.22.0

Newer Pandas versions have new methods 'DataFrame.isna()' and 'DataFrame.notna()'

In [71]: df
Out[71]:
     a    b  c
0  NaN  7.0  0
1  0.0  NaN  4
2  2.0  NaN  4
3  1.0  7.0  0
4  1.0  3.0  9
5  7.0  4.0  9
6  2.0  6.0  9
7  9.0  6.0  4
8  3.0  0.0  9
9  9.0  0.0  1

In [72]: df.isna().any()
Out[72]:
a     True
b     True
c    False
dtype: bool

as list of columns:

In [74]: df.columns[df.isna().any()].tolist()
Out[74]: ['a', 'b']

to select those columns (containing at least one NaN value):

In [73]: df.loc[:, df.isna().any()]
Out[73]:
     a    b
0  NaN  7.0
1  0.0  NaN
2  2.0  NaN
3  1.0  7.0
4  1.0  3.0
5  7.0  4.0
6  2.0  6.0
7  9.0  6.0
8  3.0  0.0
9  9.0  0.0

OLD answer:

Try to use isnull():

In [97]: df
Out[97]:
     a    b  c
0  NaN  7.0  0
1  0.0  NaN  4
2  2.0  NaN  4
3  1.0  7.0  0
4  1.0  3.0  9
5  7.0  4.0  9
6  2.0  6.0  9
7  9.0  6.0  4
8  3.0  0.0  9
9  9.0  0.0  1

In [98]: pd.isnull(df).sum() > 0
Out[98]:
a     True
b     True
c    False
dtype: bool

or as @root proposed clearer version:

In [5]: df.isnull().any()
Out[5]:
a     True
b     True
c    False
dtype: bool

In [7]: df.columns[df.isnull().any()].tolist()
Out[7]: ['a', 'b']

to select a subset - all columns containing at least one NaN value:

In [31]: df.loc[:, df.isnull().any()]
Out[31]:
     a    b
0  NaN  7.0
1  0.0  NaN
2  2.0  NaN
3  1.0  7.0
4  1.0  3.0
5  7.0  4.0
6  2.0  6.0
7  9.0  6.0
8  3.0  0.0
9  9.0  0.0

Clear icon inside input text

I've created a clearable textbox in just CSS. It requires no javascript code to make it work

below is the demo link

http://codepen.io/shidhincr/pen/ICLBD

Current date and time - Default in MVC razor

Before you return your model from the controller, set your ReturnDate property to DateTime.Now()

myModel.ReturnDate = DateTime.Now()

return View(myModel)

Your view is not the right place to set values on properties so the controller is the better place for this.

You could even have it so that the getter on ReturnDate returns the current date/time.

private DateTime _returnDate = DateTime.MinValue;
public DateTime ReturnDate{
   get{
     return (_returnDate == DateTime.MinValue)? DateTime.Now() : _returnDate;
   }
   set{_returnDate = value;}
}

How to select where ID in Array Rails ActiveRecord without exception

You can also use it in named_scope if You want to put there others conditions

for example include some other model:

named_scope 'get_by_ids', lambda { |ids| { :include => [:comments], :conditions => ["comments.id IN (?)", ids] } }

What is the best way to know if all the variables in a Class are null?

"Best" is such a subjective term :-)

I would just use the method of checking each individual variable. If your class already has a lot of these, the increase in size is not going to be that much if you do something like:

public Boolean anyUnset() {
    if (  id == null) return true;
    if (name == null) return true;
    return false;
}

Provided you keep everything in the same order, code changes (and automated checking with a script if you're paranoid) will be relatively painless.

Alternatively (assuming they're all strings), you could basically put these values into a map of some sort (eg, HashMap) and just keep a list of the key names for that list. That way, you could iterate through the list of keys, checking that the values are set correctly.

Run Executable from Powershell script with parameters

Here is an alternative method for doing multiple args. I use it when the arguments are too long for a one liner.

$app = 'C:\Program Files\MSBuild\test.exe'
$arg1 = '/genmsi'
$arg2 = '/f'
$arg3 = '$MySourceDirectory\src\Deployment\Installations.xml'

& $app $arg1 $arg2 $arg3

Custom designing EditText

android:background="#E1E1E1" 
// background add in layout
<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="#ffffff">
</EditText>

Access blocked by CORS policy: Response to preflight request doesn't pass access control check

CORS headers should be sent from the server. If you use PHP it will be like this:

header('Access-Control-Allow-Origin: your-host');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Methods: your-methods like POST,GET');
header('Access-Control-Allow-Headers: content-type or other');
header('Content-Type: application/json');

Import-CSV and Foreach

You can create the headers on the fly (no need to specify delimiter when the delimiter is a comma):

Import-CSV $filepath -Header IP1,IP2,IP3,IP4 | Foreach-Object{
   Write-Host $_.IP1
   Write-Host $_.IP2
   ...
}

What's the difference between & and && in MATLAB?

Both are logical AND operations. The && though, is a "short-circuit" operator. From the MATLAB docs:

They are short-circuit operators in that they evaluate their second operand only when the result is not fully determined by the first operand.

See more here.

RegEx match open tags except XHTML self-contained tags

Here's the solution:

<?php
// here's the pattern:
$pattern = '/<(\w+)(\s+(\w+)\s*\=\s*(\'|")(.*?)\\4\s*)*\s*(\/>|>)/';

// a string to parse:
$string = 'Hello, try clicking <a href="#paragraph">here</a>
    <br/>and check out.<hr />
    <h2>title</h2>
    <a name ="paragraph" rel= "I\'m an anchor"></a>
    Fine, <span title=\'highlight the "punch"\'>thanks<span>.
    <div class = "clear"></div>
    <br>';

// let's get the occurrences:
preg_match_all($pattern, $string, $matches, PREG_PATTERN_ORDER);

// print the result:
print_r($matches[0]);
?>

To test it deeply, I entered in the string auto-closing tags like:

  1. <hr />
  2. <br/>
  3. <br>

I also entered tags with:

  1. one attribute
  2. more than one attribute
  3. attributes which value is bound either into single quotes or into double quotes
  4. attributes containing single quotes when the delimiter is a double quote and vice versa
  5. "unpretty" attributes with a space before the "=" symbol, after it and both before and after it.

Should you find something which does not work in the proof of concept above, I am available in analyzing the code to improve my skills.

<EDIT> I forgot that the question from the user was to avoid the parsing of self-closing tags. In this case the pattern is simpler, turning into this:

$pattern = '/<(\w+)(\s+(\w+)\s*\=\s*(\'|")(.*?)\\4\s*)*\s*>/';

The user @ridgerunner noticed that the pattern does not allow unquoted attributes or attributes with no value. In this case a fine tuning brings us the following pattern:

$pattern = '/<(\w+)(\s+(\w+)(\s*\=\s*(\'|"|)(.*?)\\5\s*)?)*\s*>/';

</EDIT>

Understanding the pattern

If someone is interested in learning more about the pattern, I provide some line:

  1. the first sub-expression (\w+) matches the tag name
  2. the second sub-expression contains the pattern of an attribute. It is composed by:
    1. one or more whitespaces \s+
    2. the name of the attribute (\w+)
    3. zero or more whitespaces \s* (it is possible or not, leaving blanks here)
    4. the "=" symbol
    5. again, zero or more whitespaces
    6. the delimiter of the attribute value, a single or double quote ('|"). In the pattern, the single quote is escaped because it coincides with the PHP string delimiter. This sub-expression is captured with the parentheses so it can be referenced again to parse the closure of the attribute, that's why it is very important.
    7. the value of the attribute, matched by almost anything: (.*?); in this specific syntax, using the greedy match (the question mark after the asterisk) the RegExp engine enables a "look-ahead"-like operator, which matches anything but what follows this sub-expression
    8. here comes the fun: the \4 part is a backreference operator, which refers to a sub-expression defined before in the pattern, in this case, I am referring to the fourth sub-expression, which is the first attribute delimiter found
    9. zero or more whitespaces \s*
    10. the attribute sub-expression ends here, with the specification of zero or more possible occurrences, given by the asterisk.
  3. Then, since a tag may end with a whitespace before the ">" symbol, zero or more whitespaces are matched with the \s* subpattern.
  4. The tag to match may end with a simple ">" symbol, or a possible XHTML closure, which makes use of the slash before it: (/>|>). The slash is, of course, escaped since it coincides with the regular expression delimiter.

Small tip: to better analyze this code it is necessary looking at the source code generated since I did not provide any HTML special characters escaping.

JavaScript: Get image dimensions

Get image size with jQuery

function getMeta(url){
    $("<img/>",{
        load : function(){
            alert(this.width+' '+this.height);
        },
        src  : url
    });
}

Get image size with JavaScript

function getMeta(url){   
    var img = new Image();
    img.onload = function(){
        alert( this.width+' '+ this.height );
    };
    img.src = url;
}

Get image size with JavaScript (modern browsers, IE9+ )

function getMeta(url){   
    var img = new Image();
    img.addEventListener("load", function(){
        alert( this.naturalWidth +' '+ this.naturalHeight );
    });
    img.src = url;
}

Use the above simply as: getMeta( "http://example.com/img.jpg" );

https://developer.mozilla.org/en/docs/Web/API/HTMLImageElement

check if jquery has been loaded, then load it if false

Method 1:

if (window.jQuery) {  
    // jQuery is loaded  
} else {
    // jQuery is not loaded
}

Method 2:

if (typeof jQuery == 'undefined') {  
    // jQuery is not loaded
} else {
    // jQuery is loaded
}

If jquery.js file is not loaded, we can force load it like so:

if (!window.jQuery) {
  var jq = document.createElement('script'); jq.type = 'text/javascript';
  // Path to jquery.js file, eg. Google hosted version
  jq.src = '/path-to-your/jquery.min.js';
  document.getElementsByTagName('head')[0].appendChild(jq);
}

Android AlertDialog Single Button

Its very simple

new AlertDialog.Builder(this).setView(input).setPositiveButton("ENTER",            
                        new DialogInterface.OnClickListener()                      
                        {   public void onClick(DialogInterface di,int id)     
                            {
                                output.setText(input.getText().toString());
                            }
                        }
                     )
        .create().show();

In case you wish to read the full program see here: Program to take input from user using dialog and output to screen

How do I update a Python package?

pip install -U $(pip list --outdated | awk 'NR>2 {print $1}')

HTML: Select multiple as dropdown

Here is the documentation of <select>. You are using 2 attributes:

multiple
This Boolean attribute indicates that multiple options can be selected in the list. If it is not specified, then only one option can be selected at a time. When multiple is specified, most browsers will show a scrolling list box instead of a single line dropdown.

size
If the control is presented as a scrolling list box (e.g. when multiple is specified), this attribute represents the number of rows in the list that should be visible at one time. Browsers are not required to present a select element as a scrolled list box. The default value is 0.

As described in the docs. <select size="1" multiple> will render a List box only 1 line visible and a scrollbar. So you are loosing the dropdown/arrow with the multiple attribute.

How the single threaded non blocking IO model works in Node.js

Well, to give some perspective, let me compare node.js with apache.

Apache is a multi-threaded HTTP server, for each and every request that the server receives, it creates a separate thread which handles that request.

Node.js on the other hand is event driven, handling all requests asynchronously from single thread.

When A and B are received on apache, two threads are created which handle requests. Each handling the query separately, each waiting for the query results before serving the page. The page is only served until the query is finished. The query fetch is blocking because the server cannot execute the rest of thread until it receives the result.

In node, c.query is handled asynchronously, which means while c.query fetches the results for A, it jumps to handle c.query for B, and when the results arrive for A arrive it sends back the results to callback which sends the response. Node.js knows to execute callback when fetch finishes.

In my opinion, because it's a single thread model, there is no way to switch from one request to another.

Actually the node server does exactly that for you all the time. To make switches, (the asynchronous behavior) most functions that you would use will have callbacks.

Edit

The SQL query is taken from mysql library. It implements callback style as well as event emitter to queue SQL requests. It does not execute them asynchronously, that is done by the internal libuv threads that provide the abstraction of non-blocking I/O. The following steps happen for making a query :

  1. Open a connection to db, connection itself can be made asynchronously.
  2. Once db is connected, query is passed on to the server. Queries can be queued.
  3. The main event loop gets notified of the completion with callback or event.
  4. Main loop executes your callback/eventhandler.

The incoming requests to http server are handled in the similar fashion. The internal thread architecture is something like this:

node.js event loop

The C++ threads are the libuv ones which do the asynchronous I/O (disk or network). The main event loop continues to execute after the dispatching the request to thread pool. It can accept more requests as it does not wait or sleep. SQL queries/HTTP requests/file system reads all happen this way.

How do I create a timeline chart which shows multiple events? Eg. Metallica Band members timeline on wiki

As mentioned in the earlier comment, stacked bar chart does the trick, though the data needs to be setup differently.(See image below)

Duration column = End - Start

  1. Once done, plot your stacked bar chart using the entire data.
  2. Mark start and end range to no fill.
  3. Right click on the X Axis and change Axis options manually. (This did cause me some issues, till I realized I couldn't manipulate them to enter dates, :) yeah I am newbie, excel masters! :))

enter image description here

Converting time stamps in excel to dates

If you get a Error 509 in Libre office you may replace , by ; in the DATE() function

=(((COLUMN_ID_HERE/60)/60)/24)+DATE(1970;1;1)

What exactly is Spring Framework for?

Spring framework is definitely good for web development and to be more specific for restful api services.

It is good for the above because of its dependency injection and integration with other modules like spring security, spring aop, mvc framework, microservices

With in any application, security is most probably a requirement.
If you aim to build a product that needs long maintenance, then you will need the utilize the Aop concept.

If your application has to much traffic thus increasing the load, you need to use the microservices concept.

Spring is giving all these features in one platform. Support with many modules.
Most importantly, spring is open source and an extensible framework,have a hook everywhere to integrate custom code in life cycle.

Spring Data is one project which provides integration with your project.


So spring can fit into almost every requirement.

How do I make a <div> move up and down when I'm scrolling the page?

using position:fixed alone is just fine when you don't have a header or logo at the top of your page. This solution will take into account the how far the window has scrolled, and moves the div when you scrolled past your header. It will then lock it back into place when you get to the top again.

if($(window).scrollTop() > Height_of_Header){
    //begin to scroll
    $("#div").css("position","fixed");
    $("#div").css("top",0);
}
else{
    //lock it back into place
    $("#div").css("position","relative");
}

Cannot open Windows.h in Microsoft Visual Studio

1) Go to C:\Program Files (x86)\Microsoft SDKs\Windows\v7.1A for VS2013

2) Copy the folders Include and Lib (you should check where are your folders in folder windows such as v7.1, v8, v6, etc.)

3) Paste them into C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC

I solved my problems like:

error lnk1104: cannot open file 'kernel32.lib'.
error c1083: Cannot open Windows.h

Thanks.

Catch checked change event of a checkbox

In my experience, I've had to leverage the event's currentTarget:

$("#dingus").click( function (event) {
   if ($(event.currentTarget).is(':checked')) {
     //checkbox is checked
   }
});

INSERT INTO a temp table, and have an IDENTITY field created, without first declaring the temp table?

Good Question & Matt's was a good answer. To expand on the syntax a little if the oldtable has an identity a user could run the following:

SELECT col1, col2, IDENTITY( int ) AS idcol
INTO #newtable
FROM oldtable

That would be if the oldtable was scripted something as such:

CREATE TABLE [dbo].[oldtable]
(
    [oldtableID] [numeric](18, 0) IDENTITY(1,1) NOT NULL,
    [col1] [nvarchar](50) NULL,
    [col2] [numeric](18, 0) NULL,
)

How do I programmatically force an onchange event on an input?

In jQuery I mostly use:

$("#element").trigger("change");

Check if a value is within a range of numbers

You're asking a question about numeric comparisons, so regular expressions really have nothing to do with the issue. You don't need "multiple if" statements to do it, either:

if (x >= 0.001 && x <= 0.009) {
  // something
}

You could write yourself a "between()" function:

function between(x, min, max) {
  return x >= min && x <= max;
}
// ...
if (between(x, 0.001, 0.009)) {
  // something
}

How do I escape double quotes in attributes in an XML String in T-SQL?

Cannot comment anymore but voted it up and wanted to let folks know that &quot; works very well for the xml config files when forming regex expressions for RegexTransformer in Solr like so: regex=".*img src=&quot;(.*)&quot;.*" using the escaped version instead of double-quotes.

Angular 2 - View not updating after model changes

It might be that the code in your service somehow breaks out of Angular's zone. This breaks change detection. This should work:

import {Component, OnInit, NgZone} from 'angular2/core';

export class RecentDetectionComponent implements OnInit {

    recentDetections: Array<RecentDetection>;

    constructor(private zone:NgZone, // <== added
        private recentDetectionService: RecentDetectionService) {
        this.recentDetections = new Array<RecentDetection>();
    }

    getRecentDetections(): void {
        this.recentDetectionService.getJsonFromApi()
            .subscribe(recent => { 
                 this.zone.run(() => { // <== added
                     this.recentDetections = recent;
                     console.log(this.recentDetections[0].macAddress) 
                 });
        });
    }

    ngOnInit() {
        this.getRecentDetections();
        let timer = Observable.timer(2000, 5000);
        timer.subscribe(() => this.getRecentDetections());
    }
}

For other ways to invoke change detection see Triggering change detection manually in Angular

Alternative ways to invoke change detection are

ChangeDetectorRef.detectChanges()

to immediately run change detection for the current component and its children

ChangeDetectorRef.markForCheck()

to include the current component the next time Angular runs change detection

ApplicationRef.tick()

to run change detection for the whole application

Multiple line code example in Javadoc comment

I had a really tough time with including a specific code example in a javadoc comment. I'd like to share this one.
Please note the following:

  • usage of old <code> - tag to prevent the curly brackets from being interpreted
  • usage of "new" {@code ...} - tag to get the generics included in the output
  • escaping of the @ sign in @Override via "{@literal @}Override" because javadoc generator "tilts" there due to the fact that the @ goes directly after an opening curly bracket
  • remove one space in front of {@code and {@literal, to compensate inner spaces and keep the alignment

javadoc code:

/** this methods adds a specific translator from one type to another type. `
  * i.e.
  * <pre>
  * <code>new BeanTranslator.Builder()
  *   .translate(
  *     new{@code Translator<String, Integer>}(String.class, Integer.class){
  *      {@literal @}Override
  *       public Integer translate(String instance) {
  *         return Integer.valueOf(instance);
  *       }})
  *   .build();
  * </code>
  * </pre>
  * @param translator
  */

gets printed as

new BeanTranslator.Builder()
  .translate(
    new Translator<String, Integer>(String.class, Integer.class){
      @Override
      public Integer translate(String instance) {
        return Integer.valueOf(instance);
      }})
  .build();

minimize app to system tray

this.WindowState = FormWindowState.Minimized;

performing HTTP requests with cURL (using PROXY)

From man curl:

-x, --proxy <[protocol://][user:password@]proxyhost[:port]>

     Use the specified HTTP proxy. 
     If the port number is not specified, it is assumed at port 1080.

General way:

export http_proxy=http://your.proxy.server:port/

Then you can connect through proxy from (many) application.

And, as per comment below, for https:

export https_proxy=https://your.proxy.server:port/

SQLAlchemy: print the actual query

This code is based on brilliant existing answer from @bukzor. I just added custom render for datetime.datetime type into Oracle's TO_DATE().

Feel free to update code to suit your database:

import decimal
import datetime

def printquery(statement, bind=None):
    """
    print a query, with values filled in
    for debugging purposes *only*
    for security, you should always separate queries from their values
    please also note that this function is quite slow
    """
    import sqlalchemy.orm
    if isinstance(statement, sqlalchemy.orm.Query):
        if bind is None:
            bind = statement.session.get_bind(
                    statement._mapper_zero_or_none()
            )
        statement = statement.statement
    elif bind is None:
        bind = statement.bind 

    dialect = bind.dialect
    compiler = statement._compiler(dialect)
    class LiteralCompiler(compiler.__class__):
        def visit_bindparam(
                self, bindparam, within_columns_clause=False, 
                literal_binds=False, **kwargs
        ):
            return super(LiteralCompiler, self).render_literal_bindparam(
                    bindparam, within_columns_clause=within_columns_clause,
                    literal_binds=literal_binds, **kwargs
            )
        def render_literal_value(self, value, type_):
            """Render the value of a bind parameter as a quoted literal.

            This is used for statement sections that do not accept bind paramters
            on the target driver/database.

            This should be implemented by subclasses using the quoting services
            of the DBAPI.

            """
            if isinstance(value, basestring):
                value = value.replace("'", "''")
                return "'%s'" % value
            elif value is None:
                return "NULL"
            elif isinstance(value, (float, int, long)):
                return repr(value)
            elif isinstance(value, decimal.Decimal):
                return str(value)
            elif isinstance(value, datetime.datetime):
                return "TO_DATE('%s','YYYY-MM-DD HH24:MI:SS')" % value.strftime("%Y-%m-%d %H:%M:%S")

            else:
                raise NotImplementedError(
                            "Don't know how to literal-quote value %r" % value)            

    compiler = LiteralCompiler(dialect, statement)
    print compiler.process(statement)

What jsf component can render a div tag?

In JSF 2.2 it's possible to use passthrough elements:

<html xmlns="http://www.w3.org/1999/xhtml"
  xmlns:jsf="http://xmlns.jcp.org/jsf">
    ...
    <div jsf:id="id1" />
    ...
</html>

The requirement is to have at least one attribute in the element using jsf namespace.

Django return redirect() with parameters

Firstly, your URL definition does not accept any parameters at all. If you want parameters to be passed from the URL into the view, you need to define them in the urlconf.

Secondly, it's not at all clear what you are expecting to happen to the cleaned_data dictionary. Don't forget you can't redirect to a POST - this is a limitation of HTTP, not Django - so your cleaned_data either needs to be a URL parameter (horrible) or, slightly better, a series of GET parameters - so the URL would be in the form:

/link/mybackend/?field1=value1&field2=value2&field3=value3

and so on. In this case, field1, field2 and field3 are not included in the URLconf definition - they are available in the view via request.GET.

So your urlconf would be:

url(r'^link/(?P<backend>\w+?)/$', my_function)

and the view would look like:

def my_function(request, backend):
   data = request.GET

and the reverse would be (after importing urllib):

return "%s?%s" % (redirect('my_function', args=(backend,)),
                  urllib.urlencode(form.cleaned_data))

Edited after comment

The whole point of using redirect and reverse, as you have been doing, is that you go to the URL - it returns an Http code that causes the browser to redirect to the new URL, and call that.

If you simply want to call the view from within your code, just do it directly - no need to use reverse at all.

That said, if all you want to do is store the data, then just put it in the session:

request.session['temp_data'] = form.cleaned_data

Extending an Object in Javascript

You can simply do it by using:

Object.prototype.extend = function(object) {
  // loop through object 
  for (var i in object) {
    // check if the extended object has that property
    if (object.hasOwnProperty(i)) {
      // mow check if the child is also and object so we go through it recursively
      if (typeof this[i] == "object" && this.hasOwnProperty(i) && this[i] != null) {
        this[i].extend(object[i]);
      } else {
        this[i] = object[i];
      }
    }
  }
  return this;
};

update: I checked for this[i] != null since null is an object

Then use it like:

var options = {
      foo: 'bar',
      baz: 'dar'
    }

    var defaults = {
      foo: false,
      baz: 'car',
      nat: 0
    }

defaults.extend(options);

This well result in:

// defaults will now be
{
  foo: 'bar',
  baz: 'dar',
  nat: 0
}

Can RDP clients launch remote applications and not desktops

RDP will not do that natively.

As other answers have said -- you'll need to do some scripting and make policy changes as a kludge to make it hard for RDP logins to run anything but the intended application.

However, as of 2008, Microsoft has released application virtualization technology via Terminal Services that will allow you to do this seamlessly.

Making a WinForms TextBox behave like your browser's address bar

Interestingly, a ComboBox with DropDownStyle=Simple has pretty much exactly the behaviour you are looking for, I think.

(If you reduce the height of the control to not show the list - and then by a couple of pixels more - there's no effective difference between the ComboBox and the TextBox.)

Numpy: find index of the elements within range

Wanted to add numexpr into the mix:

import numpy as np
import numexpr as ne

a = np.array([1, 3, 5, 6, 9, 10, 14, 15, 56])  

np.where(ne.evaluate("(6 <= a) & (a <= 10)"))[0]
# array([3, 4, 5], dtype=int64)

Would only make sense for larger arrays with millions... or if you hitting a memory limits.

Visual Studio Code compile on save

If you want to avoid having to use CTRL+SHIFT+B and instead want this to occur any time you save a file, you can bind the command to the same short-cut as the save action:

[
    {
        "key": "ctrl+s",          
        "command": "workbench.action.tasks.build" 
    }
]

This goes in your keybindings.json - (head to this using File -> Preferences -> Keyboard Shortcuts).

Compare cell contents against string in Excel

If a case-insensitive comparison is acceptable, just use =:

=IF(A1="ENG",1,0)

Maven - Failed to execute goal org.apache.maven.plugins:maven-clean-plugin:2.4.1:clean

If you open the directory which it is trying to delete then also you will face same error so first close the folder.

UIViewController viewDidLoad vs. viewWillAppear: What is the proper division of labor?

viewDidLoad is things you have to do once. viewWillAppear gets called every time the view appears. You should do things that you only have to do once in viewDidLoad - like setting your UILabel texts. However, you may want to modify a specific part of the view every time the user gets to view it, e.g. the iPod application scrolls the lyrics back to the top every time you go to the "Now Playing" view.

However, when you are loading things from a server, you also have to think about latency. If you pack all of your network communication into viewDidLoad or viewWillAppear, they will be executed before the user gets to see the view - possibly resulting a short freeze of your app. It may be good idea to first show the user an unpopulated view with an activity indicator of some sort. When you are done with your networking, which may take a second or two (or may even fail - who knows?), you can populate the view with your data. Good examples on how this could be done can be seen in various twitter clients. For example, when you view the author detail page in Twitterrific, the view only says "Loading..." until the network queries have completed.

Where is android studio building my .apk file?

For Android Studio:

If you haven't built the APK at least once, you might not find the /Outputs/APK folder. Go to Build in Android Studio and one of the last three options is Build APK, select that. It will then create that folder and you will find your APK file there.

Add Insecure Registry to Docker

Create /etc/docker/daemon.json file where you want to pull docker images and add the following content to that file

{
    "insecure-registries" : [ "hostname.cloudapp.net:5000" ]
}

Refer to my blog article for an in-depth explanation of creating a private docker registry: https://geekdosage.com/how-to-create-a-private-docker-registry-in-ubuntu-20-04/

How to download all dependencies and packages to directory

# aptitude clean
# aptitude --download-only install <your_package_here>
# cp /var/cache/apt/archives/*.deb <your_directory_here>

Laravel whereIn OR whereIn

Yes, orWhereIn is a method that you can use.

I'm fairly sure it should give you the result you're looking for, however, if it doesn't you could simply use implode to create a string and then explode it (this is a guess at your array structure):

$values = implode(',', array_map(function($value)
{
    return trim($value, ',');
}, $filters));

$query->whereIn('products.value', explode(',' $values));

Sending the bearer token with axios

axios by itself comes with two useful "methods" the interceptors that are none but middlewares between the request and the response. so if on each request you want to send the token. Use the interceptor.request.

I made apackage that helps you out:

$ npm i axios-es6-class

Now you can use axios as class

export class UserApi extends Api {
    constructor (config) {
        super(config);

        // this middleware is been called right before the http request is made.
        this.interceptors.request.use(param => {
            return {
                ...param,
                defaults: {
                    headers: {
                        ...param.headers,
                        "Authorization": `Bearer ${this.getToken()}`
                    },
                }
            }
        });

      this.login = this.login.bind(this);
      this.getSome = this.getSome.bind(this);
   }

   login (credentials) {
      return this.post("/end-point", {...credentials})
      .then(response => this.setToken(response.data))
      .catch(this.error);
   }


   getSome () {
      return this.get("/end-point")
      .then(this.success)
      .catch(this.error);
   }
}

I mean the implementation of the middleware depends on you, or if you prefer to create your own axios-es6-class https://medium.com/@enetoOlveda/how-to-use-axios-typescript-like-a-pro-7c882f71e34a it is the medium post where it came from

Yarn: How to upgrade yarn version using terminal?

If you already have yarn 1.x and you want to upgrade to yarn 2. You need to do something a bit different:

yarn set version berry

Where berry is the code name for yarn version 2. See this migration guide here for more info.

Git - Ignore node_modules folder everywhere

**node_modules

This works for me

recursive approach to ignore all node_modules present in sub folders

What is a singleton in C#?

I know it's very late to answer the question but with Auto-Property you can do something like that:

public static Singleton Instance { get; } = new Singleton();

Where Singleton is you class and can be via, in this case the readonly property Instance.

How can I check if mysql is installed on ubuntu?

# mysqladmin -u root -p status

Output:

Enter password:
Uptime: 4  Threads: 1  Questions: 62  Slow queries: 0  Opens: 51  Flush tables: 1  Open tables: 45  Queries per second avg: 15.500

It means MySQL serer is running

If server is not running then it will dump error as follows

# mysqladmin -u root -p status

Output :

mysqladmin: connect to server at 'localhost' failed
error: 'Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)'
Check that mysqld is running and that the socket: '/var/run/mysqld/mysqld.sock' exists!

So Under Debian Linux you can type following command

# /etc/init.d/mysql status

How can I select from list of values in Oracle

There are various ways to take a comma-separated list and parse it into multiple rows of data. In SQL

SQL> ed
Wrote file afiedt.buf

  1  with x as (
  2    select '1,2,3,a,b,c,d' str from dual
  3  )
  4   select regexp_substr(str,'[^,]+',1,level) element
  5     from x
  6* connect by level <= length(regexp_replace(str,'[^,]+')) + 1
SQL> /

ELEMENT
----------------------------------------------------
1
2
3
a
b
c
d

7 rows selected.

Or in PL/SQL

SQL> create type str_tbl is table of varchar2(100);
  2  /

Type created.

SQL> create or replace function parse_list( p_list in varchar2 )
  2    return str_tbl
  3    pipelined
  4  is
  5  begin
  6    for x in (select regexp_substr( p_list, '[^,]', 1, level ) element
  7                from dual
  8             connect by level <= length( regexp_replace( p_list, '[^,]+')) + 1)
  9    loop
 10      pipe row( x.element );
 11    end loop
 12    return;
 13  end;
 14
 15  /

Function created.

SQL> select *
  2    from table( parse_list( 'a,b,c,1,2,3,d,e,foo' ));

COLUMN_VALUE
--------------------------------------------------------------------------------
a
b
c
1
2
3
d
e
f

9 rows selected.

Adding three months to a date in PHP

You need to convert the date into a readable value. You may use strftime() or date().

Try this:

$effectiveDate = strtotime("+3 months", strtotime($effectiveDate));
$effectiveDate = strftime ( '%Y-%m-%d' , $effectiveDate );
echo $effectiveDate;

This should work. I like using strftime better as it can be used for localization you might want to try it.

Create the perfect JPA entity

I'll try to answer several key points: this is from long Hibernate/ persistence experience including several major applications.

Entity Class: implement Serializable?

Keys needs to implement Serializable. Stuff that's going to go in the HttpSession, or be sent over the wire by RPC/Java EE, needs to implement Serializable. Other stuff: not so much. Spend your time on what's important.

Constructors: create a constructor with all required fields of the entity?

Constructor(s) for application logic, should have only a few critical "foreign key" or "type/kind" fields which will always be known when creating the entity. The rest should be set by calling the setter methods -- that's what they're for.

Avoid putting too many fields into constructors. Constructors should be convenient, and give basic sanity to the object. Name, Type and/or Parents are all typically useful.

OTOH if application rules (today) require a Customer to have an Address, leave that to a setter. That is an example of a "weak rule". Maybe next week, you want to create a Customer object before going to the Enter Details screen? Don't trip yourself up, leave possibility for unknown, incomplete or "partially entered" data.

Constructors: also, package private default constructor?

Yes, but use 'protected' rather than package private. Subclassing stuff is a real pain when the necessary internals are not visible.

Fields/Properties

Use 'property' field access for Hibernate, and from outside the instance. Within the instance, use the fields directly. Reason: allows standard reflection, the simplest & most basic method for Hibernate, to work.

As for fields 'immutable' to the application -- Hibernate still needs to be able to load these. You could try making these methods 'private', and/or put an annotation on them, to prevent application code making unwanted access.

Note: when writing an equals() function, use getters for values on the 'other' instance! Otherwise, you'll hit uninitialized/ empty fields on proxy instances.

Protected is better for (Hibernate) performance?

Unlikely.

Equals/HashCode?

This is relevant to working with entities, before they've been saved -- which is a thorny issue. Hashing/comparing on immutable values? In most business applications, there aren't any.

A customer can change address, change the name of their business, etc etc -- not common, but it happens. Corrections also need to be possible to make, when the data was not entered correctly.

The few things that are normally kept immutable, are Parenting and perhaps Type/Kind -- normally the user recreates the record, rather than changing these. But these do not uniquely identify the entity!

So, long and short, the claimed "immutable" data isn't really. Primary Key/ ID fields are generated for the precise purpose, of providing such guaranteed stability & immutability.

You need to plan & consider your need for comparison & hashing & request-processing work phases when A) working with "changed/ bound data" from the UI if you compare/hash on "infrequently changed fields", or B) working with "unsaved data", if you compare/hash on ID.

Equals/HashCode -- if a unique Business Key is not available, use a non-transient UUID which is created when the entity is initialized

Yes, this is a good strategy when required. Be aware that UUIDs are not free, performance-wise though -- and clustering complicates things.

Equals/HashCode -- never refer to related entities

"If related entity (like a parent entity) needs to be part of the Business Key then add a non insertable, non updatable field to store the parent id (with the same name as the ManytoOne JoinColumn) and use this id in the equality check"

Sounds like good advice.

Hope this helps!

(change) vs (ngModelChange) in angular

As I have found and wrote in another topic - this applies to angular < 7 (not sure how it is in 7+)

Just for the future

we need to observe that [(ngModel)]="hero.name" is just a short-cut that can be de-sugared to: [ngModel]="hero.name" (ngModelChange)="hero.name = $event".

So if we de-sugar code we would end up with:

<select (ngModelChange)="onModelChange()" [ngModel]="hero.name" (ngModelChange)="hero.name = $event">

or

<[ngModel]="hero.name" (ngModelChange)="hero.name = $event" select (ngModelChange)="onModelChange()">

If you inspect the above code you will notice that we end up with 2 ngModelChange events and those need to be executed in some order.

Summing up: If you place ngModelChange before ngModel, you get the $event as the new value, but your model object still holds previous value. If you place it after ngModel, the model will already have the new value.

SOURCE

How do you rebase the current branch's changes on top of changes being merged in?

You've got what rebase does backwards. git rebase master does what you're asking for — takes the changes on the current branch (since its divergence from master) and replays them on top of master, then sets the head of the current branch to be the head of that new history. It doesn't replay the changes from master on top of the current branch.

LD_LIBRARY_PATH vs LIBRARY_PATH

LD_LIBRARY_PATH is searched when the program starts, LIBRARY_PATH is searched at link time.

caveat from comments:

Initializing default values in a struct

You don't even need to define a constructor

struct foo {
    bool a = true;
    bool b = true;
    bool c;
 } bar;

To clarify: these are called brace-or-equal-initializers (because you may also use brace initialization instead of equal sign). This is not only for aggregates: you can use this in normal class definitions. This was added in C++11.

Django optional url parameters

There are several approaches.

One is to use a non-capturing group in the regex: (?:/(?P<title>[a-zA-Z]+)/)?
Making a Regex Django URL Token Optional

Another, easier to follow way is to have multiple rules that matches your needs, all pointing to the same view.

urlpatterns = patterns('',
    url(r'^project_config/$', views.foo),
    url(r'^project_config/(?P<product>\w+)/$', views.foo),
    url(r'^project_config/(?P<product>\w+)/(?P<project_id>\w+)/$', views.foo),
)

Keep in mind that in your view you'll also need to set a default for the optional URL parameter, or you'll get an error:

def foo(request, optional_parameter=''):
    # Your code goes here

Can I make a <button> not submit a form?

The button element has a default type of submit.

You can make it do nothing by setting a type of button:

<button type="button">Cancel changes</button>

Substring in VBA

You can first find the position of the string in this case ":"

'position = InStr(StringToSearch, StringToFind)
position = InStr(StringToSearch, ":")

Then use Left(StringToCut, NumberOfCharacterToCut)

Result = Left(StringToSearch, position -1)

How to see full absolute path of a symlink

unix flavors -> ll symLinkName

OSX -> readlink symLinkName

Difference is 1st way would display the sym link path in a blinking way and 2nd way would just echo it out on the console.

Get Application Name/ Label via ADB Shell or Terminal

Inorder to find an app's name (application label), you need to do the following:
(as shown in other answers)

  1. Find the APK path of the app whose name you want to find.
  2. Using aapt command, find the app label.

But devices don't ship with the aapt binary out-of-the-box.
So you will need to install it first. You can download it from here:
https://github.com/Calsign/APDE/tree/master/APDE/src/main/assets/aapt-binaries


Check this guide for complete steps:
How to find an app name using package name through ADB Android?
(Disclaimer: I am the author of that blog post)

How to re-sync the Mysql DB if Master and slave have different database incase of Mysql replication?

sometimes you just need to give the slave a kick too

try

stop slave;    
reset slave;    
start slave;    
show slave status;

quite often, slaves, they just get stuck guys :)

Differences between time complexity and space complexity?

First of all, the space complexity of this loop is O(1) (the input is customarily not included when calculating how much storage is required by an algorithm).

So the question that I have is if its possible that an algorithm has different time complexity from space complexity?

Yes, it is. In general, the time and the space complexity of an algorithm are not related to each other.

Sometimes one can be increased at the expense of the other. This is called space-time tradeoff.

Can Json.NET serialize / deserialize to / from a stream?

The current version of Json.net does not allow you to use the accepted answer code. A current alternative is:

public static object DeserializeFromStream(Stream stream)
{
    var serializer = new JsonSerializer();

    using (var sr = new StreamReader(stream))
    using (var jsonTextReader = new JsonTextReader(sr))
    {
        return serializer.Deserialize(jsonTextReader);
    }
}

Documentation: Deserialize JSON from a file stream

How to recognize swipe in all 4 directions

Swipe Gesture in Swift 5

  override func viewDidLoad() {
    super.viewDidLoad()
    let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(handleGesture))
    swipeLeft.direction = .left
    self.view!.addGestureRecognizer(swipeLeft)

    let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(handleGesture))
    swipeRight.direction = .right
    self.view!.addGestureRecognizer(swipeRight)

    let swipeUp = UISwipeGestureRecognizer(target: self, action: #selector(handleGesture))
    swipeUp.direction = .up
    self.view!.addGestureRecognizer(swipeUp)

    let swipeDown = UISwipeGestureRecognizer(target: self, action: #selector(handleGesture))
    swipeDown.direction = .down
    self.view!.addGestureRecognizer(swipeDown)
}

@objc func handleGesture(gesture: UISwipeGestureRecognizer) -> Void {
    if gesture.direction == UISwipeGestureRecognizer.Direction.right {
        print("Swipe Right")
    }
    else if gesture.direction == UISwipeGestureRecognizer.Direction.left {
        print("Swipe Left")
    }
    else if gesture.direction == UISwipeGestureRecognizer.Direction.up {
        print("Swipe Up")
    }
    else if gesture.direction == UISwipeGestureRecognizer.Direction.down {
        print("Swipe Down")
    }
}

How to start MySQL server on windows xp

The error complains about localhost rather than permissions and the current practice in MySQL is to have a bind-address specifying localhost only in a configuration file.

So I don't think it's a password problem - except that you say you 'unzipped' MySQL.

Is that enough installation? What did you download?

Was there any installation step which allowed you to define a root password?

And, as NawaMan said, is the server running?

permission denied - php unlink

in addition to all the answers that other friends have , if somebody who is looking this post is looking for a way to delete a "Folder" not a "file" , should take care that Folders must delete by php rmdir() function and if u want to delete a "Folder" by unlink() , u will encounter with a wrong Warning message that says "permission denied"

however u can make folders & files by mkdir() but the way u delete folders (rmdir()) is different from the way you delete files(unlink())

eventually as a fact:

in many programming languages, any permission related error may not directly means an actual permission issue

for example, if you want to readSync a file that doesn't exist with node fs module you will encounter a wrong EPERM error

Datepicker: How to popup datepicker when click on edittext

<EditText
    android:id="@+id/date"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:ems="10"
    android:hint="DD/MM/YYYY"
    android:inputType="date"
    android:focusable="false"/>

<EditText
    android:id="@+id/time"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:hint="00:00"
    android:inputType="time"
    android:focusable="false"/>

JAVA FILE

import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;

import java.util.Calendar;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    EditText selectDate,selectTime;
    private int mYear, mMonth, mDay, mHour, mMinute;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        selectDate=(EditText)findViewById(R.id.date);
        selectTime=(EditText)findViewById(R.id.time);

        selectDate.setOnClickListener(this);
        selectTime.setOnClickListener(this);




    }

    @Override
    public void onClick(View view) {

        if (view == selectDate) {
            final Calendar c = Calendar.getInstance();
            mYear = c.get(Calendar.YEAR);
            mMonth = c.get(Calendar.MONTH);
            mDay = c.get(Calendar.DAY_OF_MONTH);


            DatePickerDialog datePickerDialog = new DatePickerDialog(this,
                    new DatePickerDialog.OnDateSetListener() {

                        @Override
                        public void onDateSet(DatePicker view, int year,
                                              int monthOfYear, int dayOfMonth) {

                            selectDate.setText(dayOfMonth + "-" + (monthOfYear + 1) + "-" + year);

                        }
                    }, mYear, mMonth, mDay);
            datePickerDialog.show();
        }
        if (view == selectTime) {

            // Get Current Time
            final Calendar c = Calendar.getInstance();
            mHour = c.get(Calendar.HOUR_OF_DAY);
            mMinute = c.get(Calendar.MINUTE);

            // Launch Time Picker Dialog
            TimePickerDialog timePickerDialog = new TimePickerDialog(this,
                    new TimePickerDialog.OnTimeSetListener() {

                        @Override
                        public void onTimeSet(TimePicker view, int hourOfDay,
                                              int minute) {

                            selectTime.setText(hourOfDay + ":" + minute);
                        }
                    }, mHour, mMinute, false);
            timePickerDialog.show();
        }
    }
}

Setting a system environment variable from a Windows batch file?

Simple example for how to set JAVA_HOME with setx.exe in command line:

setx JAVA_HOME "C:\Program Files (x86)\Java\jdk1.7.0_04"

This will set environment variable "JAVA_HOME" for current user. If you want to set a variable for all users, you have to use option "-m". Here is an example:

setx -m JAVA_HOME "C:\Program Files (x86)\Java\jdk1.7.0_04"

Note: you have to execute this command as Administrator.

Note: Make sure to run the command setx from an command-line Admin window

Laravel 5 - How to access image uploaded in storage within View?

The best approach is to create a symbolic link like @SlateEntropy very well pointed out in the answer below. To help with this, since version 5.3, Laravel includes a command which makes this incredibly easy to do:

php artisan storage:link

That creates a symlink from public/storage to storage/app/public for you and that's all there is to it. Now any file in /storage/app/public can be accessed via a link like:

http://somedomain.com/storage/image.jpg

If, for any reason, your can't create symbolic links (maybe you're on shared hosting, etc.) or you want to protect some files behind some access control logic, there is the alternative of having a special route that reads and serves the image. For example a simple closure route like this:

Route::get('storage/{filename}', function ($filename)
{
    $path = storage_path('public/' . $filename);

    if (!File::exists($path)) {
        abort(404);
    }

    $file = File::get($path);
    $type = File::mimeType($path);

    $response = Response::make($file, 200);
    $response->header("Content-Type", $type);

    return $response;
});

You can now access your files just as you would if you had a symlink:

http://somedomain.com/storage/image.jpg

If you're using the Intervention Image Library you can use its built in response method to make things more succinct:

Route::get('storage/{filename}', function ($filename)
{
    return Image::make(storage_path('public/' . $filename))->response();
});

WARNING

Keep in mind that by manually serving the files you're incurring a performance penalty, because you're going through the entire Laravel request lifecycle in order to read and send the file contents, which is considerably slower than having the HTTP server handle it.