Programs & Examples On #Zsh

The Z shell (Zsh) is a Unix shell that can be used as an interactive login shell and as a powerful command interpreter for shell scripting.

How to make zsh run as a login shell on Mac OS X (in iTerm)?

In iTerm -> Preferences -> Profiles Tab -> General section set Command to: /bin/zsh --login

/bin/zsh --login

How to add a progress bar to a shell script?

My solution displays the percentage of the tarball that is currently being uncompressed and written. I use this when writing out 2GB root filesystem images. You really need a progress bar for these things. What I do is use gzip --list to get the total uncompressed size of the tarball. From that I calculate the blocking-factor needed to divide the file into 100 parts. Finally, I print a checkpoint message for each block. For a 2GB file this gives about 10MB a block. If that is too big then you can divide the BLOCKING_FACTOR by 10 or 100, but then it's harder to print pretty output in terms of a percentage.

Assuming you are using Bash then you can use the following shell function

untar_progress () 
{ 
  TARBALL=$1
  BLOCKING_FACTOR=$(gzip --list ${TARBALL} |
    perl -MPOSIX -ane '$.==2 && print ceil $F[1]/50688')
  tar --blocking-factor=${BLOCKING_FACTOR} --checkpoint=1 \
    --checkpoint-action='ttyout=Wrote %u%  \r' -zxf ${TARBALL}
}

How can I change the color of my prompt in zsh (different from normal text)?

The answer by Bryan Oakley above has a glitch as it has already been pointed out and the solution offered by Andrew Marshall though it does not carry the glitch, nevertheless it does not make it obvious for too much customization on the colors used.

As macOS Catalina asks for zsh to be the default shell from now on, I think several more people may want to customize their prompt and might be coming here for an answer. So, I thought I would try to give a broader summary and touch upon other very closely-related notions that allow more customization.

3-Digit Codes for Various Colors. First of all, here we can find 3-digit codes for various colors: https://unix.stackexchange.com/a/124409/194343. For example, 214 is some kind of orange color.

Foreground and Background. The other key information is that for Foreground and bacKground colors one can define what they want with F and K respectively. Source is zsh manual on visual effects: http://zsh.sourceforge.net/Doc/Release/Prompt-Expansion.html#Visual-effects

So, for example, the following two commands

autoload -U colors && colors
export PS1="%F{214}%K{000}%m%F{015}%K{000}:%F{039}%K{000}%~%F{015}%K{000}\$ "

present the hostname in orange with black background, followed by a colon in white with black background, followed by the current working directory in bright blue with black background, followed by the dollar sign in white with black background.

More related information is found below.

Prompt information on the right-hand side. For example, adding a timestamp. See https://superuser.com/a/1251045/290299. Of course, this can be color-coded, for example with some light blue/purple-ish color, like this:

RPROMPT="%F{111}%K{000}[%D{%f/%m/%y}|%@]"

Colors for ls. After reading the manual for ls, one for example can activate the colors for ls using the following two commands:

export CLICOLOR=1
export LSCOLORS=gafacadabaegedabagacad

Finally, as a last remark that I have not tested as I am happy with my configuration, another avenue might be for someone to install the port coreutils from MacPorts and then use gdircolors (source: https://unix.stackexchange.com/a/174596/194343). (I may edit this last part in the future as all the above are related pieces that make every-day life much more fun and easier to cope with.)

How can I format the output of a bash command in neat columns

column(1) is your friend.

$ column -t <<< '"option-y"      yank-pop
> "option-z"      execute-last-named-cmd
> "option-|"      vi-goto-column
> "option-~"      _bash_complete-word
> "option-control-?"      backward-kill-word
> "control-_"     undo
> "control-?"     backward-delete-char
> '
"option-y"          yank-pop
"option-z"          execute-last-named-cmd
"option-|"          vi-goto-column
"option-~"          _bash_complete-word
"option-control-?"  backward-kill-word
"control-_"         undo
"control-?"         backward-delete-char

What does "export" do in shell programming?

Well, it generally depends on the shell. For bash, it marks the variable as "exportable" meaning that it will show up in the environment for any child processes you run.

Non-exported variables are only visible from the current process (the shell).

From the bash man page:

export [-fn] [name[=word]] ...
export -p

The supplied names are marked for automatic export to the environment of subsequently executed commands.

If the -f option is given, the names refer to functions. If no names are given, or if the -p option is supplied, a list of all names that are exported in this shell is printed.

The -n option causes the export property to be removed from each name.

If a variable name is followed by =word, the value of the variable is set to word.

export returns an exit status of 0 unless an invalid option is encountered, one of the names is not a valid shell variable name, or -f is supplied with a name that is not a function.

You can also set variables as exportable with the typeset command and automatically mark all future variable creations or modifications as such, with set -a.

Command not found after npm install in zsh

Another thing to try and the answer for me was to uncomment the first export in ~/.zshrc

# If you come from bash you might have to change your $PATH. export PATH=$HOME/bin:/usr/local/bin:$PATH

Zsh: Conda/Pip installs command not found

You need to fix the spacing and quotes:

export PATH ="/Users/Dz/anaconda/bin:$PATH"

Instead use

export PATH="/Users/Dz/anaconda/bin":$PATH

How do I update zsh to the latest version?

I just switched the main shell to zsh. It suppresses the warnings and it isn't too complicated.

zsh compinit: insecure directories

I had the same warning lately on Catalina. An easy workaround is to put this to the top of your .zshrc

ZSH_DISABLE_COMPFIX=true

npm global path prefix

Any one got the same issue it's related to a conflict between brew and npm Please check this solution https://gist.github.com/DanHerbert/9520689

Check if current directory is a Git repository

Based on @Alex Cory's answer:

[ "$(git rev-parse --is-inside-work-tree 2>/dev/null)" == "true" ]

doesn't contain any redundant operations and works in -e mode.

  • As @go2null noted, this will not work in a bare repo. If you want to work with a bare repo for whatever reason, you can just check for git rev-parse succeeding, ignoring its output.
    • I don't consider this a drawback because the above line is indended for scripting, and virtually all git commands are only valid inside a worktree. So for scripting purposes, you're most likely interested in being not just inside a "git repo" but inside a worktree.

Adding a new entry to the PATH variable in ZSH

  1. Added path to ~/.zshrc

    sudo vi ~/.zshrc

    add new path

    export PATH="$PATH:[NEW_DIRECTORY]/bin"
    
  2. Update ~/.zshrc

    Save ~/.zshrc

    source ~/.zshrc

  3. Check PATH

    echo $PATH

Conda command not found

I faced this issue on my mac after updating conda. Solution was to run conda mini installer on top of existing conda setup.

$ curl https://repo.continuum.io/miniconda/Miniconda3-latest-MacOSX-x86_64.sh -o ~/miniconda3.sh
$ bash ~/miniconda3.sh -bfp ~/miniconda3

On linux, you can use:

$ curl https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh -o ~/miniconda3.sh
$ bash ~/miniconda3.sh -bfp ~/miniconda3

For other versions, you can go to https://repo.continuum.io/miniconda/

For details check: https://github.com/conda/conda/issues/1364

Switching from zsh to bash on OSX, and back again?

you can try chsh -s /bin/bash to set the bash as the default, or chsh -s /bin/zsh to set the zsh as the default.

Terminal will need a restart to take effect.

commands not found on zsh

In my case, it was by mistake the commented code was uncommented at the very first line.

# If you come from bash you might have to change your $PATH.

The hash was removed. After adding it back worked fine.

I just posted this here so someone might find this helpful. Because it's just start of the line and might be deleted by mistake like I had done. And seems there's no solution after trying several ways.

Where to place $PATH variable assertions in zsh?

I had similar problem (in bash terminal command was working correctly but zsh showed command not found error)

Solution:


just paste whatever you were earlier pasting in ~/.bashrc to:

~/.zshrc

How to permanently set $PATH on Linux/Unix?

Add to /etc/profile.d folder script [name_of_script].sh with line: export PATH=$PATH:/dir. Every script within /etc/profile.d folder is automaticaly executed by /etc/profile on login.

Find elements inside forms and iframe using Java and Selenium WebDriver

Before you try searching for the elements within the iframe you will have to switch Selenium focus to the iframe.

Try this before searching for the elements within the iframe:

driver.switchTo().frame(driver.findElement(By.name("iFrameTitle")));

How to get Top 5 records in SqLite?

select price from mobile_sales_details order by price desc limit 5

Note: i have mobile_sales_details table

syntax

select column_name from table_name order by column_name desc limit size.  

if you need top low price just remove the keyword desc from order by

graphing an equation with matplotlib

To plot an equation that is not solved for a specific variable (like circle or hyperbola):

import numpy as np  
import matplotlib.pyplot as plt  
plt.figure() # Create a new figure window
xlist = np.linspace(-2.0, 2.0, 100) # Create 1-D arrays for x,y dimensions
ylist = np.linspace(-2.0, 2.0, 100) 
X,Y = np.meshgrid(xlist, ylist) # Create 2-D grid xlist,ylist values
F = X**2 + Y**2 - 1  #  'Circle Equation
plt.contour(X, Y, F, [0], colors = 'k', linestyles = 'solid')
plt.show()

More about it: http://courses.csail.mit.edu/6.867/wiki/images/3/3f/Plot-python.pdf

How to join two tables by multiple columns in SQL?

You would basically want something along the lines of:

SELECT e.*, v.Score
  FROM Evaluation e
LEFT JOIN Value v
ON v.CaseNum = e.CaseNum AND
v.FileNum = e.FileNum AND
v.ActivityNum = e.ActivityNum;

Difference between Console.Read() and Console.ReadLine()?

Console.Read() basically reads a character so if you are on a console and you press a key then the console will close, meanwhile Console.Readline() will read the whole string.

ASP.NET MVC Razor: How to render a Razor Partial View's HTML inside the controller action

@Html.Partial("nameOfPartial", Model)

Update

protected string RenderPartialViewToString(string viewName, object model)
{
    if (string.IsNullOrEmpty(viewName))
        viewName = ControllerContext.RouteData.GetRequiredString("action");

    ViewData.Model = model;

    using (StringWriter sw = new StringWriter()) {
        ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
        ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
        viewResult.View.Render(viewContext, sw);

        return sw.GetStringBuilder().ToString();
    }
}

Replace duplicate spaces with a single space in T-SQL

Method #1

The first method is to replace extra spaces between words with an uncommon symbol combination as a temporary marker. Then you can replace the temporary marker symbols using the replace function rather than a loop.

Here is a code example that replaces text within a String variable.

DECLARE @testString AS VARCHAR(256) = ' Test        text   with  random*        spacing. Please normalize  this spacing!';
SELECT REPLACE(REPLACE(REPLACE(@testString, ' ', '*^'), '^*', ''), '*^', ' ');

Execution Time Test #1: In ten runs of this replacement method, the average wait time on server replies was 1.7 milliseconds and total execution time was 4.6 milliseconds. Execution Time Test #2: The average wait time on server replies was 1.7 milliseconds and total execution time was 3.7 milliseconds.

Method #2

The second method is not quite as elegant as the first, but also gets the job done. This method works by nesting four (or optionally more) replace statements that replace two blank spaces with one blank space.

DECLARE @testString AS VARCHAR(256) = ' Test        text   with  random*        spacing. Please normalize  this spacing!';
SELECT REPLACE(REPLACE(REPLACE(REPLACE(@testString,' ',' '),' ',' '),' ',' '),' ',' ')

Execution Time Test #1: In ten runs of this replacement method, the average wait time on server replies was 1.9 milliseconds and total execution time was 3.8 milliseconds. Execution Time Test #2: The average wait time on server replies was 1.8 milliseconds and total execution time was 4.8 milliseconds.

Method #3

The third method of replacing extra spaces between words is to use a simple loop. You can do a check on extra spaces in a while loop and then use the replace function to reduce the extra spaces with each iteration of the loop.

DECLARE @testString AS VARCHAR(256) = ' Test text with random* spacing. Please normalize this spacing!';
WHILE CHARINDEX(' ',@testString) > 0
SET @testString = REPLACE(@testString, ' ', ' ')
SELECT @testString

Execution Time Test #1: In ten runs of this replacement method, the average wait time on server replies was 1.8 milliseconds and total execution time was 3.4 milliseconds. Execution Time Test #2: The average wait time on server replies was 1.9 milliseconds and total execution time was 2.8 milliseconds.

Which .NET Dependency Injection frameworks are worth looking into?

I'm a huge fan of Castle. I love the facilities it also provides beyond the IoC Container story. It really simplfies using NHibernate, logging, AOP, etc. I also use Binsor for configuration with Boo and have really fallen in love with Boo as a language because of it.

How to find out the location of currently used MySQL configuration file in linux

login to mysql with proper credential and used mysql>SHOW VARIABLES LIKE 'datadir'; that will give you path of where mysql stored

How do I set up Visual Studio Code to compile C++ code?

There's now a C/C++ language extension from Microsoft. You can install it by going to the "quick open" thing (Ctrl+p) and typing:

ext install cpptools

You can read about it here:

https://blogs.msdn.microsoft.com/vcblog/2016/03/31/cc-extension-for-visual-studio-code/

It's very basic, as of May 2016.

Python function global variables?

If you want to simply access a global variable you just use its name. However to change its value you need to use the global keyword.

E.g.

global someVar
someVar = 55

This would change the value of the global variable to 55. Otherwise it would just assign 55 to a local variable.

The order of function definition listings doesn't matter (assuming they don't refer to each other in some way), the order they are called does.

How to get list of dates between two dates in mysql select query

Try:

select * from 
(select adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
where selected_date between '2012-02-10' and '2012-02-15'

-for date ranges up to nearly 300 years in the future.

[Corrected following a suggested edit by UrvishAtSynapse.]

How to get all enum values in Java?

Enums are just like Classes in that they are typed. Your current code just checks if it is an Enum without specifying what type of Enum it is a part of.

Because you haven't specified the type of the enum, you will have to use reflection to find out what the list of enum values is.

You can do it like so:

enumValue.getDeclaringClass().getEnumConstants() 

This will return an array of Enum objects, with each being one of the available options.

ADB.exe is obsolete and has serious performance problems

I followed the answer, but the magic final step was deleting the existing virtual environment and creating a new one.

How to upgrade docker container after its image changed

Just for providing a more general (not mysql specific) answer...

  1. In short

Synchronize with service image registry (https://docs.docker.com/compose/compose-file/#image):

docker-compose pull 

Recreate container if docker-compose file or image have changed:

docker-compose up -d
  1. Background

Container image management is one of the reason for using docker-compose (see https://docs.docker.com/compose/reference/up/)

If there are existing containers for a service, and the service’s configuration or image was changed after the container’s creation, docker-compose up picks up the changes by stopping and recreating the containers (preserving mounted volumes). To prevent Compose from picking up changes, use the --no-recreate flag.

Data management aspect being also covered by docker-compose through mounted external "volumes" (See https://docs.docker.com/compose/compose-file/#volumes) or data container.

This leaves potential backward compatibility and data migration issues untouched, but these are "applicative" issues, not Docker specific, which have to be checked against release notes and tests...

Powershell: A positional parameter cannot be found that accepts argument "xxx"

I had this problem when trying to change directory, using the character _. The solution was to use a string to change directories.

C:\> cd "my_new_dir"

FPDF utf-8 encoding (HOW-TO)

There also is a official UTF-8 Version of FPDF called tFPDF http://www.fpdf.org/en/script/script92.php

You can easyly switch from the original FPDF, just make sure you also use a unicode Font as shown in the example in the above link or my code:

<?php

//this is a UTF-8 file, we won't need any encode/decode/iconv workarounds

//define the path to the .ttf files you want to use
define('FPDF_FONTPATH',"../fonts/");
require('tfpdf.php');

$pdf = new tFPDF();
$pdf->AddPage();

// Add Unicode fonts (.ttf files)
$fontName = 'Helvetica';
$pdf->AddFont($fontName,'','HelveticaNeue LightCond.ttf',true);
$pdf->AddFont($fontName,'B','HelveticaNeue MediumCond.ttf',true);

//now use the Unicode font in bold
$pdf->SetFont($fontName,'B',12);

//anything else is identical to the old FPDF, just use Write(),Cell(),MultiCell()... 
//without any encoding trouble
$pdf->Cell(100,20, "Some UTF-8 String");

//...
?>

I think its much more elegant to use this instead of spaming utf8_decode() everywhere and the ability to use .ttf files directly in AddFont() is an upside too.

Any other answer here is just a way to avoid or work around the problem, and avoiding UTF-8 is no real option for an up to date project.

There are also alternatives like mPDF or TCPDF (and others) wich base on FPDF but offer advanced functions, have UTF-8 Support and can interpret HTML Code (limited of course as there is no direct way to convert HTML to PDF). Most of the FPDF code can be used directly in those librarys, so its pretty easy to migrate the code.

https://github.com/mpdf/mpdf http://www.tcpdf.org/

Rollback to last git commit

An easy foolproof way to UNDO local file changes since the last commit is to place them in a new branch:

git branch changes
git checkout changes
git add .
git commit

This leaves the changes in the new branch. Return to the original branch to find it back to the last commit:

git checkout master

The new branch is a good place to practice different ways to revert changes without risk of messing up the original branch.

Should I use SVN or Git?

The funny thing is: I host projects in Subversion Repos, but access them via the Git Clone command.

Please read Develop with Git on a Google Code Project

Although Google Code natively speaks Subversion, you can easily use Git during development. Searching for "git svn" suggests this practice is widespread, and we too encourage you to experiment with it.

Using Git on a Svn Repository gives me benefits:

  1. I can work distributed on several machines, commiting and pulling from and to them
  2. I have a central backup/public svn repository for others to check out
  3. And they are free to use Git for their own

How to increase scrollback buffer size in tmux?

Open tmux configuration file with the following command:

vim ~/.tmux.conf

In the configuration file add the following line:

set -g history-limit 5000

Log out and log in again, start a new tmux windows and your limit is 5000 now.

writing to serial port from linux command line

SCREEN:

NOTE: screen is actually not able to send hex, as far as I know. To do that, use echo or printf

I was using the suggestions in this post to write to a serial port, then using the info from another post to read from the port, with mixed results. I found that using screen is an "easier" solution, since it opens a terminal session directly with that port. (I put easier in quotes, because screen has a really weird interface, IMO, and takes some further reading to figure it out.)

You can issue this command to open a screen session, then anything you type will be sent to the port, plus the return values will be printed below it:

screen /dev/ttyS0 19200,cs8

(Change the above to fit your needs for speed, parity, stop bits, etc.) I realize screen isn't the "linux command line" as the post specifically asks for, but I think it's in the same spirit. Plus, you don't have to type echo and quotes every time.

ECHO:

Follow praetorian droid's answer. HOWEVER, this didn't work for me until I also used the cat command (cat < /dev/ttyS0) while I was sending the echo command.

PRINTF:

I found that one can also use printf's '%x' command:

c="\x"$(printf '%x' 0x12)
printf $c >> $SERIAL_COMM_PORT

Again, for printf, start cat < /dev/ttyS0 before sending the command.

Timeout on a function call

Great, easy to use and reliable PyPi project timeout-decorator (https://pypi.org/project/timeout-decorator/)

installation:

pip install timeout-decorator

Usage:

import time
import timeout_decorator

@timeout_decorator.timeout(5)
def mytest():
    print "Start"
    for i in range(1,10):
        time.sleep(1)
        print "%d seconds have passed" % i

if __name__ == '__main__':
    mytest()

How to get thread id of a pthread in linux c program?

pid_t tid = syscall(SYS_gettid);

Linux provides such system call to allow you get id of a thread.

Installing mcrypt extension for PHP on OSX Mountain Lion

I just went through this on Mountain Lion. Homebrew blocked on libiconv which it thought was missing but was actually up to date. After an hour of trying to get it to recognize libiconv, I gave up and installed it the old fashion way, which took all of five minutes...

(download your php version)
$ wget http://www.php.net/get/php-5.3.21.tar.gz/from/a/mirror
$ tar -xvzf php-5.3.21.tar.gz
$ cd php-5.3.21/ext/mcrypt
$ phpize
$ ./configure
$ make
$ make test
$ sudo make install 

mcrypt.so is now in your PHP ext dir (/usr/lib/php/extensions/no-debug-non-zts-20090626/ in my case), now you need to add to php.ini as a module

$ vi /etc/php.ini
$ (insert) extension=mcrypt.so
$ sudo apachectl restart

Done - no brew necessary. HTH someone.

Find rows that have the same value on a column in MySQL

First part of accepted answer does not work for MSSQL.
This worked for me:

select email, COUNT(*) as C from table 
group by email having COUNT(*) >1 order by C desc

Getting GET "?" variable in laravel

Query params are used like this:

use Illuminate\Http\Request;

class MyController extends BaseController{

    public function index(Request $request){
         $param = $request->query('param');
    }

Where are the Android icon drawables within the SDK?

You can find android drawables icons from the example path below...

C:\Users\User\AppData\Local\Android\sdk\platforms\android-25\data\res\drawable-xhdpi

Return string without trailing slash

Here a small url example.

var currentUrl = location.href;

if(currentUrl.substr(-1) == '/') {
    currentUrl = currentUrl.substr(0, currentUrl.length - 1);
}

log the new url

console.log(currentUrl);

How to get selected option using Selenium WebDriver with Java

You should be able to get the text using getText() (for the option element you got using getFirstSelectedOption()):

Select select = new Select(driver.findElement(By.xpath("//select")));
WebElement option = select.getFirstSelectedOption();
String defaultItem = option.getText();
System.out.println(defaultItem );

Property [title] does not exist on this collection instance

$about->first()->id or $stm->first()->title and your problem is sorted out.

Using request.setAttribute in a JSP page

The reply by Phil Sacre was correct however the session shouldn't be used just for the hell of it. You should only use this for values which really need to live for the lifetime of the session, such as a user login. It's common to see people overuse the session and run into more issues, especially when dealing with a collection or when users return to a page they previously visited only to find they have values still remaining from a previous visit. A smart program minimizes the scope of variables as much as possible, a bad one uses session too much.

Redefine tab as 4 spaces

To define this on a permanent basis for the current user, create (or edit) the .vimrc file:

$ vim ~/.vimrc

Then, paste the configuration below into the file. Once vim is restarted, the tab settings will apply.

set tabstop=4       " The width of a TAB is set to 4.
                    " Still it is a \t. It is just that
                    " Vim will interpret it to be having
                    " a width of 4.

set shiftwidth=4    " Indents will have a width of 4

set softtabstop=4   " Sets the number of columns for a TAB

set expandtab       " Expand TABs to spaces

Dealing with timestamps in R

You want the (standard) POSIXt type from base R that can be had in 'compact form' as a POSIXct (which is essentially a double representing fractional seconds since the epoch) or as long form in POSIXlt (which contains sub-elements). The cool thing is that arithmetic etc are defined on this -- see help(DateTimeClasses)

Quick example:

R> now <- Sys.time()
R> now
[1] "2009-12-25 18:39:11 CST"
R> as.numeric(now)
[1] 1.262e+09
R> now + 10  # adds 10 seconds
[1] "2009-12-25 18:39:21 CST"
R> as.POSIXlt(now)
[1] "2009-12-25 18:39:11 CST"
R> str(as.POSIXlt(now))
 POSIXlt[1:9], format: "2009-12-25 18:39:11"
R> unclass(as.POSIXlt(now))
$sec
[1] 11.79

$min
[1] 39

$hour
[1] 18

$mday
[1] 25

$mon
[1] 11

$year
[1] 109

$wday
[1] 5

$yday
[1] 358

$isdst
[1] 0

attr(,"tzone")
[1] "America/Chicago" "CST"             "CDT"            
R> 

As for reading them in, see help(strptime)

As for difference, easy too:

R> Jan1 <- strptime("2009-01-01 00:00:00", "%Y-%m-%d %H:%M:%S")
R> difftime(now, Jan1, unit="week")
Time difference of 51.25 weeks
R> 

Lastly, the zoo package is an extremely versatile and well-documented container for matrix with associated date/time indices.

What's the difference between window.location= and window.location.replace()?

TLDR;

use location.href or better use window.location.href;

However if you read this you will gain undeniable proof.

The truth is it's fine to use but why do things that are questionable. You should take the higher road and just do it the way that it probably should be done.

location = "#/mypath/otherside"
var sections = location.split('/')

This code is perfectly correct syntax-wise, logic wise, type-wise you know the only thing wrong with it?

it has location instead of location.href

what about this

var mystring = location = "#/some/spa/route"

what is the value of mystring? does anyone really know without doing some test. No one knows what exactly will happen here. Hell I just wrote this and I don't even know what it does. location is an object but I am assigning a string will it pass the string or pass the location object. Lets say there is some answer to how this should be implemented. Can you guarantee all browsers will do the same thing?

This i can pretty much guess all browsers will handle the same.

var mystring = location.href = "#/some/spa/route"

What about if you place this into typescript will it break because the type compiler will say this is suppose to be an object?

This conversation is so much deeper than just the location object however. What this conversion is about what kind of programmer you want to be?

If you take this short-cut, yea it might be okay today, ye it might be okay tomorrow, hell it might be okay forever, but you sir are now a bad programmer. It won't be okay for you and it will fail you.

There will be more objects. There will be new syntax.

You might define a getter that takes only a string but returns an object and the worst part is you will think you are doing something correct, you might think you are brilliant for this clever method because people here have shamefully led you astray.

var Person.name = {first:"John":last:"Doe"}
console.log(Person.name) // "John Doe"

With getters and setters this code would actually work, but just because it can be done doesn't mean it's 'WISE' to do so.

Most people who are programming love to program and love to get better. Over the last few years I have gotten quite good and learn a lot. The most important thing I know now especially when you write Libraries is consistency and predictability.

Do the things that you can consistently do.

+"2" <-- this right here parses the string to a number. should you use it? or should you use parseInt("2")?

what about var num =+"2"?

From what you have learn, from the minds of stackoverflow i am not too hopefully.

If you start following these 2 words consistent and predictable. You will know the right answer to a ton of questions on stackoverflow.

Let me show you how this pays off. Normally I place ; on every line of javascript i write. I know it's more expressive. I know it's more clear. I have followed my rules. One day i decided not to. Why? Because so many people are telling me that it is not needed anymore and JavaScript can do without it. So what i decided to do this. Now because I have become sure of my self as a programmer (as you should enjoy the fruit of mastering a language) i wrote something very simple and i didn't check it. I erased one comma and I didn't think I needed to re-test for such a simple thing as removing one comma.

I wrote something similar to this in es6 and babel

var a = "hello world"
(async function(){
  //do work
})()

This code fail and took forever to figure out. For some reason what it saw was

var a = "hello world"(async function(){})()

hidden deep within the source code it was telling me "hello world" is not a function.

For more fun node doesn't show the source maps of transpiled code.

Wasted so much stupid time. I was presenting to someone as well about how ES6 is brilliant and then I had to start debugging and demonstrate how headache free and better ES6 is. Not convincing is it.

I hope this answered your question. This being an old question it's more for the future generation, people who are still learning.

Question when people say it doesn't matter either way works. Chances are a wiser more experienced person will tell you other wise.

what if someone overwrite the location object. They will do a shim for older browsers. It will get some new feature that needs to be shimmed and your 3 year old code will fail.

My last note to ponder upon.

Writing clean, clear purposeful code does something for your code that can't be answer with right or wrong. What it does is it make your code an enabler.

You can use more things plugins, Libraries with out fear of interruption between the codes.

for the record. use

window.location.href

VBA error 1004 - select method of range class failed

assylias and Head of Catering have already given your the reason why the error is occurring.

Now regarding what you are doing, from what I understand, you don't need to use Select at all

I guess you are doing this from VBA PowerPoint? If yes, then your code be rewritten as

Dim sourceXL As Object, sourceBook As Object
Dim sourceSheet As Object, sourceSheetSum As Object
Dim lRow As Long
Dim measName As Variant, partName As Variant
Dim filepath As String

filepath = CStr(FileDialog)

'~~> Establish an EXCEL application object
On Error Resume Next
Set sourceXL = GetObject(, "Excel.Application")

'~~> If not found then create new instance
If Err.Number <> 0 Then
    Set sourceXL = CreateObject("Excel.Application")
End If
Err.Clear
On Error GoTo 0

Set sourceBook = sourceXL.Workbooks.Open(filepath)
Set sourceSheet = sourceBook.Sheets("Measurements")
Set sourceSheetSum = sourceBook.Sheets("Analysis Summary")

lRow = sourceSheetSum.Range("C" & sourceSheetSum.Rows.Count).End(xlUp).Row
measName = sourceSheetSum.Range("C3:C" & lRow)

lRow = sourceSheetSum.Range("D" & sourceSheetSum.Rows.Count).End(xlUp).Row
partName = sourceSheetSum.Range("D3:D" & lRow)

Socket.io + Node.js Cross-Origin Request Blocked

Alright I had some issues getting this to work using a self signed cert for testing so I am going to copy my setup that worked for me. If your not using a self signed cert you probably wont have these issues, hopefully!

To start off depending on your browser Firefox or Chrome you may have different issues and I'll explain in a minute.

First the Setup:

Client

// May need to load the client script from a Absolute Path
<script src="https://www.YOURDOMAIN.com/node/node_modules/socket.io-client/dist/socket.io.js"></script>
<script>
var options = {
          rememberUpgrade:true,
          transports: ['websocket'],
          secure:true, 
          rejectUnauthorized: false
              }
var socket = io.connect('https://www.YOURDOMAIN.com:PORT', options);

// Rest of your code here
</script>

Server

var fs = require('fs');

var options = {
  key: fs.readFileSync('/path/to/your/file.pem'),
  cert: fs.readFileSync('/path/to/your/file.crt'),

};
var origins = 'https://www.YOURDOMAIN.com:*';
var app = require('https').createServer(options,function(req,res){

    // Set CORS headers
    res.setHeader('Access-Control-Allow-Origin', 'https://www.YOURDOMAIN.com:*');
    res.setHeader('Access-Control-Request-Method', '*');
    res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET');
    res.setHeader('Access-Control-Allow-Headers', '*');
    if ( req.method === 'OPTIONS' || req.method === 'GET' ) {
        res.writeHead(200);
        res.end();
        return;
            }

});

var io = require('socket.io')(app);

app.listen(PORT);

For development the options used on the client side are ok in production you would want the option:

 rejectUnauthorized: false

You would more than likely want set to "true"

Next thing is if its a self signed cert you will need to vist your server in a separate page/tab and accept the cert or import it into your browser.

For Firefox I kept getting the error

MOZILLA_PKIX_ERROR_SELF_SIGNED_CERT

The solution for me was to add the following options and accepting the cert in a different page/tab.

{ 
rejectUnauthorized: false
} 

In Chrome I had to open another page and accept the cert but after that everything worked fine with out having to add any options.

Hope this helps.

References:

https://github.com/theturtle32/WebSocket-Node/issues/259

https://github.com/socketio/engine.io-client#methods

The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception

Check the C-drive inside C:\inetpub\wwwroot and remove all unnecessary folders from it, else remove unnecessary host files or folders from IIS.

Difference between List, List<?>, List<T>, List<E>, and List<Object>

The reason you cannot cast List<String> to List<Object> is that it would allow you to violate the constraints of the List<String>.

Think about the following scenario: If I have a List<String>, it is supposed to only contain objects of type String. (Which is a final class)

If I can cast that to a List<Object>, then that allows me to add Object to that list, thus violating the original contract of List<String>.

Thus, in general, if class C inherits from class P, you cannot say that GenericType<C> also inherits from GenericType<P>.

N.B. I already commented on this in a previous answer but wanted to expand on it.

What is the right way to POST multipart/form-data using curl?

I had a hard time sending a multipart HTTP PUT request with curl to a Java backend. I simply tried

curl -X PUT URL \
   --header 'Content-Type: multipart/form-data; boundary=---------BOUNDARY' \
   --data-binary @file

and the content of the file was

-----------BOUNDARY
Content-Disposition: form-data; name="name1"
Content-Type: application/xml;version=1.0;charset=UTF-8

<xml>content</xml>
-----------BOUNDARY
Content-Disposition: form-data; name="name2"
Content-Type: text/plain

content
-----------BOUNDARY--

but I always got an error that the boundary was incorrect. After some Java backend debugging I found out that the Java implementation was adding a \r\n-- as a prefix to the boundary, so after changing my input file to

                          <-- here's the CRLF
-------------BOUNDARY       <-- added '--' at the beginning
...
-------------BOUNDARY       <-- added '--' at the beginning
...
-------------BOUNDARY--     <-- added '--' at the beginning

everything works fine!

tl;dr

Add a newline (CRLF \r\n) at the beginning of the multipart boundary content and -- at the beginning of the boundaries and try again.

Maybe you are sending a request to a Java backend that needs this changes in the boundary.

How to call webmethod in Asp.net C#

I'm not sure why that isn't working, It works fine on my test. But here is an alternative technique that might help.

Instead of calling the method in the AJAX url, just use the page .aspx url, and add the method as a parameter in the data object. Then when it calls page_load, your data will be in the Request.Form variable.

jQuery

jQuery.ajax({
    url: 'AddToCart.aspx',
    type: "POST",
    data: {
        method: 'AddTo_Cart', quantity: total_qty, itemId: itemId
    },
    dataType: "json",
    beforeSend: function () {
        alert("Start!!! ");
    },
    success: function (data) {
        alert("a");
    },
    failure: function (msg) { alert("Sorry!!! "); }
});

C# Page Load:

if (!Page.IsPostBack)
{
    if (Request.Form["method"] == "AddTo_Cart")
    {
        int q, id;
        int.TryParse(Request.Form["quantity"], out q);
        int.TryParse(Request.Form["itemId"], out id);
        AddTo_Cart(q,id);
    }
}

get string value from HashMap depending on key name

If you will use Generics and define your map as

Map<String,String> map = new HashMap<String,String>();

then fetching value as

 String s = map.get("keyStr"); 

you wont be required to typecast the map.get() or call toString method to get String value

Why is this printing 'None' in the output?

Because of double print function. I suggest you to use return instead of print inside the function definition.

def lyrics():
    return "The very first line"
print(lyrics())

OR

def lyrics():
    print("The very first line")
lyrics()

Using CSS in Laravel views?

your css file belongs into the public folder or a subfolder of it.

f.e if you put your css in

public/css/common.css

you would use

HTML::style('css/common.css');

In your blade view...

Or you could also use the Asset class http://laravel.com/docs/views/assets...

Call an overridden method from super class in typescript

The order of execution is:

  1. A's constructor
  2. B's constructor

The assignment occurs in B's constructor after A's constructor—_super—has been called:

function B() {
    _super.apply(this, arguments);   // MyvirtualMethod called in here
    this.testString = "Test String"; // testString assigned here
}

So the following happens:

var b = new B();     // undefined
b.MyvirtualMethod(); // "Test String"

You will need to change your code to deal with this. For example, by calling this.MyvirtualMethod() in B's constructor, by creating a factory method to create the object and then execute the function, or by passing the string into A's constructor and working that out somehow... there's lots of possibilities.

How to fix nginx throws 400 bad request headers on any header testing tools?

Just to clearify, in /etc/nginx/nginx.conf, you can put at the beginning of the file the line

error_log /var/log/nginx/error.log debug;

And then restart nginx:

sudo service nginx restart

That way you can detail what nginx is doing and why it is returning the status code 400.

Pie chart with jQuery

Tons of great suggestions here, just going to throw ZingChart onto the stack for good measure. We recently released a jQuery wrapper for the library that makes it even easier to build and customize charts. The CDN links are in the demo below.

I'm on the ZingChart team and we're here to answer any questions any of you might have!

_x000D_
_x000D_
$('#pie-chart').zingchart({_x000D_
  "data": {_x000D_
    "type": "pie",_x000D_
    "legend": {},_x000D_
    "series": [{_x000D_
      "values": [5]_x000D_
    }, {_x000D_
      "values": [10]_x000D_
    }, {_x000D_
      "values": [15]_x000D_
    }]_x000D_
  }_x000D_
});
_x000D_
<script src="http://cdn.zingchart.com/zingchart.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="http://cdn.zingchart.com/zingchart.jquery.min.js"></script>_x000D_
_x000D_
<div id="pie-chart"></div>
_x000D_
_x000D_
_x000D_

How do I call the base class constructor?

Use the name of the base class in an initializer-list. The initializer-list appears after the constructor signature before the method body and can be used to initialize base classes and members.

class Base
{
public:
  Base(char* name)
  {
     // ...
  }
};

class Derived : Base
{
public:
  Derived()
    : Base("hello")
  {
      // ...
  }
};

Or, a pattern used by some people is to define 'super' or 'base' yourself. Perhaps some of the people who favour this technique are Java developers who are moving to C++.

class Derived : Base
{
public:
  typedef Base super;
  Derived()
    : super("hello")
  {
      // ...
  }
};

How can I use "e" (Euler's number) and power operation in python 2.7

You can use exp(x) function of math library, which is same as e^x. Hence you may write your code as:

import math
x.append(1 - math.exp( -0.5 * (value1*value2)**2))

I have modified the equation by replacing 1/2 as 0.5. Else for Python <2.7, we'll have to explicitly type cast the division value to float because Python round of the result of division of two int as integer. For example: 1/2 gives 0 in python 2.7 and below.

less than 10 add 0 to number

You can always do

('0' + deg).slice(-2)

See slice():

You can also use negative numbers to select from the end of an array

Hence

('0' + 11).slice(-2) // '11'
('0' + 4).slice(-2)  // '04'

For ease of access, you could of course extract it to a function, or even extend Number with it:

Number.prototype.pad = function(n) {
    return new Array(n).join('0').slice((n || 2) * -1) + this;
}

Which will allow you to write:

c += deg.pad() + '° '; // "04° "

The above function pad accepts an argument specifying the length of the desired string. If no such argument is used, it defaults to 2. You could write:

deg.pad(4) // "0045"

Note the obvious drawback that the value of n cannot be higher than 11, as the string of 0's is currently just 10 characters long. This could of course be given a technical solution, but I did not want to introduce complexity in such a simple function. (Should you elect to, see alex's answer for an excellent approach to that).

Note also that you would not be able to write 2.pad(). It only works with variables. But then, if it's not a variable, you'll always know beforehand how many digits the number consists of.

How to implement reCaptcha for ASP.NET MVC?

Step 1: Client site integration

Paste this snippet before the closing </head> tag on your HTML template:

<script src='https://www.google.com/recaptcha/api.js'></script>

Paste this snippet at the end of the <form> where you want the reCAPTCHA widget to appear:

<div class="g-recaptcha" data-sitekey="your-site-key"></div>

Step 2: Server site integration

When your users submit the form where you integrated reCAPTCHA, you'll get as part of the payload a string with the name "g-recaptcha-response". In order to check whether Google has verified that user, send a POST request with these parameters:

URL : https://www.google.com/recaptcha/api/siteverify

secret : your secret key

response : The value of 'g-recaptcha-response'.

Now in action of your MVC app:

// return ActionResult if you want
    public string RecaptchaWork()
    {
        // Get recaptcha value
        var r = Request.Params["g-recaptcha-response"];
        // ... validate null or empty value if you want
        // then
        // make a request to recaptcha api
        using (var wc = new WebClient())
        {
            var validateString = string.Format(
                "https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}",
               "your_secret_key",    // secret recaptcha key
               r); // recaptcha value
             // Get result of recaptcha
            var recaptcha_result = wc.DownloadString(validateString);
            // Just check if request make by user or bot
            if (recaptcha_result.ToLower().Contains("false"))
            {
                 return "recaptcha false";
            }
        }
        // Do your work if request send from human :)
    }

commands not found on zsh

You can create a symlink in /usr/local/bin/

sudo ln -s $HOME/.composer/vendor/bin/homestead /usr/local/bin/homestead

use video as background for div

Pure CSS method

It is possible to center a video inside an element just like a cover sized background-image without JS using the object-fit attribute or CSS Transforms.

2021 answer: object-fit

As pointed in the comments, it is possible to achieve the same result without CSS transform, but using object-fit, which I think it's an even better option for the same result:

_x000D_
_x000D_
.video-container {
    height: 300px;
    width: 300px;
    position: relative;
}

.video-container video {
  width: 100%;
  height: 100%;
  position: absolute;
  object-fit: cover;
  z-index: 0;
}

/* Just styling the content of the div, the *magic* in the previous rules */
.video-container .caption {
  z-index: 1;
  position: relative;
  text-align: center;
  color: #dc0000;
  padding: 10px;
}
_x000D_
<div class="video-container">
    <video autoplay muted loop>
        <source src="https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" type="video/mp4" />
    </video>
    <div class="caption">
      <h2>Your caption here</h2>
    </div>
</div>
_x000D_
_x000D_
_x000D_


Previous answer: CSS Transform

You can set a video as a background to any HTML element easily thanks to transform CSS property.

Note that you can use the transform technique to center vertically and horizontally any HTML element.

_x000D_
_x000D_
.video-container {
  height: 300px;
  width: 300px;
  overflow: hidden;
  position: relative;
}

.video-container video {
  min-width: 100%;
  min-height: 100%;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translateX(-50%) translateY(-50%);
}

/* Just styling the content of the div, the *magic* in the previous rules */
.video-container .caption {
  z-index: 1;
  position: relative;
  text-align: center;
  color: #dc0000;
  padding: 10px;
}
_x000D_
<div class="video-container">
  <video autoplay muted loop>
    <source src="https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" type="video/mp4" />
  </video>
  <div class="caption">
    <h2>Your caption here</h2>
  </div>
</div>
_x000D_
_x000D_
_x000D_

Maximum concurrent Socket.IO connections

After making configurations, you can check by writing this command on terminal

sysctl -a | grep file

C# An established connection was aborted by the software in your host machine

An established connection was aborted by the software in your host machine

That is a boiler-plate error message, it comes out of Windows. The underlying error code is WSAECONNABORTED. Which really doesn't mean more than "connection was aborted". You have to be a bit careful about the "your host machine" part of the phrase. In the vast majority of Windows application programs, it is indeed the host that the desktop app is connected to that aborted the connection. Usually a server somewhere else.

The roles are reversed however when you implement your own server. Now you need to read the error message as "aborted by the application at the other end of the wire". Which is of course not uncommon when you implement a server, client programs that use your server are not unlikely to abort a connection for whatever reason. It can mean that a fire-wall or a proxy terminated the connection but that's not very likely since they typically would not allow the connection to be established in the first place.

You don't really know why a connection was aborted unless you have insight what is going on at the other end of the wire. That's of course hard to come by. If your server is reachable through the Internet then don't discount the possibility that you are being probed by a port scanner. Or your customers, looking for a game cheat.

Difference between Subquery and Correlated Subquery

A subquery is a select statement that is embedded in a clause of another select statement.

EX:

select ename, sal 
from emp  where sal > (select sal 
                       from emp where ename ='FORD');

A Correlated subquery is a subquery that is evaluated once for each row processed by the outer query or main query. Execute the Inner query based on the value fetched by the Outer query all the values returned by the main query are matched. The INNER Query is driven by the OUTER Query.

Ex:

select empno,sal,deptid 
from emp e 
where sal=(select avg(sal) 
           from emp where deptid=e.deptid);

DIFFERENCE

The inner query executes first and finds a value, the outer query executes once using the value from the inner query (subquery)

Fetch by the outer query, execute the inner query using the value of the outer query, use the values resulting from the inner query to qualify or disqualify the outer query (correlated)

For more information : http://www.oraclegeneration.com/2014/01/sql-interview-questions.html

Your branch is ahead of 'origin/master' by 3 commits

There is nothing to fix. You simply have made 3 commits and haven't moved them to the remote branch yet. There are several options, depending on what you want to do:

  • git push: move your changes to the remote (this might get rejected if there are already other changes on the remote)
  • do nothing and keep coding, sync another day
  • git pull: get the changes (if any) from the remote and merge them into your changes
  • git pull --rebase: as above, but try to redo your commits on top of the remote changes

You are in a classical situation (although usually you wouldn't commit a lot on master in most workflows). Here is what I would normally do: Review my changes. Maybe do a git rebase --interactive to do some cosmetics on them, drop the ones that suck, reorder them to make them more logical. Now move them to the remote with git push. If this gets rejected because my local branch is not up to date: git pull --rebase to redo my work on top of the most recent changes and git push again.

How does EL empty operator work in JSF?

From EL 2.2 specification (get the one below "Click here to download the spec for evaluation"):

1.10 Empty Operator - empty A

The empty operator is a prefix operator that can be used to determine if a value is null or empty.

To evaluate empty A

  • If A is null, return true
  • Otherwise, if A is the empty string, then return true
  • Otherwise, if A is an empty array, then return true
  • Otherwise, if A is an empty Map, return true
  • Otherwise, if A is an empty Collection, return true
  • Otherwise return false

So, considering the interfaces, it works on Collection and Map only. In your case, I think Collection is the best option. Or, if it's a Javabean-like object, then Map. Either way, under the covers, the isEmpty() method is used for the actual check. On interface methods which you can't or don't want to implement, you could throw UnsupportedOperationException.

How to force the browser to reload cached CSS and JavaScript files

For a Java Servlet environment, you can look at the Jawr library. The features page explains how it handles caching:

Jawr will try its best to force your clients to cache the resources. If a browser asks if a file changed, a 304 (not modified) header is sent back with no content. On the other hand, with Jawr you will be 100% sure that new versions of your bundles are downloaded by all clients. Every URL to your resources will include an automatically generated, content-based prefix that changes automatically whenever a resource is updated. Once you deploy a new version, the URL to the bundle will change as well so it will be impossible that a client uses an older, cached version.

The library also does JavaScript and CSS minification, but you can turn that off if you don't want it.

How to count duplicate rows in pandas dataframe?

df = pd.DataFrame({'one' : pd.Series([1., 1, 1, 3]), 'two' : pd.Series([1., 2., 1, 3] ), 'three' : pd.Series([1., 2., 1, 2] )})
df['str_list'] = df.apply(lambda row: ' '.join([str(int(val)) for val in row]), axis=1)
df1 = pd.DataFrame(df['str_list'].value_counts().values, index=df['str_list'].value_counts().index, columns=['Count'])

Produces:

>>> df1
       Count
1 1 1      2
3 2 3      1
1 2 2      1

If the index values must be a list, you could take the above code a step further with:

df1.index = df1.index.str.split()

Produces:

           Count
[1, 1, 1]      2
[3, 2, 3]      1
[1, 2, 2]      1

Manually install Gradle and use it in Android Studio

(There are 2 solutions mentioned in existing answers that might work, but the preferred one - manually download gradle for gradlew, is lack of essential details, and cause it fail. So, I would add a summary with missing details to save the unnecessary time wasted, in case others encounter into the same issue.)

There are 2 possible solutions:


Solution A: Use location gradle, and delete gradlew related files. (not recommend)

Refer to this answer from this post: https://stackoverflow.com/a/29198101/

Tips:

  • I tried, it works, though this is not suggested for gradle use in general.
  • And, with this solution, each time open project, android-studio will ask to confirm whether to use gradlew instead, it's kinda annoying.

Solution B: Download gradle distribution manually for gradlew. (recommended)

Android Studio will download gradle to sub dir named by a hash.
To download manually, need to download to the exact sub dir named by the hash.

Steps:

  • Get the hash.
    • Start android-studio.
    • Create a basic project.
    • Then it will create the hash, and start to download gradle.
      e.g .gradle/wrapper/dists/gradle-4.10.1-all/455itskqi2qtf0v2sja68alqd/
    • Close android-studio.
    • Find the download process, by android-studio.
      e.g ps -aux grep | android
    • Kill all the related android processes.
    • Remove the blank project.
  • Download gradle by hand.
  • Start Android Studio and try again.
    • Create a new blank project again.
    • Then it shouldn't need to download gradle again.
    • It will uncompress gradle in the the same dir.
      e.g .gradle/wrapper/dists/gradle-4.10.1-all/455itskqi2qtf0v2sja68alqd/gradle-4.10.1/
    • And starts to sync dependencies, indexing, and build.

Tips:

  • After restart Android Studio & creating blank project again, if you see it says waiting for other process to download the distribution.
    That means you didn't kill the previous download process, kill it first, then remove blank project, then create a new project to confirm again.
  • Each version of Android Studio might use different gradle version, thus might need to repeat this process once, when Android Studio is upgraded.

BTW:

  • Here is the dir layout on my Linux
    (For Android Studio 3.3.1, which use gradle 4.10.1)

    eric@eric-pc:~/.gradle/wrapper$ tree -L 4

    .
    +-- dists
        +-- gradle-4.10.1-all
            +-- 455itskqi2qtf0v2sja68alqd
                +-- gradle-4.10.1
                +-- gradle-4.10.1-all.zip
                +-- gradle-4.10.1-all.zip.lck
                +-- gradle-4.10.1-all.zip.ok
    
    

Suggestions to Android-Studio

  • Since it's so slow when download gradle distrbution within Android Studio.
    It's better to provide an option to choose local gradle installation dir or .zip file to be used by gradlew.

How can I reverse the order of lines in a file?

For cross OS (i.e. OSX, Linux) solution that may use tac inside a shell script use homebrew as others have mentioned above, then just alias tac like so:

Install lib

For MacOS

brew install coreutils

For linux debian

sudo apt-get update
sudo apt-get install coreutils 

Then add alias

echo "alias tac='gtac'" >> ~/.bash_aliases (or wherever you load aliases)
source ~/.bash_aliases
tac myfile.txt

How to open the Google Play Store directly from my Android application?

Some of the answers to this question are outdated.

What worked for me (in 2020) was to explicitly tell the intent to skip the chooser and directly open the play store app, according to this link:

"If you want to link to your products from an Android app, create an Intent that opens a URL. As you configure this intent, pass "com.android.vending" into Intent.setPackage() so that users see your app's details in the Google Play Store app instead of a chooser."

This is the Kotlin code I used to direct users to viewing the app containing the package name com.google.android.apps.maps in Google Play:

val intent = Intent(Intent.ACTION_VIEW).apply {
               data = Uri.parse("http://play.google.com/store/apps/details?id=com.google.android.apps.maps")
               setPackage("com.android.vending")
            }
            startActivity(intent)

I hope that helps someone!

How can I remove space (margin) above HTML header?

It is probably the h1 tag causing the problem. Applying margin: 0; should fix the problem.

But you should use a CSS reset for every new project to eliminate browser consistencies and problems like yours. Probably the most famous one is Eric Meyer's: http://meyerweb.com/eric/tools/css/reset/

Can I get image from canvas element and use it in img src tag?

I´ve found two problems with your Fiddle, one of the problems is first in Zeta´s answer.

the method is not toDataUrl(); is toDataURL(); and you forgot to store the canvas in your variable.

So the Fiddle now works fine http://jsfiddle.net/gfyWK/12/

I hope this helps!

Extracting specific selected columns to new DataFrame as a copy

There is a way of doing this and it actually looks similar to R

new = old[['A', 'C', 'D']].copy()

Here you are just selecting the columns you want from the original data frame and creating a variable for those. If you want to modify the new dataframe at all you'll probably want to use .copy() to avoid a SettingWithCopyWarning.

An alternative method is to use filter which will create a copy by default:

new = old.filter(['A','B','D'], axis=1)

Finally, depending on the number of columns in your original dataframe, it might be more succinct to express this using a drop (this will also create a copy by default):

new = old.drop('B', axis=1)

How do I reverse a C++ vector?

All containers offer a reversed view of their content with rbegin() and rend(). These two functions return so-calles reverse iterators, which can be used like normal ones, but it will look like the container is actually reversed.

#include <vector>
#include <iostream>

template<class InIt>
void print_range(InIt first, InIt last, char const* delim = "\n"){
  --last;
  for(; first != last; ++first){
    std::cout << *first << delim;
  }
  std::cout << *first;
}

int main(){
  int a[] = { 1, 2, 3, 4, 5 };
  std::vector<int> v(a, a+5);
  print_range(v.begin(), v.end(), "->");
  std::cout << "\n=============\n";
  print_range(v.rbegin(), v.rend(), "<-");
}

Live example on Ideone. Output:

1->2->3->4->5
=============
5<-4<-3<-2<-1

Clear git local cache

To remove cached .idea/ directory. e.g. git rm -r --cached .idea

Unicode (UTF-8) reading and writing to files in Python

To read in an Unicode string and then send to HTML, I did this:

fileline.decode("utf-8").encode('ascii', 'xmlcharrefreplace')

Useful for python powered http servers.

How can I send large messages with Kafka (over 15MB)?

The answer from @laughing_man is quite accurate. But still, I wanted to give a recommendation which I learned from Kafka expert Stephane Maarek.

Kafka isn’t meant to handle large messages.

Your API should use cloud storage (Ex AWS S3), and just push to Kafka or any message broker a reference of S3. You must find somewhere to persist your data, maybe it’s a network drive, maybe it’s whatever, but it shouldn't be message broker.

Now, if you don’t want to go with the above solution

The message max size is 1MB (the setting in your brokers is called message.max.bytes) Apache Kafka. If you really needed it badly, you could increase that size and make sure to increase the network buffers for your producers and consumers.

And if you really care about splitting your message, make sure each message split has the exact same key so that it gets pushed to the same partition, and your message content should report a “part id” so that your consumer can fully reconstruct the message.

You can also explore compression, if your message is text-based (gzip, snappy, lz4 compression) which may reduce the data size, but not magically.

Again, you have to use an external system to store that data and just push an external reference to Kafka. That is a very common architecture and one you should go with and widely accepted.

Keep that in mind Kafka works best only if the messages are huge in amount but not in size.

Source: https://www.quora.com/How-do-I-send-Large-messages-80-MB-in-Kafka

Convert from ASCII string encoded in Hex to plain ASCII?

In Python 2:

>>> "7061756c".decode("hex")
'paul'

In Python 3:

>>> bytes.fromhex('7061756c').decode('utf-8')
'paul'

How to return a list of keys from a Hash Map?

map.keySet()

will return you all the keys. If you want the keys to be sorted, you might consider a TreeMap

Django development IDE

I am beginning to enjoy working with Aptana Studios + PyDev (and other) plugins for all sorts of web application development. As you can tell, it is built on top of the powerful Eclipse, but is tailor-designed to focus on web application development.

Eclipse JPA Project Change Event Handler (waiting)

I had the same problem and I ended up finding out that this seems to be a known bug in DALI (Eclipse Java Persistence Tools) since at least eclipse 3.8 which could cause the save action in the java editor to be extremly slow.

Since this hasn't been fully resolved in Kepler (20130614-0229) yet and because I don't need JPT/DALI in my eclipse I ended up manually removing the org.eclipse.jpt features and plugins.

What I did was:

1.) exit eclipse

2.) go to my eclipse install directory

cd eclipse

and execute these steps:

*nix:

mkdir disabled
mkdir disabled/features disabled/plugins

mv plugins/org.eclipse.jpt.* disabled/plugins
mv features/org.eclipse.jpt.* disabled/features

windows:

mkdir disabled
mkdir disabled\features 
mkdir disabled\plugins

move plugins\org.eclipse.jpt.* disabled\plugins
for /D /R %D in (features\org.eclipse.jpt.*) do move %D disabled\features

3.) Restart eclipse.

After startup and on first use eclipse may warn you that you need to reconfigure your content-assist. Do this in your preferences dialog.

Done.

After uninstalling DALI/JPT my eclipse feels good again. No more blocked UI and waiting for seconds when saving a file.

How do I output the results of a HiveQL query to CSV?

I had a similar issue and this is how I was able to address it.

Step 1 - Loaded the data from Hive table into another table as follows

DROP TABLE IF EXISTS TestHiveTableCSV;
CREATE TABLE TestHiveTableCSV 
ROW FORMAT DELIMITED 
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n' AS
SELECT Column List FROM TestHiveTable;

Step 2 - Copied the blob from Hive warehouse to the new location with appropriate extension

Start-AzureStorageBlobCopy
-DestContext $destContext 
-SrcContainer "Source Container"
-SrcBlob "hive/warehouse/TestHiveTableCSV/000000_0"
-DestContainer "Destination Container"
-DestBlob "CSV/TestHiveTable.csv"

Generating a PDF file from React Components

Only few steps. We can download or generate PDF from our HTML page or we can generate PDF of specific div from a HTML page.

Steps : HTML -> Image (PNG or JPEG) -> PDF

Please Follow the below steps,

Step 1 :-

npm install --save html-to-image
npm install jspdf --save

Step 2 :-

/* ES6 */
import * as htmlToImage from 'html-to-image';
import { toPng, toJpeg, toBlob, toPixelData, toSvg } from 'html-to-image';
 
/* ES5 */
var htmlToImage = require('html-to-image');

-------------------------
import { jsPDF } from "jspdf";

Step 3 :-

   ******  With out PDF properties given below  ******

 htmlToImage.toPng(document.getElementById('myPage'), { quality: 0.95 })
        .then(function (dataUrl) {
          var link = document.createElement('a');
          link.download = 'my-image-name.jpeg';
          const pdf = new jsPDF();          
          pdf.addImage(dataUrl, 'PNG', 0, 0);
          pdf.save("download.pdf"); 
        });


    ******  With PDF properties given below ******

    htmlToImage.toPng(document.getElementById('myPage'), { quality: 0.95 })
        .then(function (dataUrl) {
          var link = document.createElement('a');
          link.download = 'my-image-name.jpeg';
          const pdf = new jsPDF();
          const imgProps= pdf.getImageProperties(dataUrl);
          const pdfWidth = pdf.internal.pageSize.getWidth();
          const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;
          pdf.addImage(dataUrl, 'PNG', 0, 0,pdfWidth, pdfHeight);
          pdf.save("download.pdf"); 
        });

I think this is helpful. Please try

Sending data from HTML form to a Python script in Flask

You need a Flask view that will receive POST data and an HTML form that will send it.

from flask import request

@app.route('/addRegion', methods=['POST'])
def addRegion():
    ...
    return (request.form['projectFilePath'])
<form action="{{ url_for('addRegion') }}" method="post">
    Project file path: <input type="text" name="projectFilePath"><br>
    <input type="submit" value="Submit">
</form>

Add a tooltip to a div

I have developed three type fade effects :

_x000D_
_x000D_
/* setup tooltips */_x000D_
    .tooltip {_x000D_
      position: relative;_x000D_
    }_x000D_
    .tooltip:before,_x000D_
    .tooltip:after {_x000D_
      display: block;_x000D_
      opacity: 0;_x000D_
      pointer-events: none;_x000D_
      position: absolute;_x000D_
    }_x000D_
    .tooltip:after {_x000D_
     border-right: 6px solid transparent;_x000D_
     border-bottom: 6px solid rgba(0,0,0,.75); _x000D_
      border-left: 6px solid transparent;_x000D_
      content: '';_x000D_
      height: 0;_x000D_
        top: 20px;_x000D_
        left: 20px;_x000D_
      width: 0;_x000D_
    }_x000D_
    .tooltip:before {_x000D_
      background: rgba(0,0,0,.75);_x000D_
      border-radius: 2px;_x000D_
      color: #fff;_x000D_
      content: attr(data-title);_x000D_
      font-size: 14px;_x000D_
      padding: 6px 10px;_x000D_
        top: 26px;_x000D_
      white-space: nowrap;_x000D_
    }_x000D_
_x000D_
    /* the animations */_x000D_
    /* fade */_x000D_
    .tooltip.fade:after,_x000D_
    .tooltip.fade:before {_x000D_
      transform: translate3d(0,-10px,0);_x000D_
      transition: all .15s ease-in-out;_x000D_
    }_x000D_
    .tooltip.fade:hover:after,_x000D_
    .tooltip.fade:hover:before {_x000D_
      opacity: 1;_x000D_
      transform: translate3d(0,0,0);_x000D_
    }_x000D_
_x000D_
    /* expand */_x000D_
    .tooltip.expand:before {_x000D_
      transform: scale3d(.2,.2,1);_x000D_
      transition: all .2s ease-in-out;_x000D_
    }_x000D_
    .tooltip.expand:after {_x000D_
      transform: translate3d(0,6px,0);_x000D_
      transition: all .1s ease-in-out;_x000D_
    }_x000D_
    .tooltip.expand:hover:before,_x000D_
    .tooltip.expand:hover:after {_x000D_
      opacity: 1;_x000D_
      transform: scale3d(1,1,1);_x000D_
    }_x000D_
    .tooltip.expand:hover:after {_x000D_
      transition: all .2s .1s ease-in-out;_x000D_
    }_x000D_
_x000D_
    /* swing */_x000D_
    .tooltip.swing:before,_x000D_
    .tooltip.swing:after {_x000D_
      transform: translate3d(0,30px,0) rotate3d(0,0,1,60deg);_x000D_
      transform-origin: 0 0;_x000D_
      transition: transform .15s ease-in-out, opacity .2s;_x000D_
    }_x000D_
    .tooltip.swing:after {_x000D_
      transform: translate3d(0,60px,0);_x000D_
      transition: transform .15s ease-in-out, opacity .2s;_x000D_
    }_x000D_
    .tooltip.swing:hover:before,_x000D_
    .tooltip.swing:hover:after {_x000D_
      opacity: 1;_x000D_
      transform: translate3d(0,0,0) rotate3d(1,1,1,0deg);_x000D_
    }_x000D_
_x000D_
    /* basic styling: has nothing to do with tooltips: */_x000D_
    h1 {_x000D_
      padding-left: 50px;_x000D_
    }_x000D_
    ul {_x000D_
      margin-bottom: 40px;_x000D_
    }_x000D_
    li {_x000D_
      cursor: pointer; _x000D_
      display: inline-block; _x000D_
      padding: 0 10px;_x000D_
    }
_x000D_
 <h1>FADE</h1>_x000D_
_x000D_
      <div class="tooltip fade" data-title="Hypertext Markup Language">_x000D_
      <label>Name</label>_x000D_
      <input type="text"/>_x000D_
      </div>_x000D_
      _x000D_
_x000D_
    <h1>EXPAND</h1>_x000D_
_x000D_
      <div class="tooltip expand" data-title="Hypertext Markup Language">_x000D_
      <label>Name</label>_x000D_
      <input type="text"/>_x000D_
      </div>_x000D_
      _x000D_
_x000D_
    <h1>SWING</h1>_x000D_
_x000D_
      <div class="tooltip swing" data-title="Hypertext Markup Language"> _x000D_
      <label>Name</label>_x000D_
      <input type="text"/>_x000D_
      </div>_x000D_
     
_x000D_
_x000D_
_x000D_

Get selected value from combo box in C# WPF

Write it like this:

String CmbTitle = (cmb.SelectedItem as ComboBoxItem).Content.ToString()

Difference between "as $key => $value" and "as $value" in PHP foreach

if the array looks like:

  • $featured["fruit"] = "orange";
  • $featured["fruit"] = "banana";
  • $featured["vegetable"] = "carrot";

the $key will hold the type (fruit or vegetable) for each array value (orange, banana or carrot)

How can I strip all punctuation from a string in JavaScript using regex?

str = str.replace(/[^\w\s]|_/g, "")
         .replace(/\s+/g, " ");

Removes everything except alphanumeric characters and whitespace, then collapses multiple adjacent characters to single spaces.

Detailed explanation:

  1. \w is any digit, letter, or underscore.
  2. \s is any whitespace.
  3. [^\w\s] is anything that's not a digit, letter, whitespace, or underscore.
  4. [^\w\s]|_ is the same as #3 except with the underscores added back in.

how to fetch array keys with jQuery?

Use an object (key/value pairs, the nearest JavaScript has to an associative array) for this and not the array object. Other than that, I believe that is the most elegant way

var foo = {};
foo['alfa'] = "first item";
foo['beta'] = "second item";

for (var key in foo) {
        console.log(key);
}

Note: JavaScript doesn't guarantee any particular order for the properties. So you cannot expect the property that was defined first to appear first, it might come last.

EDIT:

In response to your comment, I believe that this article best sums up the cases for why arrays in JavaScript should not be used in this fashion -

Differences between CHMOD 755 vs 750 permissions set

0755 = User:rwx Group:r-x World:r-x

0750 = User:rwx Group:r-x World:--- (i.e. World: no access)

r = read
w = write
x = execute (traverse for directories)

How to make a <ul> display in a horizontal row

#ul_top_hypers li {
  display: flex;
}

How can I inject a property value into a Spring Bean which was configured using annotations?

If you are stuck using Spring 2.5 you could define a bean for each of your properties and inject them using qualifiers. Like this:

  <bean id="someFile" class="java.io.File">
    <constructor-arg value="${someFile}"/>
  </bean>

and

@Service
public class Thing
      public Thing(@Qualifier("someFile") File someFile) {
...

Its not super readable but it gets the job done.

Should I use Java's String.format() if performance is important?

I took hhafez code and added a memory test:

private static void test() {
    Runtime runtime = Runtime.getRuntime();
    long memory;
    ...
    memory = runtime.freeMemory();
    // for loop code
    memory = memory-runtime.freeMemory();

I run this separately for each approach, the '+' operator, String.format and StringBuilder (calling toString()), so the memory used will not be affected by other approaches. I added more concatenations, making the string as "Blah" + i + "Blah"+ i +"Blah" + i + "Blah".

The result are as follow (average of 5 runs each):
Approach       Time(ms)  Memory allocated (long)
'+' operator     747           320,504
String.format  16484       373,312
StringBuilder  769           57,344

We can see that String '+' and StringBuilder are practically identical time-wise, but StringBuilder is much more efficient in memory use. This is very important when we have many log calls (or any other statements involving strings) in a time interval short enough so the Garbage Collector won't get to clean the many string instances resulting of the '+' operator.

And a note, BTW, don't forget to check the logging level before constructing the message.

Conclusions:

  1. I'll keep on using StringBuilder.
  2. I have too much time or too little life.

Embed image in a <button> element

Buttons don't directly support images. Moreover the way you're doing is for links ()

Images are added over buttons using the BACKGROUND-IMAGE property in style

you can also specify the repeats and other properties using tag

For example: a basic image added to a button would have this code:

    <button style="background-image:url(myImage.png)">

Peace

How can I check if a user is logged-in in php?

You may do a session and place it:

// Start session
session_start();

// Check do the person logged in
if($_SESSION['username']==NULL){
    // Haven't log in
    echo "You haven't log in";
}else{
    // Logged in
    echo "Successfully logged in!";
}

Note: you must make a form which contain $_SESSION['username'] = $login_input_username;

Dynamically Add Variable Name Value Pairs to JSON Object

With ECMAScript 6 there is a better way.

You can use computed property names in object property definitions, for example:

var name1 = 'John'; 
var value1 = '42'; 
var name2 = 'Sarah'; 
var value2 = '35';

var ipID = { 
             [name1] : value1, 
             [name2] : value2 
           }

This is equivalent to the following, where you have variables for the property names.

var ipID = { 
             John: '42', 
             Sarah: '35' 
           }

What are access specifiers? Should I inherit with private, protected or public?

The explanation from Scott Meyers in Effective C++ might help understand when to use them:

Public inheritance should model "is-a relationship," whereas private inheritance should be used for "is-implemented-in-terms-of" - so you don't have to adhere to the interface of the superclass, you're just reusing the implementation.

Remove decimal values using SQL query

Here column name must be decimal.

select CAST(columnname AS decimal(38,0)) from table

Argument list too long error for rm, cp, mv commands

you can use this commend

find -name "*.pdf"  -delete

How to get "wc -l" to print just the number of lines without file name?

cat file.txt | wc -l

According to the man page (for the BSD version, I don't have a GNU version to check):

If no files are specified, the standard input is used and no file name is displayed. The prompt will accept input until receiving EOF, or [^D] in most environments.

python paramiko ssh

The code of @ThePracticalOne is great for showing the usage except for one thing: Somtimes the output would be incomplete.(session.recv_ready() turns true after the if session.recv_ready(): while session.recv_stderr_ready() and session.exit_status_ready() turned true before entering next loop)

so my thinking is to retrieving the data when it is ready to exit the session.

while True:
if session.exit_status_ready():
while True:
    while True:
        print "try to recv stdout..."
        ret = session.recv(nbytes)
        if len(ret) == 0:
            break
        stdout_data.append(ret)

    while True:
        print "try to recv stderr..."
        ret = session.recv_stderr(nbytes)
        if len(ret) == 0:
            break
        stderr_data.append(ret)
    break

How do I execute code AFTER a form has loaded?

This an old question and depends more upon when you need to start your routines. Since no one wants a null reference exception it is always best to check for null first then use as needed; that alone may save you a lot of grief.

The most common reason for this type of question is when a container or custom control type attempts to access properties initialized outside of a custom class where those properties have not yet been initialized thus potentially causing null values to populate and can even cause a null reference exceptions on object types. It means your class is running before it is fully initialized - before you have finished setting your properties etc. Another possible reason for this type of question is when to perform custom graphics.

To best answer the question about when to start executing code following the form load event is to monitor the WM_Paint message or hook directly in to the paint event itself. Why? The paint event only fires when all modules have fully loaded with respect to your form load event. Note: This.visible == true is not always true when it is set true so it is not used at all for this purpose except to hide a form.

The following is a complete example of how to start executing you code following the form load event. It is recommended that you do not unnecessarily tie up the paint message loop so we'll create an event that will start executing your code outside that loop.

using System.Windows.Forms;

namespace MyProgramStartingPlaceExample {

/// <summary>
/// Main UI form object
/// </summary>
public class Form1 : Form
{

    /// <summary>
    /// Main form load event handler
    /// </summary>
    public Form1()
    {
        // Initialize ONLY. Setup your controls and form parameters here. Custom controls should wait for "FormReady" before starting up too.
        this.Text = "My Program title before form loaded";
        // Size need to see text. lol
        this.Width = 420;

        // Setup the sub or fucntion that will handle your "start up" routine
        this.StartUpEvent += StartUPRoutine;

        // Optional: Custom control simulation startup sequence:
        // Define your class or control in variable. ie. var MyControlClass new CustomControl;
        // Setup your parameters only. ie. CustomControl.size = new size(420, 966); Do not validate during initialization wait until "FormReady" is set to avoid possible null values etc. 
        // Inside your control or class have a property and assign it as bool FormReady - do not validate anything until it is true and you'll be good! 
    }

    /// <summary>
    /// The main entry point for the application which sets security permissions when set.
    /// </summary>
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }


    #region "WM_Paint event hooking with StartUpEvent"            
    //
    // Create a delegate for our "StartUpEvent"
    public delegate void StartUpHandler();
    //
    // Create our event handle "StartUpEvent"
    public event StartUpHandler StartUpEvent;
    //
    // Our FormReady will only be set once just he way we intendded
    // Since it is a global variable we can poll it else where as well to determine if we should begin code execution !!
    bool FormReady;
    //
    // The WM_Paint message handler: Used mostly to paint nice things to controls and screen
    protected override void OnPaint(PaintEventArgs e)
    {
        // Check if Form is ready for our code ?
        if (FormReady == false) // Place a break point here to see the initialized version of the title on the form window
        {
            // We only want this to occur once for our purpose here.
            FormReady = true;
            //
            // Fire the start up event which then will call our "StartUPRoutine" below.
            StartUpEvent();
        }
        //
        // Always call base methods unless overriding the entire fucntion
        base.OnPaint(e);
    }
    #endregion


    #region "Your StartUp event Entry point"
    //
    // Begin executuing your code here to validate properties etc. and to run your program. Enjoy!
    // Entry point is just following the very first WM_Paint message - an ideal starting place following form load
    void StartUPRoutine()
    {
        // Replace the initialized text with the following
        this.Text = "Your Code has executed after the form's load event";
        //
        // Anyway this is the momment when the form is fully loaded and ready to go - you can also use these methods for your classes to synchronize excecution using easy modifications yet here is a good starting point. 
        // Option: Set FormReady to your controls manulaly ie. CustomControl.FormReady = true; or subscribe to the StartUpEvent event inside your class and use that as your entry point for validating and unleashing its code.
        //
        // Many options: The rest is up to you!
    }
    #endregion

}

}

Html.Raw() in ASP.NET MVC Razor view

Html.Raw() returns IHtmlString, not the ordinary string. So, you cannot write them in opposite sides of : operator. Remove that .ToString() calling

@{int count = 0;}
@foreach (var item in Model.Resources)
{
    @(count <= 3 ? Html.Raw("<div class=\"resource-row\">"): Html.Raw("")) 
    // some code
    @(count <= 3 ? Html.Raw("</div>") : Html.Raw("")) 
    @(count++)

}

By the way, returning IHtmlString is the way MVC recognizes html content and does not encode it. Even if it hasn't caused compiler errors, calling ToString() would destroy meaning of Html.Raw()

Parsing JSON in Spring MVC using Jackson JSON

I'm using json lib from http://json-lib.sourceforge.net/
json-lib-2.1-jdk15.jar

import net.sf.json.JSONObject;
...

public void send()
{
    //put attributes
    Map m = New HashMap();
    m.put("send_to","[email protected]");
    m.put("email_subject","this is a test email");
    m.put("email_content","test email content");

    //generate JSON Object
    JSONObject json = JSONObject.fromObject(content);
    String message = json.toString();
    ...
}

public void receive(String jsonMessage)
{
    //parse attributes
    JSONObject json = JSONObject.fromObject(jsonMessage);
    String to = (String) json.get("send_to");
    String title = (String) json.get("email_subject");
    String content = (String) json.get("email_content");
    ...
}

More samples here http://json-lib.sourceforge.net/usage.html

For loop example in MySQL

drop table if exists foo;
create table foo
(
id int unsigned not null auto_increment primary key,
val smallint unsigned not null default 0
)
engine=innodb;

drop procedure if exists load_foo_test_data;

delimiter #
create procedure load_foo_test_data()
begin

declare v_max int unsigned default 1000;
declare v_counter int unsigned default 0;

  truncate table foo;
  start transaction;
  while v_counter < v_max do
    insert into foo (val) values ( floor(0 + (rand() * 65535)) );
    set v_counter=v_counter+1;
  end while;
  commit;
end #

delimiter ;

call load_foo_test_data();

select * from foo order by id;

Python 2.6: Class inside a Class?

I think you are confusing objects and classes. A class inside a class looks like this:

class Foo(object):
    class Bar(object):
        pass

>>> foo = Foo()
>>> bar = Foo.Bar()

But it doesn't look to me like that's what you want. Perhaps you are after a simple containment hierarchy:

class Player(object):
    def __init__(self, ... airplanes ...) # airplanes is a list of Airplane objects
        ...
        self.airplanes = airplanes
        ...

class Airplane(object):
    def __init__(self, ... flights ...) # flights is a list of Flight objects
        ...
        self.flights = flights
        ...

class Flight(object):
    def __init__(self, ... duration ...)
        ...
        self.duration = duration
        ...

Then you can build and use the objects thus:

player = Player(...[
    Airplane(... [
        Flight(...duration=10...),
        Flight(...duration=15...),
        ] ... ),
    Airplane(...[
        Flight(...duration=20...),
        Flight(...duration=11...),
        Flight(...duration=25...),
        ]...),
    ])

player.airplanes[5].flights[6].duration = 5

Node.js Generate html

Node.js does not run in a browser, therefore you will not have a document object available. Actually, you will not even have a DOM tree at all. If you are a bit confused at this point, I encourage you to read more about it before going further.

There are a few methods you can choose from to do what you want.


Method 1: Serving the file directly via HTTP

Because you wrote about opening the file in the browser, why don't you use a framework that will serve the file directly as an HTTP service, instead of having a two-step process? This way, your code will be more dynamic and easily maintainable (not mentioning your HTML always up-to-date).

There are plenty frameworks out there for that :

The most basic way you could do what you want is this :

var http = require('http');

http.createServer(function (req, res) {
  var html = buildHtml(req);

  res.writeHead(200, {
    'Content-Type': 'text/html',
    'Content-Length': html.length,
    'Expires': new Date().toUTCString()
  });
  res.end(html);
}).listen(8080);

function buildHtml(req) {
  var header = '';
  var body = '';

  // concatenate header string
  // concatenate body string

  return '<!DOCTYPE html>'
       + '<html><head>' + header + '</head><body>' + body + '</body></html>';
};

And access this HTML with http://localhost:8080 from your browser.

(Edit: you could also serve them with a small HTTP server.)


Method 2: Generating the file only

If what you are trying to do is simply generating some HTML files, then go simple. To perform IO access on the file system, Node has an API for that, documented here.

var fs = require('fs');

var fileName = 'path/to/file';
var stream = fs.createWriteStream(fileName);

stream.once('open', function(fd) {
  var html = buildHtml();

  stream.end(html);
});

Note: The buildHtml function is exactly the same as in Method 1.


Method 3: Dumping the file directly into stdout

This is the most basic Node.js implementation and requires the invoking application to handle the output itself. To output something in Node (ie. to stdout), the best way is to use console.log(message) where message is any string, or object, etc.

var html = buildHtml();

console.log(html);

Note: The buildHtml function is exactly the same as in Method 1 (again)

If your script is called html-generator.js (for example), in Linux/Unix based system, simply do

$ node html-generator.js > path/to/file

Conclusion

Because Node is a modular system, you can even put the buildHtml function inside it's own module and simply write adapters to handle the HTML however you like. Something like

var htmlBuilder = require('path/to/html-builder-module');

var html = htmlBuilder(options);
...

You have to think "server-side" and not "client-side" when writing JavaScript for Node.js; you are not in a browser and/or limited to a sandbox, other than the V8 engine.

Extra reading, learn about npm. Hope this helps.

Does VBA have Dictionary Structure?

All the others have already mentioned the use of the scripting.runtime version of the Dictionary class. If you are unable to use this DLL you can also use this version, simply add it to your code.

https://github.com/VBA-tools/VBA-Dictionary/blob/master/Dictionary.cls

It is identical to Microsoft's version.

How to unlock a file from someone else in Team Foundation Server

You need to be project admin or to have tfs account (user name/password) of the user who had locked the file.

in Visual Studio 2019:

  • Menu > View > Terminal (ctrl+`)
  • Wait until developer powershell or command prompt loads to the cursor like this:
    Drive:\your solution path>
  • you must undo changes to unlock the file:
    tf vc undo /workspace:"workspacename;worksapceowner" "$/path/[file.extension][*]" [/recursive] [/login:"user name,password"]
    example:-
    tf vc undo /workspace:"DESKTOP-F6BN2GHTKQ8;Johne123" "$/mywebsite/mywebsite/appsettings.json"

Best Way to View Generated Source of Webpage?

If you load the document in Chrome, the Developer|Elements view will show you the HTML as fiddled by your JS code. It's not directly HTML text and you have to open (unfold) any elements of interest, but you effectively get to inspect the generated HTML.

Should composer.lock be committed to version control?

If you update your libs, you want to commit the lockfile too. It basically states that your project is locked to those specific versions of the libs you are using.

If you commit your changes, and someone pulls your code and updates the dependencies, the lockfile should be unmodified. If it is modified, it means that you have a new version of something.

Having it in the repository assures you that each developer is using the same versions.

How to serialize a JObject without the formatting?

Call JObject's ToString(Formatting.None) method.

Alternatively if you pass the object to the JsonConvert.SerializeObject method it will return the JSON without formatting.

Documentation: Write JSON text with JToken.ToString

Merge 2 arrays of objects

Merging two arrays:

var arr1 = new Array({name: "lang", value: "English"}, {name: "age", value: "18"});
var arr2 = new Array({name : "childs", value: '5'}, {name: "lang", value: "German"});
var result=arr1.concat(arr2);
// result: [{name: "lang", value: "English"}, {name: "age", value: "18"}, {name : "childs", value: '5'}, {name: "lang", value: "German"}]

Merging two arrays without duplicated values for 'name':

var arr1 = new Array({name: "lang", value: "English"}, {name: "age", value: "18"});
var arr2 = new Array({name : "childs", value: '5'}, {name: "lang", value: "German"});
var i,p,obj={},result=[];
for(i=0;i<arr1.length;i++)obj[arr1[i].name]=arr1[i].value;
for(i=0;i<arr2.length;i++)obj[arr2[i].name]=arr2[i].value;
for(p in obj)if(obj.hasOwnProperty(p))result.push({name:p,value:obj[p]});
// result: [{name: "lang", value: "German"}, {name: "age", value: "18"}, {name : "childs", value: '5'}]

How to remove only 0 (Zero) values from column in excel 2010

I selected columns that I want to delete 0 values then clicked DATA > FILTER. In column's header there is a filter icon appears. I clicked on that icon and selected only 0 values and clicked OK. Only 0 values becomes selected. Finally clear content OR use DELETE button.

Then to remove the blank rows from the deleted 0 values removed. I click DATA > FILTER I clicked on that filter icon and unselected blanks copy and paste the remaining data into a new sheet.

MySQL show status - active or total connections?

According to the docs, it means the total number throughout history:

Connections

The number of connection attempts (successful or not) to the MySQL server.

You can see the number of active connections either through the Threads_connected status variable:

Threads_connected

The number of currently open connections.

mysql> show status where `variable_name` = 'Threads_connected';
+-------------------+-------+
| Variable_name     | Value |
+-------------------+-------+
| Threads_connected | 4     |
+-------------------+-------+
1 row in set (0.00 sec)

... or through the show processlist command:

mysql> show processlist;
+----+------+-----------------+--------+---------+------+-------+------------------+
| Id | User | Host            | db     | Command | Time | State | Info             |
+----+------+-----------------+--------+---------+------+-------+------------------+
|  3 | root | localhost       | webapp | Query   |    0 | NULL  | show processlist | 
|  5 | root | localhost:61704 | webapp | Sleep   |  208 |       | NULL             | 
|  6 | root | localhost:61705 | webapp | Sleep   |  208 |       | NULL             | 
|  7 | root | localhost:61706 | webapp | Sleep   |  208 |       | NULL             | 
+----+------+-----------------+--------+---------+------+-------+------------------+
4 rows in set (0.00 sec)

How do I access nested HashMaps in Java?

You can do it like you assumed. But your HashMap has to be templated:

Map<String, Map<String, String>> map = 
    new HashMap<String, Map<String, String>>();

Otherwise you have to do a cast to Map after you retrieve the second map from the first.

Map map = new HashMap();
((Map)map.get( "keyname" )).get( "nestedkeyname" );

Pandas column of lists, create a row for each list element

Pandas >= 0.25

Series and DataFrame methods define a .explode() method that explodes lists into separate rows. See the docs section on Exploding a list-like column.

df = pd.DataFrame({
    'var1': [['a', 'b', 'c'], ['d', 'e',], [], np.nan], 
    'var2': [1, 2, 3, 4]
})
df
        var1  var2
0  [a, b, c]     1
1     [d, e]     2
2         []     3
3        NaN     4

df.explode('var1')

  var1  var2
0    a     1
0    b     1
0    c     1
1    d     2
1    e     2
2  NaN     3  # empty list converted to NaN
3  NaN     4  # NaN entry preserved as-is

# to reset the index to be monotonically increasing...
df.explode('var1').reset_index(drop=True)

  var1  var2
0    a     1
1    b     1
2    c     1
3    d     2
4    e     2
5  NaN     3
6  NaN     4

Note that this also handles mixed columns of lists and scalars, as well as empty lists and NaNs appropriately (this is a drawback of repeat-based solutions).

However, you should note that explode only works on a single column (for now).

P.S.: if you are looking to explode a column of strings, you need to split on a separator first, then use explode. See this (very much) related answer by me.

How to create Toast in Flutter?

You can use this link to show Toast in Flutter. Use this as :--

void method1(){

      Fluttertoast.showToast(
          msg: "This is Add Button",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          timeInSecForIosWeb: 1,
          backgroundColor: Colors.blueGrey,
          textColor: Colors.white,
          fontSize: 14.0
      );
  }

Can functions be passed as parameters?

This is the simplest way I can come with.

package main

import "fmt"

func main() {
    g := greeting
    getFunc(g)
}

func getFunc(f func()) {
    f()
}

func greeting() {
    fmt.Println("Hello")
}

@Cacheable key on multiple method arguments

After some limited testing with Spring 3.2, it seems one can use a SpEL list: {..., ..., ...}. This can also include null values. Spring passes the list as the key to the actual cache implementation. When using Ehcache, such will at some point invoke List#hashCode(), which takes all its items into account. (I am not sure if Ehcache only relies on the hash code.)

I use this for a shared cache, in which I include the method name in the key as well, which the Spring default key generator does not include. This way I can easily wipe the (single) cache, without (too much...) risking matching keys for different methods. Like:

@Cacheable(value="bookCache", 
  key="{ #root.methodName, #isbn?.id, #checkWarehouse }")
public Book findBook(ISBN isbn, boolean checkWarehouse) 
...

@Cacheable(value="bookCache", 
  key="{ #root.methodName, #asin, #checkWarehouse }")
public Book findBookByAmazonId(String asin, boolean checkWarehouse)
...

Of course, if many methods need this and you're always using all parameters for your key, then one can also define a custom key generator that includes the class and method name:

<cache:annotation-driven mode="..." key-generator="cacheKeyGenerator" />
<bean id="cacheKeyGenerator" class="net.example.cache.CacheKeyGenerator" />

...with:

public class CacheKeyGenerator 
  implements org.springframework.cache.interceptor.KeyGenerator {

    @Override
    public Object generate(final Object target, final Method method, 
      final Object... params) {

        final List<Object> key = new ArrayList<>();
        key.add(method.getDeclaringClass().getName());
        key.add(method.getName());

        for (final Object o : params) {
            key.add(o);
        }
        return key;
    }
}

jQuery val is undefined?

I just ran across this myself yesterday on a project I was working on. I'm my specific case, it was not exactly what the input was named, but how the ID was named.

<input id="user_info[1][last_name]" ..... />
var last_name = $("#user_info[1][last_name]").val() // returned undefined

Removing the brackets solved the issue:

<input id="user_info1_last_name" ..... />
var last_name = $("#user_info1_last_name").val() // returned "MyLastNameValue"

Anyway, probably a no brainer for some people, but in case this helps anyone else... there you go!

:-) - Drew

How to get package name from anywhere?

You can get your package name like so:

$ /path/to/adb shell 'pm list packages -f myapp'
package:/data/app/mycompany.myapp-2.apk=mycompany.myapp

Here are the options:

$ adb
Android Debug Bridge version 1.0.32
Revision 09a0d98bebce-android

 -a                            - directs adb to listen on all interfaces for a connection
 -d                            - directs command to the only connected USB device
                                 returns an error if more than one USB device is present.
 -e                            - directs command to the only running emulator.
                                 returns an error if more than one emulator is running.
 -s <specific device>          - directs command to the device or emulator with the given
                                 serial number or qualifier. Overrides ANDROID_SERIAL
                                 environment variable.
 -p <product name or path>     - simple product name like 'sooner', or
                                 a relative/absolute path to a product
                                 out directory like 'out/target/product/sooner'.
                                 If -p is not specified, the ANDROID_PRODUCT_OUT
                                 environment variable is used, which must
                                 be an absolute path.
 -H                            - Name of adb server host (default: localhost)
 -P                            - Port of adb server (default: 5037)
 devices [-l]                  - list all connected devices
                                 ('-l' will also list device qualifiers)
 connect <host>[:<port>]       - connect to a device via TCP/IP
                                 Port 5555 is used by default if no port number is specified.
 disconnect [<host>[:<port>]]  - disconnect from a TCP/IP device.
                                 Port 5555 is used by default if no port number is specified.
                                 Using this command with no additional arguments
                                 will disconnect from all connected TCP/IP devices.

device commands:
  adb push [-p] <local> <remote>
                               - copy file/dir to device
                                 ('-p' to display the transfer progress)
  adb pull [-p] [-a] <remote> [<local>]
                               - copy file/dir from device
                                 ('-p' to display the transfer progress)
                                 ('-a' means copy timestamp and mode)
  adb sync [ <directory> ]     - copy host->device only if changed
                                 (-l means list but don't copy)
  adb shell                    - run remote shell interactively
  adb shell <command>          - run remote shell command
  adb emu <command>            - run emulator console command
  adb logcat [ <filter-spec> ] - View device log
  adb forward --list           - list all forward socket connections.
                                 the format is a list of lines with the following format:
                                    <serial> " " <local> " " <remote> "\n"
  adb forward <local> <remote> - forward socket connections
                                 forward specs are one of:
                                   tcp:<port>
                                   localabstract:<unix domain socket name>
                                   localreserved:<unix domain socket name>
                                   localfilesystem:<unix domain socket name>
                                   dev:<character device name>
                                   jdwp:<process pid> (remote only)
  adb forward --no-rebind <local> <remote>
                               - same as 'adb forward <local> <remote>' but fails
                                 if <local> is already forwarded
  adb forward --remove <local> - remove a specific forward socket connection
  adb forward --remove-all     - remove all forward socket connections
  adb reverse --list           - list all reverse socket connections from device
  adb reverse <remote> <local> - reverse socket connections
                                 reverse specs are one of:
                                   tcp:<port>
                                   localabstract:<unix domain socket name>
                                   localreserved:<unix domain socket name>
                                   localfilesystem:<unix domain socket name>
  adb reverse --norebind <remote> <local>
                               - same as 'adb reverse <remote> <local>' but fails
                                 if <remote> is already reversed.
  adb reverse --remove <remote>
                               - remove a specific reversed socket connection
  adb reverse --remove-all     - remove all reversed socket connections from device
  adb jdwp                     - list PIDs of processes hosting a JDWP transport
  adb install [-lrtsdg] <file>
                               - push this package file to the device and install it
                                 (-l: forward lock application)
                                 (-r: replace existing application)
                                 (-t: allow test packages)
                                 (-s: install application on sdcard)
                                 (-d: allow version code downgrade)
                                 (-g: grant all runtime permissions)
  adb install-multiple [-lrtsdpg] <file...>
                               - push this package file to the device and install it
                                 (-l: forward lock application)
                                 (-r: replace existing application)
                                 (-t: allow test packages)
                                 (-s: install application on sdcard)
                                 (-d: allow version code downgrade)
                                 (-p: partial application install)
                                 (-g: grant all runtime permissions)
  adb uninstall [-k] <package> - remove this app package from the device
                                 ('-k' means keep the data and cache directories)
  adb bugreport                - return all information from the device
                                 that should be included in a bug report.

  adb backup [-f <file>] [-apk|-noapk] [-obb|-noobb] [-shared|-noshared] [-all] [-system|-nosystem] [<packages...>]
                               - write an archive of the device's data to <file>.
                                 If no -f option is supplied then the data is written
                                 to "backup.ab" in the current directory.
                                 (-apk|-noapk enable/disable backup of the .apks themselves
                                    in the archive; the default is noapk.)
                                 (-obb|-noobb enable/disable backup of any installed apk expansion
                                    (aka .obb) files associated with each application; the default
                                    is noobb.)
                                 (-shared|-noshared enable/disable backup of the device's
                                    shared storage / SD card contents; the default is noshared.)
                                 (-all means to back up all installed applications)
                                 (-system|-nosystem toggles whether -all automatically includes
                                    system applications; the default is to include system apps)
                                 (<packages...> is the list of applications to be backed up.  If
                                    the -all or -shared flags are passed, then the package
                                    list is optional.  Applications explicitly given on the
                                    command line will be included even if -nosystem would
                                    ordinarily cause them to be omitted.)

  adb restore <file>           - restore device contents from the <file> backup archive

  adb disable-verity           - disable dm-verity checking on USERDEBUG builds
  adb enable-verity            - re-enable dm-verity checking on USERDEBUG builds
  adb keygen <file>            - generate adb public/private key. The private key is stored in <file>,
                                 and the public key is stored in <file>.pub. Any existing files
                                 are overwritten.
  adb help                     - show this help message
  adb version                  - show version num

scripting:
  adb wait-for-device          - block until device is online
  adb start-server             - ensure that there is a server running
  adb kill-server              - kill the server if it is running
  adb get-state                - prints: offline | bootloader | device
  adb get-serialno             - prints: <serial-number>
  adb get-devpath              - prints: <device-path>
  adb remount                  - remounts the /system, /vendor (if present) and /oem (if present) partitions on the device read-write
  adb reboot [bootloader|recovery]
                               - reboots the device, optionally into the bootloader or recovery program.
  adb reboot sideload          - reboots the device into the sideload mode in recovery program (adb root required).
  adb reboot sideload-auto-reboot
                               - reboots into the sideload mode, then reboots automatically after the sideload regardless of the result.
  adb sideload <file>          - sideloads the given package
  adb root                     - restarts the adbd daemon with root permissions
  adb unroot                   - restarts the adbd daemon without root permissions
  adb usb                      - restarts the adbd daemon listening on USB
  adb tcpip <port>             - restarts the adbd daemon listening on TCP on the specified port

networking:
  adb ppp <tty> [parameters]   - Run PPP over USB.
 Note: you should not automatically start a PPP connection.
 <tty> refers to the tty for PPP stream. Eg. dev:/dev/omap_csmi_tty1
 [parameters] - Eg. defaultroute debug dump local notty usepeerdns

adb sync notes: adb sync [ <directory> ]
  <localdir> can be interpreted in several ways:

  - If <directory> is not specified, /system, /vendor (if present), /oem (if present) and /data partitions will be updated.

  - If it is "system", "vendor", "oem" or "data", only the corresponding partition
    is updated.

environment variables:
  ADB_TRACE                    - Print debug information. A comma separated list of the following values
                                 1 or all, adb, sockets, packets, rwx, usb, sync, sysdeps, transport, jdwp
  ANDROID_SERIAL               - The serial number to connect to. -s takes priority over this if given.
  ANDROID_LOG_TAGS             - When used with the logcat option, only these debug tags are printed.

Copy folder structure (without files) from one location to another

A python script from Sergiy Kolodyazhnyy posted on Copy only folders not files?:

#!/usr/bin/env python
import os,sys
dirs=[ r for r,s,f in os.walk(".") if r != "."]
for i in dirs:
    os.makedirs(os.path.join(sys.argv[1],i)) 

or from the shell:

python -c 'import os,sys;dirs=[ r for r,s,f in os.walk(".") if r != "."];[os.makedirs(os.path.join(sys.argv[1],i)) for i in dirs]' ~/new_destination

FYI:

How do you setLayoutParams() for an ImageView?

An ImageView gets setLayoutParams from View which uses ViewGroup.LayoutParams. If you use that, it will crash in most cases so you should use getLayoutParams() which is in View.class. This will inherit the parent View of the ImageView and will work always. You can confirm this here: ImageView extends view

Assuming you have an ImageView defined as 'image_view' and the width/height int defined as 'thumb_size'

The best way to do this:

ViewGroup.LayoutParams iv_params_b = image_view.getLayoutParams();
iv_params_b.height = thumb_size;
iv_params_b.width = thumb_size;
image_view.setLayoutParams(iv_params_b);

How to vertically align an image inside a div

The only (and the best cross-browser) way as I know is to use an inline-block helper with height: 100% and vertical-align: middle on both elements.

So there is a solution: http://jsfiddle.net/kizu/4RPFa/4570/

_x000D_
_x000D_
.frame {_x000D_
    height: 25px;      /* Equals maximum image height */_x000D_
    width: 160px;_x000D_
    border: 1px solid red;_x000D_
    white-space: nowrap; /* This is required unless you put the helper span closely near the img */_x000D_
_x000D_
    text-align: center;_x000D_
    margin: 1em 0;_x000D_
}_x000D_
_x000D_
.helper {_x000D_
    display: inline-block;_x000D_
    height: 100%;_x000D_
    vertical-align: middle;_x000D_
}_x000D_
_x000D_
img {_x000D_
    background: #3A6F9A;_x000D_
    vertical-align: middle;_x000D_
    max-height: 25px;_x000D_
    max-width: 160px;_x000D_
}
_x000D_
<div class="frame">_x000D_
    <span class="helper"></span><img src="http://jsfiddle.net/img/logo.png" height=250px />_x000D_
</div>_x000D_
<div class="frame">_x000D_
    <span class="helper"></span><img src="http://jsfiddle.net/img/logo.png" height=25px />_x000D_
</div>_x000D_
<div class="frame">_x000D_
    <span class="helper"></span><img src="http://jsfiddle.net/img/logo.png" height=23px />_x000D_
</div>_x000D_
<div class="frame">_x000D_
    <span class="helper"></span><img src="http://jsfiddle.net/img/logo.png" height=21px />_x000D_
</div>_x000D_
<div class="frame">_x000D_
    <span class="helper"></span><img src="http://jsfiddle.net/img/logo.png" height=19px />_x000D_
</div>_x000D_
<div class="frame">_x000D_
    <span class="helper"></span>_x000D_
    <img src="http://jsfiddle.net/img/logo.png" height=17px />_x000D_
</div>_x000D_
<div class="frame">_x000D_
    <span class="helper"></span>_x000D_
    <img src="http://jsfiddle.net/img/logo.png" height=15px />_x000D_
</div>_x000D_
<div class="frame">_x000D_
    <span class="helper"></span>_x000D_
    <img src="http://jsfiddle.net/img/logo.png" height=13px />_x000D_
</div>_x000D_
<div class="frame">_x000D_
    <span class="helper"></span>_x000D_
    <img src="http://jsfiddle.net/img/logo.png" height=11px />_x000D_
</div>_x000D_
<div class="frame">_x000D_
    <span class="helper"></span>_x000D_
    <img src="http://jsfiddle.net/img/logo.png" height=9px />_x000D_
</div>_x000D_
<div class="frame">_x000D_
    <span class="helper"></span>_x000D_
    <img src="http://jsfiddle.net/img/logo.png" height=7px />_x000D_
</div>_x000D_
<div class="frame">_x000D_
    <span class="helper"></span>_x000D_
    <img src="http://jsfiddle.net/img/logo.png" height=5px />_x000D_
</div>_x000D_
<div class="frame">_x000D_
    <span class="helper"></span>_x000D_
    <img src="http://jsfiddle.net/img/logo.png" height=3px />_x000D_
</div>
_x000D_
_x000D_
_x000D_

Or, if you don't want to have an extra element in modern browsers and don't mind using Internet Explorer expressions, you can use a pseudo-element and add it to Internet Explorer using a convenient Expression, that runs only once per element, so there won't be any performance issues:

The solution with :before and expression() for Internet Explorer: http://jsfiddle.net/kizu/4RPFa/4571/

_x000D_
_x000D_
.frame {_x000D_
    height: 25px;      /* Equals maximum image height */_x000D_
    width: 160px;_x000D_
    border: 1px solid red;_x000D_
    white-space: nowrap;_x000D_
_x000D_
    text-align: center;_x000D_
    margin: 1em 0;_x000D_
}_x000D_
_x000D_
.frame:before,_x000D_
.frame_before {_x000D_
    content: "";_x000D_
    display: inline-block;_x000D_
    height: 100%;_x000D_
    vertical-align: middle;_x000D_
}_x000D_
_x000D_
img {_x000D_
    background: #3A6F9A;_x000D_
    vertical-align: middle;_x000D_
    max-height: 25px;_x000D_
    max-width: 160px;_x000D_
}_x000D_
_x000D_
/* Move this to conditional comments */_x000D_
.frame {_x000D_
    list-style:none;_x000D_
    behavior: expression(_x000D_
        function(t){_x000D_
            t.insertAdjacentHTML('afterBegin','<span class="frame_before"></span>');_x000D_
            t.runtimeStyle.behavior = 'none';_x000D_
        }(this)_x000D_
    );_x000D_
}
_x000D_
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=250px /></div>_x000D_
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=25px /></div>_x000D_
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=23px /></div>_x000D_
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=21px /></div>_x000D_
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=19px /></div>_x000D_
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=17px /></div>_x000D_
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=15px /></div>_x000D_
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=13px /></div>_x000D_
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=11px /></div>_x000D_
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=9px /></div>_x000D_
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=7px /></div>_x000D_
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=5px /></div>_x000D_
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=3px /></div>
_x000D_
_x000D_
_x000D_


How it works:

  1. When you have two inline-block elements near each other, you can align each to other's side, so with vertical-align: middle you'll get something like this:

    Two aligned blocks

  2. When you have a block with fixed height (in px, em or another absolute unit), you can set the height of inner blocks in %.

  3. So, adding one inline-block with height: 100% in a block with fixed height would align another inline-block element in it (<img/> in your case) vertically near it.

Get login username in java

inspired by @newacct's answer, a code that can be compiled in any platform:

String osName = System.getProperty( "os.name" ).toLowerCase();
String className = null;
String methodName = "getUsername";

if( osName.contains( "windows" ) ){
    className = "com.sun.security.auth.module.NTSystem";
    methodName = "getName";
}
else if( osName.contains( "linux" ) ){
    className = "com.sun.security.auth.module.UnixSystem";
}
else if( osName.contains( "solaris" ) || osName.contains( "sunos" ) ){
    className = "com.sun.security.auth.module.SolarisSystem";
}

if( className != null ){
    Class<?> c = Class.forName( className );
    Method method = c.getDeclaredMethod( methodName );
    Object o = c.newInstance();
    System.out.println( method.invoke( o ) );
}

jQuery posting JSON

'data' should be a stringified JavaScript object:

data: JSON.stringify({ "userName": userName, "password" : password })

To send your formData, pass it to stringify:

data: JSON.stringify(formData)

Some servers also require the application/json content type:

contentType: 'application/json'

There's also a more detailed answer to a similar question here: Jquery Ajax Posting json to webservice

How can I generate an MD5 hash?

Here is how I use it:

final MessageDigest messageDigest = MessageDigest.getInstance("MD5");
messageDigest.reset();
messageDigest.update(string.getBytes(Charset.forName("UTF8")));
final byte[] resultByte = messageDigest.digest();
final String result = new String(Hex.encodeHex(resultByte));

where Hex is: org.apache.commons.codec.binary.Hex from the Apache Commons project.

How to style a disabled checkbox?

If you're trying to stop someone from updating the checkbox so it appears disabled then just use JQuery

$('input[type=checkbox]').click(false);

You can then style the checkbox.

How to compress a String in Java?

When you create a String, you can think of it as a list of char's, this means that for each character in your String, you need to support all the possible values of char. From the sun docs

char: The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).

If you have a reduced set of characters you want to support you can write a simple compression algorithm, which is analogous to binary->decimal->hex radix converstion. You go from 65,536 (or however many characters your target system supports) to 26 (alphabetical) / 36 (alphanumeric) etc.

I've used this trick a few times, for example encoding timestamps as text (target 36 +, source 10) - just make sure you have plenty of unit tests!

Use of 'const' for function parameters

the thing to remember with const is that it is much easier to make things const from the start, than it is to try and put them in later.

Use const when you want something to be unchanged - its an added hint that describes what your function does and what to expect. I've seen many an C API that could do with some of them, especially ones that accept c-strings!

I'd be more inclined to omit the const keyword in the cpp file than the header, but as I tend to cut+paste them, they'd be kept in both places. I have no idea why the compiler allows that, I guess its a compiler thing. Best practice is definitely to put your const keyword in both files.

Get screen width and height in Android

This set of utilities to work with the Size abstraction in Android.

It contains a class SizeFromDisplay.java You can use it like this:

ISize size = new SizeFromDisplay(getWindowManager().getDefaultDisplay());
size.width();
size.hight();

How to convert image to byte array

You can use File.ReadAllBytes() method to read any file into byte array. To write byte array into file, just use File.WriteAllBytes() method.

Hope this helps.

You can find more information and sample code here.

PostgreSQL - fetch the row which has the Max value for a column

I would propose a clean version based on DISTINCT ON (see docs):

SELECT DISTINCT ON (usr_id)
    time_stamp,
    lives_remaining,
    usr_id,
    trans_id
FROM lives
ORDER BY usr_id, time_stamp DESC, trans_id DESC;

Python: How to create a unique file name?

The uuid module would be a good choice, I prefer to use uuid.uuid4().hex as random filename because it will return a hex string without dashes.

import uuid
filename = uuid.uuid4().hex

The outputs should like this:

>>> import uuid
>>> uuid.uuid()
UUID('20818854-3564-415c-9edc-9262fbb54c82')
>>> str(uuid.uuid4())
'f705a69a-8e98-442b-bd2e-9de010132dc4'
>>> uuid.uuid4().hex
'5ad02dfb08a04d889e3aa9545985e304'  # <-- this one

How to sort Counter by value? - python

Use the Counter.most_common() method, it'll sort the items for you:

>>> from collections import Counter
>>> x = Counter({'a':5, 'b':3, 'c':7})
>>> x.most_common()
[('c', 7), ('a', 5), ('b', 3)]

It'll do so in the most efficient manner possible; if you ask for a Top N instead of all values, a heapq is used instead of a straight sort:

>>> x.most_common(1)
[('c', 7)]

Outside of counters, sorting can always be adjusted based on a key function; .sort() and sorted() both take callable that lets you specify a value on which to sort the input sequence; sorted(x, key=x.get, reverse=True) would give you the same sorting as x.most_common(), but only return the keys, for example:

>>> sorted(x, key=x.get, reverse=True)
['c', 'a', 'b']

or you can sort on only the value given (key, value) pairs:

>>> sorted(x.items(), key=lambda pair: pair[1], reverse=True)
[('c', 7), ('a', 5), ('b', 3)]

See the Python sorting howto for more information.

return results from a function (javascript, nodejs)

You are trying to execute an asynchronous function in a synchronous way, which is unfortunately not possible in Javascript.

As you guessed correctly, the roomId=results.... is executed when the loading from the DB completes, which is done asynchronously, so AFTER the resto of your code is completed.

Look at this article, it talks about .insert and not .find, but the idea is the same : http://metaduck.com/01-asynchronous-iteration-patterns.html

How to clear a chart from a canvas so that hover events cannot be triggered?

Since destroy kind of destroys "everything", a cheap and simple solution when all you really want is to just "reset the data". Resetting your datasets to an empty array will work perfectly fine as well. So, if you have a dataset with labels, and an axis on each side:

window.myLine2.data.labels = [];
window.myLine2.data.datasets[0].data = [];
window.myLine2.data.datasets[1].data = [];

After this, you can simply call:

window.myLine2.data.labels.push(x);
window.myLine2.data.datasets[0].data.push(y);

or, depending whether you're using a 2d dataset:

window.myLine2.data.datasets[0].data.push({ x: x, y: y});

It'll be a lot more lightweight than completely destroying your whole chart/dataset, and rebuilding everything.

How can I revert a single file to a previous version?

Git doesn't think in terms of file versions. A version in git is a snapshot of the entire tree.

Given this, what you really want is a tree that has the latest content of most files, but with the contents of one file the same as it was 5 commits ago. This will take the form of a new commit on top of the old ones, and the latest version of the tree will have what you want.

I don't know if there's a one-liner that will revert a single file to the contents of 5 commits ago, but the lo-fi solution should work: checkout master~5, copy the file somewhere else, checkout master, copy the file back, then commit.

.htaccess rewrite to redirect root URL to subdirectory

You can use a rewrite rule that uses ^$ to represent the root and rewrite that to your /store directory, like this:

RewriteEngine On
RewriteRule ^$ /store [L]

Downloading folders from aws s3, cp or sync?

In the case you want to download a single file, you can try the following command:

aws s3 cp s3://bucket/filename /path/to/dest/folder

How to resolve Value cannot be null. Parameter name: source in linq?

When you call a Linq statement like this:

// x = new List<string>();
var count = x.Count(s => s.StartsWith("x"));

You are actually using an extension method in the System.Linq namespace, so what the compiler translates this into is:

var count = Enumerable.Count(x, s => s.StartsWith("x"));

So the error you are getting above is because the first parameter, source (which would be x in the sample above) is null.

java: How can I do dynamic casting of a variable from one type to another?

For what it is worth, most scripting languages (like Perl) and non-static compile-time languages (like Pick) support automatic run-time dynamic String to (relatively arbitrary) object conversions. This CAN be accomplished in Java as well without losing type-safety and the good stuff statically-typed languages provide WITHOUT the nasty side-effects of some of the other languages that do evil things with dynamic casting. A Perl example that does some questionable math:

print ++($foo = '99');  # prints '100'
print ++($foo = 'a0');  # prints 'a1'

In Java, this is better accomplished (IMHO) by using a method I call "cross-casting". With cross-casting, reflection is used in a lazy-loaded cache of constructors and methods that are dynamically discovered via the following static method:

Object fromString (String value, Class targetClass)

Unfortunately, no built-in Java methods such as Class.cast() will do this for String to BigDecimal or String to Integer or any other conversion where there is no supporting class hierarchy. For my part, the point is to provide a fully dynamic way to achieve this - for which I don't think the prior reference is the right approach - having to code every conversion. Simply put, the implementation is just to cast-from-string if it is legal/possible.

So the solution is simple reflection looking for public Members of either:

STRING_CLASS_ARRAY = (new Class[] {String.class});

a) Member member = targetClass.getMethod(method.getName(),STRING_CLASS_ARRAY); b) Member member = targetClass.getConstructor(STRING_CLASS_ARRAY);

You will find that all of the primitives (Integer, Long, etc) and all of the basics (BigInteger, BigDecimal, etc) and even java.regex.Pattern are all covered via this approach. I have used this with significant success on production projects where there are a huge amount of arbitrary String value inputs where some more strict checking was needed. In this approach, if there is no method or when the method is invoked an exception is thrown (because it is an illegal value such as a non-numeric input to a BigDecimal or illegal RegEx for a Pattern), that provides the checking specific to the target class inherent logic.

There are some downsides to this:

1) You need to understand reflection well (this is a little complicated and not for novices). 2) Some of the Java classes and indeed 3rd-party libraries are (surprise) not coded properly. That is, there are methods that take a single string argument as input and return an instance of the target class but it isn't what you think... Consider the Integer class:

static Integer getInteger(String nm)
      Determines the integer value of the system property with the specified name.

The above method really has nothing to do with Integers as objects wrapping primitives ints. Reflection will find this as a possible candidate for creating an Integer from a String incorrectly versus the decode, valueof and constructor Members - which are all suitable for most arbitrary String conversions where you really don't have control over your input data but just want to know if it is possible an Integer.

To remedy the above, looking for methods that throw Exceptions is a good start because invalid input values that create instances of such objects should throw an Exception. Unfortunately, implementations vary as to whether the Exceptions are declared as checked or not. Integer.valueOf(String) throws a checked NumberFormatException for example, but Pattern.compile() exceptions are not found during reflection lookups. Again, not a failing of this dynamic "cross-casting" approach I think so much as a very non-standard implementation for exception declarations in object creation methods.

If anyone would like more details on how the above was implemented, let me know but I think this solution is much more flexible/extensible and with less code without losing the good parts of type-safety. Of course it is always best to "know thy data" but as many of us find, we are sometimes only recipients of unmanaged content and have to do the best we can to use it properly.

Cheers.

Global variables in Java

public class GlobalClass {
     public static int x = 37;
     public static String s = "aaa";
}

This way you can access them with GlobalClass.x and GlobalClass.s

Can't specify the 'async' modifier on the 'Main' method of a console app

I'll add an important feature that all of the other answers have overlooked: cancellation.

One of the big things in TPL is cancellation support, and console apps have a method of cancellation built in (CTRL+C). It's very simple to bind them together. This is how I structure all of my async console apps:

static void Main(string[] args)
{
    CancellationTokenSource cts = new CancellationTokenSource();
    
    System.Console.CancelKeyPress += (s, e) =>
    {
        e.Cancel = true;
        cts.Cancel();
    };

    MainAsync(args, cts.Token).GetAwaiter.GetResult();
}

static async Task MainAsync(string[] args, CancellationToken token)
{
    ...
}

Presto SQL - Converting a date string to date format

SQL 2003 standard defines the format as follows:

<unquoted timestamp string> ::= <unquoted date string> <space> <unquoted time string>
<date value> ::= <years value> <minus sign> <months value> <minus sign> <days value>
<time value> ::= <hours value> <colon> <minutes value> <colon> <seconds value>

There are some definitions in between that just link back to these, but in short YYYY-MM-DD HH:MM:SS with optional .mmm milliseconds is required to work on all SQL databases.

Facebook share link - can you customize the message body text?

Like @Ardee said you sharer.php uses data from the meta tags, the Dialog API accepts parameters. Facebook have removed the ability to use the message parameter but you can use the quote parameter which can be useful in a lot of cases e.g.

enter image description here

https://www.facebook.com/dialog/share?
app_id=[your-app-id]
&display=popup
&title=This+is+the+title+parameter
&description=This+is+the+description+parameter
&quote=This+is+the+quote+parameter
&caption=This+is+the+caption+parameter
&href=https%3A%2F%2Fdevelopers.facebook.com%2Fdocs%2F
&redirect_uri=https%3A%2F%2Fwww.[url-in-your-accepted-list].com

Just have to create an app id:

https://developers.facebook.com/docs/apps/register

Then make sure the redirect url domain is listed in the accepted domains for that app.

MySQL: is a SELECT statement case sensitive?

You can lowercase the value and the passed parameter :

SELECT * FROM `table` WHERE LOWER(`Value`) = LOWER("IAreSavage")

Another (better) way would be to use the COLLATE operator as said in the documentation

Full-screen responsive background image

This worked for me, so posting this.

.my-container {
  position: relative;
  background: #696969;
  overflow: hidden;
}
.my-container:before {
  content: ' ';
  display: block;
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
  opacity: 0.6;
  background-image: url('https://images.pexels.com/photos/1084542/pexels-photo-1084542.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260');
  background-repeat: no-repeat;
  background-position: 50% 0;
  -ms-background-size: cover;
  -o-background-size: cover;
  -moz-background-size: cover;
  -webkit-background-size: cover;
  background-size: cover;
}

How to adjust the size of y axis labels only in R?

As the title suggests that we want to adjust the size of the labels and not the tick marks I figured that I actually might add something to the question, you need to use the mtext() if you want to specify one of the label sizes, or you can just use par(cex.lab=2) as a simple alternative. Here's a more advanced mtext() example:

set.seed(123)
foo <- data.frame(X = rnorm(10), Y = rnorm(10))
plot(Y ~ X, data=foo,
     yaxt="n", ylab="", 
     xlab="Regular boring x", 
     pch=16,
     col="darkblue")
axis(2,cex.axis=1.2)
mtext("Awesome Y variable", side=2, line=2.2, cex=2)

enter image description here

You may need to adjust the line= option to get the optimal positioning of the text but apart from that it's really easy to use.

How to resolve this System.IO.FileNotFoundException

I've been mislead by this error more than once. After spending hours googling, updating nuget packages, version checking, then after sitting with a completely updated solution I re-realize a perfectly valid, simpler reason for the error.

If in a threaded enthronement (UI Dispatcher.Invoke for example), System.IO.FileNotFoundException is thrown if the thread manager dll (file) fails to return. So if your main UI thread A, calls the system thread manager dll B, and B calls your thread code C, but C throws for some unrelated reason (such as null Reference as in my case), then C does not return, B does not return, and A only blames B with FileNotFoundException for being lost...

Before going down the dll version path... Check closer to home and verify your thread code is not throwing.

Jenkins Host key verification failed

issue is with the /var/lib/jenkins/.ssh/known_hosts. It exists in the first case, but not in the second one. This means you are running either on different system or the second case is somehow jailed in chroot or by other means separated from the rest of the filesystem (this is a good idea for running random code from jenkins).

Next steps are finding out how are the chroots for this user created and modify the known hosts inside this chroot. Or just go other ways of ignoring known hosts, such as ssh-keyscan, StrictHostKeyChecking=no or so.

Android Layout Weight

<LinearLayout
    android:id="@+id/linear1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:weightSum="9"
    android:orientation="horizontal" >

    <ImageView
        android:id="@+id/ring_oss"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="3"
        android:src="@drawable/ring_oss" />

    <ImageView
        android:id="@+id/maila_oss"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="3"
        android:src="@drawable/maila_oss" />
<EditText
        android:id="@+id/edittxt"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="3"
        android:src="@drawable/maila_oss" />
</LinearLayout>

How to execute function in SQL Server 2008

I have come to this question and the one below several times.

how to call scalar function in sql server 2008

Each time, I try entering the Function using the syntax shown here in SQL Server Management Studio, or SSMS, to see the results, and each time I get the errors.

For me, that is because my result set is in tabular data format. Therefore, to see the results in SSMS, I have to call it like this:

SELECT * FROM dbo.Afisho_rankimin_TABLE(5);

I understand that the author's question involved a scalar function, so this answer is only to help others who come to StackOverflow often when they have a problem with a query (like me).

I hope this helps others.

Local package.json exists, but node_modules missing

Just had the same error message, but when I was running a package.json with:

"scripts": {
    "build": "tsc -p ./src",
}

tsc is the command to run the TypeScript compiler.

I never had any issues with this project because I had TypeScript installed as a global module. As this project didn't include TypeScript as a dev dependency (and expected it to be installed as global), I had the error when testing in another machine (without TypeScript) and running npm install didn't fix the problem. So I had to include TypeScript as a dev dependency (npm install typescript --save-dev) to solve the problem.

Adding a right click menu to an item

This is a comprehensive answer to this question. I have done this because this page is high on the Google search results and the answer does not go into enough detail. This post assumes that you are competent at using Visual Studio C# forms. This is based on VS2012.

  1. Start by simply dragging a ContextMenuStrip onto the form. It will just put it into the top left corner where you can add your menu items and rename it as you see fit.

  2. You will have to view code and enter in an event yourself on the form. Create a mouse down event for the item in question and then assign a right click event for it like so (I have called the ContextMenuStrip "rightClickMenuStrip"):

    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
    switch (e.Button)
        {
            case MouseButtons.Right:
            {
                rightClickMenuStrip.Show(this, new Point(e.X, e.Y));//places the menu at the pointer position
            }
            break;
        }
    }
    
  3. Assign the event handler manually to the form.designer (you may need to add a "using" for System.Windows.Forms; You can just resolve it):

    this.pictureBox1.MouseDown += new MouseEventHandler(this.pictureBox1_MouseDown);
    
  4. All that is needed at this point is to simply double click each menu item and do the desired operations for each click event in the same way you would for any other button.

This is the basic code for this operation. You can obviously modify it to fit in with your coding practices.

How to list records with date from the last 10 days?

you can use between too:

SELECT Table.date
  FROM Table 
  WHERE date between current_date and current_date - interval '10 day';

PIL image to array (numpy array to array) - Python

I use numpy.fromiter to invert a 8-greyscale bitmap, yet no signs of side-effects

import Image
import numpy as np

im = Image.load('foo.jpg')
im = im.convert('L')

arr = np.fromiter(iter(im.getdata()), np.uint8)
arr.resize(im.height, im.width)

arr ^= 0xFF  # invert
inverted_im = Image.fromarray(arr, mode='L')
inverted_im.show()

How do you concatenate Lists in C#?

Take a look at my implementation. It's safe from null lists.

 IList<string> all= new List<string>();

 if (letterForm.SecretaryPhone!=null)// first list may be null
     all=all.Concat(letterForm.SecretaryPhone).ToList();

 if (letterForm.EmployeePhone != null)// second list may be null
     all= all.Concat(letterForm.EmployeePhone).ToList(); 

 if (letterForm.DepartmentManagerName != null) // this is not list (its just string variable) so wrap it inside list then concat it 
     all = all.Concat(new []{letterForm.DepartmentManagerPhone}).ToList();

How to implement oauth2 server in ASP.NET MVC 5 and WEB API 2

I am researching the same thing and stumbled upon identityserver which implements OAuth and OpenID on top of ASP.NET. It integrates with ASP.NET identity and Membership Reboot with persistence support for Entity Framework.

So, to answer your question, check out their detailed document on how to setup an OAuth and OpenID server.

How do you render primitives as wireframes in OpenGL?

From http://cone3d.gamedev.net/cgi-bin/index.pl?page=tutorials/ogladv/tut5

// Turn on wireframe mode
glPolygonMode(GL_FRONT, GL_LINE);
glPolygonMode(GL_BACK, GL_LINE);

// Draw the box
DrawBox();

// Turn off wireframe mode
glPolygonMode(GL_FRONT, GL_FILL);
glPolygonMode(GL_BACK, GL_FILL);

How do I round to the nearest 0.5?

Multiply your rating by 2, then round using Math.Round(rating, MidpointRounding.AwayFromZero), then divide that value by 2.

Math.Round(value * 2, MidpointRounding.AwayFromZero) / 2

Perform curl request in javascript?

Yes, use getJSONP. It's the only way to make cross domain/server async calls. (*Or it will be in the near future). Something like

$.getJSON('your-api-url/validate.php?'+$(this).serialize+'callback=?', function(data){
if(data)console.log(data);
});

The callback parameter will be filled in automatically by the browser, so don't worry.

On the server side ('validate.php') you would have something like this

<?php
if(isset($_GET))
{
//if condition is met
echo $_GET['callback'] . '(' . "{'message' : 'success', 'userID':'69', 'serial' : 'XYZ99UAUGDVD&orwhatever'}". ')';
}
else echo json_encode(array('error'=>'failed'));
?>

JavaScript adding decimal numbers issue

Testing this Javascript:

var arr = [1234563995.721, 12345691212.718, 1234568421.5891, 12345677093.49284];

var sum = 0;
for( var i = 0; i < arr.length; i++ ) {
    sum += arr[i];
}

alert( "fMath(sum) = " + Math.round( sum * 1e12 ) / 1e12 );
alert( "fFixed(sum) = " + sum.toFixed( 5 ) );

Conclusion

Dont use Math.round( (## + ## + ... + ##) * 1e12) / 1e12

Instead, use ( ## + ## + ... + ##).toFixed(5) )

In IE 9, toFixed works very well.

How to disable sort in DataGridView?

You can disable it in the ColumnAdded event:

private void dataGridView1_ColumnAdded(object sender, DataGridViewColumnEventArgs e)
{
    dataGridView1.Columns[e.Column.Index].SortMode = DataGridViewColumnSortMode.NotSortable;
}

How an 'if (A && B)' statement is evaluated?

Yes, it is called Short-circuit Evaluation.

If the validity of the boolean statement can be assured after part of the statement, the rest is not evaluated.

This is very important when some of the statements have side-effects.

How to connect android wifi to adhoc wifi?

You are correct, but note that you can do it the other way around - use Android Wifi tethering that sets up the phone as a base station and connect to said base station from the laptop.

How do I reverse a commit in git?

git push -f maybe?

man git-push will tell more.

How to change 1 char in the string?

Strings are immutable. You can use the string builder class to help!:

string str = "valta is the best place in the World";

StringBuilder strB = new StringBuilder(str);

strB[0] = 'M';

Android widget: How to change the text of a button

I was able to change the button's text like this:

import android.widget.RemoteViews;

//grab the layout, then set the text of the Button called R.id.Counter:
RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.my_layout);
remoteViews.setTextViewText(R.id.Counter, "Set button text here");

How to parse freeform street/postal address out of text, and into components

For US Address Parsing,

I prefer using usaddress package that is available in pip for usaddress only

python3 -m pip install usaddress

Documentation
PyPi

This worked well for me for US address.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# address_parser.py
import sys
from usaddress import tag
from json import dumps, loads

if __name__ == '__main__':
    tag_mapping = {
        'Recipient': 'recipient',
        'AddressNumber': 'addressStreet',
        'AddressNumberPrefix': 'addressStreet',
        'AddressNumberSuffix': 'addressStreet',
        'StreetName': 'addressStreet',
        'StreetNamePreDirectional': 'addressStreet',
        'StreetNamePreModifier': 'addressStreet',
        'StreetNamePreType': 'addressStreet',
        'StreetNamePostDirectional': 'addressStreet',
        'StreetNamePostModifier': 'addressStreet',
        'StreetNamePostType': 'addressStreet',
        'CornerOf': 'addressStreet',
        'IntersectionSeparator': 'addressStreet',
        'LandmarkName': 'addressStreet',
        'USPSBoxGroupID': 'addressStreet',
        'USPSBoxGroupType': 'addressStreet',
        'USPSBoxID': 'addressStreet',
        'USPSBoxType': 'addressStreet',
        'BuildingName': 'addressStreet',
        'OccupancyType': 'addressStreet',
        'OccupancyIdentifier': 'addressStreet',
        'SubaddressIdentifier': 'addressStreet',
        'SubaddressType': 'addressStreet',
        'PlaceName': 'addressCity',
        'StateName': 'addressState',
        'ZipCode': 'addressPostalCode',
    }
    try:
        address, _ = tag(' '.join(sys.argv[1:]), tag_mapping=tag_mapping)
    except:
        with open('failed_address.txt', 'a') as fp:
            fp.write(sys.argv[1] + '\n')
        print(dumps({}))
    else:
        print(dumps(dict(address)))

Running the address_parser.py

 python3 address_parser.py 9757 East Arcadia Ave. Saugus MA 01906
 {"addressStreet": "9757 East Arcadia Ave.", "addressCity": "Saugus", "addressState": "MA", "addressPostalCode": "01906"}

How to clear memory to prevent "out of memory error" in excel vba?

The best way to help memory to be freed is to nullify large objects:

Sub Whatever()
    Dim someLargeObject as SomeObject

    'expensive computation

    Set someLargeObject = Nothing
End Sub

Also note that global variables remain allocated from one call to another, so if you don't need persistence you should either not use global variables or nullify them when you don't need them any longer.

However this won't help if:

  • you need the object after the procedure (obviously)
  • your object does not fit in memory

Another possibility is to switch to a 64 bit version of Excel which should be able to use more RAM before crashing (32 bits versions are typically limited at around 1.3GB).

What's the difference between identifying and non-identifying relationships?

An Identifying relationship specifies that a child object cannot exist without the parent object

Non-identifying relationships specifies a regular association between objects, 1:1 or 1:n cardinality.

Non-identifying relationships can be specified as optional where a parent is not required or mandatory where a parent is required by setting the parent table cardinality...

Is it bad to have my virtualenv directory inside my git repository?

I used to do the same until I started using libraries that are compiled differently depending on the environment such as PyCrypto. My PyCrypto mac wouldn't work on Cygwin wouldn't work on Ubuntu.

It becomes an utter nightmare to manage the repository.

Either way I found it easier to manage the pip freeze & a requirements file than having it all in git. It's cleaner too since you get to avoid the commit spam for thousands of files as those libraries get updated...

Node.js - get raw request body using Express

Edit 2: Release 1.15.2 of the body parser module introduces raw mode, which returns the body as a Buffer. By default, it also automatically handles deflate and gzip decompression. Example usage:

var bodyParser = require('body-parser');
app.use(bodyParser.raw(options));

app.get(path, function(req, res) {
  // req.body is a Buffer object
});

By default, the options object has the following default options:

var options = {
  inflate: true,
  limit: '100kb',
  type: 'application/octet-stream'
};

If you want your raw parser to parse other MIME types other than application/octet-stream, you will need to change it here. It will also support wildcard matching such as */* or */application.


Note: The following answer is for versions before Express 4, where middleware was still bundled with the framework. The modern equivalent is the body-parser module, which must be installed separately.

The rawBody property in Express was once available, but removed since version 1.5.1. To get the raw request body, you have to put in some middleware before using the bodyParser. You can also read a GitHub discussion about it here.

app.use(function(req, res, next) {
  req.rawBody = '';
  req.setEncoding('utf8');

  req.on('data', function(chunk) { 
    req.rawBody += chunk;
  });

  req.on('end', function() {
    next();
  });
});
app.use(express.bodyParser());

That middleware will read from the actual data stream, and store it in the rawBody property of the request. You can then access the raw body like this:

app.post('/', function(req, res) {
  // do something with req.rawBody
  // use req.body for the parsed body
});

Edit: It seems that this method and bodyParser refuse to coexist, because one will consume the request stream before the other, leading to whichever one is second to never fire end, thus never calling next(), and hanging your application.

The simplest solution would most likely be to modify the source of bodyParser, which you would find on line 57 of Connect's JSON parser. This is what the modified version would look like.

var buf = '';
req.setEncoding('utf8');
req.on('data', function(chunk){ buf += chunk });
req.on('end', function() {
  req.rawBody = buf;
  var first = buf.trim()[0];
  ...
});

You would find the file at this location:

/node_modules/express/node_modules/connect/lib/middleware/json.js.

linking jquery in html

<script
 src="CDN">
</script>

for change the CDN check this website.

the first one is JQuery

Running a cron job on Linux every six hours

Try:

0 */6 * * * command

. * has to

How to convert any Object to String?

I am not getting your question properly but as per your heading, you can convert any type of object to string by using toString() function on a String Object.

What does OpenCV's cvWaitKey( ) function do?

cvWaitKey(0) stops your program until you press a button.

cvWaitKey(10) doesn't stop your program but wake up and alert to end your program when you press a button. Its used into loops because cvWaitkey doesn't stop loop.

Normal use

char k;

k=cvWaitKey(0);

if(k == 'ESC')

with k you can see what key was pressed.

Uploading/Displaying Images in MVC 4

        <input type="file" id="picfile" name="picf" />
       <input type="text" id="txtName" style="width: 144px;" />
 $("#btncatsave").click(function () {
var Name = $("#txtName").val();
var formData = new FormData();
var totalFiles = document.getElementById("picfile").files.length;

                    var file = document.getElementById("picfile").files[0];
                    formData.append("FileUpload", file);
                    formData.append("Name", Name);

$.ajax({
                    type: "POST",
                    url: '/Category_Subcategory/Save_Category',
                    data: formData,
                    dataType: 'json',
                    contentType: false,
                    processData: false,
                    success: function (msg) {

                                 alert(msg);

                    },
                    error: function (error) {
                        alert("errror");
                    }
                });

});

 [HttpPost]
    public ActionResult Save_Category()
    {
      string Name=Request.Form[1]; 
      if (Request.Files.Count > 0)
        {
            HttpPostedFileBase file = Request.Files[0];
         }


    }

How to parse Excel (XLS) file in Javascript/HTML5

If you are ever wondering how to read a file from server this code might be helpful.

Restrictions :

  1. File should be in the server (Local/Remote).
  2. You will have to setup headers or have CORS google plugin.

<Head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script lang="javascript" src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.12.4/xlsx.core.min.js"></script>
</head>

<body>
    <script>
    /* set up XMLHttpRequest */


    // replace it with your file path in local server
    var url = "http://localhost/test.xlsx";

    var oReq = new XMLHttpRequest();
    oReq.open("GET", url, true);
    oReq.responseType = "arraybuffer";

    oReq.onload = function(e) {
        var arraybuffer = oReq.response;

        /* convert data to binary string */
        var data = new Uint8Array(arraybuffer);

        var arr = new Array();
        for (var i = 0; i != data.length; ++i) {
            arr[i] = String.fromCharCode(data[i]);
        }

        var bstr = arr.join("");

        var cfb = XLSX.read(bstr, { type: 'binary' });

        cfb.SheetNames.forEach(function(sheetName, index) {

            // Obtain The Current Row As CSV
            var fieldsObjs = XLS.utils.sheet_to_json(cfb.Sheets[sheetName]);

            fieldsObjs.map(function(field) {
                $("#my_file_output").append('<input type="checkbox" value="' + field.Fields + '">' + field.Fields + '<br>');
            });

        });
    }

    oReq.send();
    </script>
</body>
<div id="my_file_output">
</div>

</html>

Clear and reset form input fields

Why not use HTML-controlled items such as <input type="reset">

JQuery: Change value of hidden input field

It's simple as:

$('#action').val("1");

#action is hidden input field id.

How to insert new row to database with AUTO_INCREMENT column without specifying column names?

Even better, use DEFAULT instead of NULL. You want to store the default value, not a NULL that might trigger a default value.

But you'd better name all columns, with a piece of SQL you can create all the INSERT, UPDATE and DELETE's you need. Just check the information_schema and construct the queries you need. There is no need to do it all by hand, SQL can help you out.

SQL to Entity Framework Count Group-By

Here is a simple example of group by in .net core 2.1

var query = this.DbContext.Notifications.
            Where(n=> n.Sent == false).
            GroupBy(n => new { n.AppUserId })
            .Select(g => new { AppUserId = g.Key, Count =  g.Count() });

var query2 = from n in this.DbContext.Notifications
            where n.Sent == false
            group n by n.AppUserId into g
            select new { id = g.Key,  Count = g.Count()};

Which translates to:

SELECT [n].[AppUserId], COUNT(*) AS [Count]
FROM [Notifications] AS [n]
WHERE [n].[Sent] = 0
GROUP BY [n].[AppUserId]

How to set the env variable for PHP?

Try display phpinfo() by file and check this var.

What is the format specifier for unsigned short int?

From the Linux manual page:

h      A  following  integer conversion corresponds to a short int or unsigned short int argument, or a fol-
       lowing n conversion corresponds to a pointer to a short int argument.

So to print an unsigned short integer, the format string should be "%hu".

How can I check whether a variable is defined in Node.js?

Determine if property is existing (but is not a falsy value):

if (typeof query !== 'undefined' && query !== null){
   doStuff();
}

Usually using

if (query){
   doStuff();
}

is sufficient. Please note that:

if (!query){
   doStuff();
}

doStuff() will execute even if query was an existing variable with falsy value (0, false, undefined or null)

Btw, there's a sexy coffeescript way of doing this:

if object?.property? then doStuff()

which compiles to:

if ((typeof object !== "undefined" && object !== null ? object.property : void 0) != null) 

{
  doStuff();
}

iTerm2 keyboard shortcut - split pane navigation

Cmd+opt+?/?/?/? navigate similarly to vim's C-w hjkl.

How do I return the SQL data types from my query?

SELECT COLUMN_NAME,
       DATA_TYPE,
       CHARACTER_MAXIMUM_LENGTH
FROM information_schema.columns
WHERE TABLE_NAME = 'YOUR_TABLE_NAME'

You can use columns aliases for better looking output.

How to vertically align text in input type="text"?

Use padding to fake it since vertical-align doesn't work on text inputs.

jsFiddle example

CSS

.date-input {     
    width: 145px;
    padding-top: 80px;
}?

Pass Parameter to Gulp Task

If you want to use environment params and other utils as well such as log, you can use gulp-util

/* 
  $npm install gulp-util --save-dev
  $gulp --varName 123
*/
var util = require('gulp-util');
util.log(util.env.varName);

Update

gulp-util is now deprecated. You can use minimist instead.

var argv = require('minimist')(process.argv.slice(2));
console.dir(argv);

RegEx to match stuff between parentheses

You need to make your regex pattern 'non-greedy' by adding a '?' after the '.+'

By default, '*' and '+' are greedy in that they will match as long a string of chars as possible, ignoring any matches that might occur within the string.

Non-greedy makes the pattern only match the shortest possible match.

See Watch Out for The Greediness! for a better explanation.

Or alternately, change your regex to

\(([^\)]+)\)

which will match any grouping of parens that do not, themselves, contain parens.

Correct way to remove plugin from Eclipse

Inspired by sergionni's answer, I ended up doing the following steps:

Help --> Installation Details --> Installation History tab

In the Previous configurations table, you can select a configuration and see in the Configuration contents exactly which plugins were installed and are included in it.

It's easy to find the configuration that contains the plugin you want to remove, using the Compare button. This button is enabled when two configurations are selected.

After tracking the configuration that's responsible for that plugin, select the previous configuration and press the Revert button.

Note that if you revert to a configuration that isn't the one just right before the Current Installation, it causes any other plugins that were installed since, to be uninstalled as well.

Setting a windows batch file variable to the day of the week

If you can change format of short date in the PC to "ddd yyyy-MM-dd" (only first parameter 'ddd' is compulsory), then following command returns-

c:\>vol | date
The current date is: Mon 2014-12-01

Then you can write you batch file -

@echo off

vol | date | find /i "sun" > nul 
if not errorlevel 1 goto SUN

vol | date | find /i "mon" > nul 
if not errorlevel 1 goto MON

      # write block for other week days    

goto END

:SUN
set fname="sun"
goto BACKUP

:MON
set fname="mon"
goto BACKUP

      # write block for other week days

:BACKUP
echo %fname%

:END

Expanding tuples into arguments

Note that you can also expand part of argument list:

myfun(1, *("foo", "bar"))

Catch paste input

Script to remove special characters from all fields with class portlet-form-input-field:

// Remove special chars from input field on paste
jQuery('.portlet-form-input-field').bind('paste', function(e) {
    var textInput = jQuery(this);
    setTimeout(function() {
        textInput.val(replaceSingleEndOfLineCharactersInString(textInput.val()));
    }, 200);
});

function replaceSingleEndOfLineCharactersInString(value) {
    <%
        // deal with end-of-line characters (\n or \r\n) that will affect string length calculation,
        // also remove all non-printable control characters that can cause XML validation errors
    %>
    if (value != "") {
        value = value.replace(/(\x00|\x01|\x02|\x03|\x04|\x05|\x06|\x07|\x08|\x0B|\x0C|\x0E|\x0F|\x10|\x11|\x12|\x13|\x14|\x15|\x16|\x17|\x18|\x19|\x1A|\x1B|\x1C|\x1D|\x1E|\x1F|\x7F)/gm,'');
        return value = value.replace(/(\r\n|\n|\r)/gm,'##').replace(/(\#\#)/gm,"\r\n");
    }
}

Best HTML5 markup for sidebar

Update 17/07/27: As this is the most-voted answer, I should update this to include current information locally (with links to the references).

From the spec [1]:

The aside element represents a section of a page that consists of content that is tangentially related to the content of the parenting sectioning content, and which could be considered separate from that content. Such sections are often represented as sidebars in printed typography.

Great! Exactly what we're looking for. In addition, it is best to check on <section> as well.

The section element represents a generic section of a document or application. A section, in this context, is a thematic grouping of content. Each section should be identified, typically by including a heading (h1-h6 element) as a child of the section element.

...

A general rule is that the section element is appropriate only if the element’s contents would be listed explicitly in the document’s outline.

Excellent. Just what we're looking for. As opposed to <article> [2] which is for "self-contained" content, <section> allows for related content that isn't stand-alone, or generic enough for a <div> element.

As such, the spec seems to suggest that using Option 1, <aside> with <section> children is best practice.

References

  1. https://www.w3.org/TR/html51/sections.html#the-aside-element
  2. https://www.w3.org/TR/html51/sections.html#elementdef-article
  3. http://html5doctor.com/aside-revisited/

Capitalize the first letter of both words in a two word string

You could also use the snakecase package:

install.packages("snakecase")
library(snakecase)

name <- c("zip code", "state", "final count")
to_title_case(name)
#> [1] "Zip Code"    "State"       "Final Count"

# or 
to_upper_camel_case(name, sep_out = " ")
#> [1] "Zip Code"    "State"       "Final Count"

https://github.com/Tazinho/snakecase

How to set True as default value for BooleanField on Django?

I found the cleanest way of doing it is this.

Tested on Django 3.1.5

class MyForm(forms.Form):
    my_boolean = forms.BooleanField(required=False, initial=True)

I found the answer here

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

MySQL SELECT statement for the "length" of the field is greater than 1

Just in case anybody want to find how in oracle and came here (like me), the syntax is

select length(FIELD) from TABLE

just in case ;)

how to get the child node in div using javascript

If you give your table a unique id, its easier:

<div id="ctl00_ContentPlaceHolder1_Jobs_dlItems_ctl01_a"
    onmouseup="checkMultipleSelection(this,event);">
       <table id="ctl00_ContentPlaceHolder1_Jobs_dlItems_ctl01_a_table" 
              cellpadding="0" cellspacing="0" border="0" width="100%">
           <tr>
              <td style="width:50px; text-align:left;">09:15 AM</td>
              <td style="width:50px; text-align:left;">Item001</td>
              <td style="width:50px; text-align:left;">10</td>
              <td style="width:50px; text-align:left;">Address1</td>
              <td style="width:50px; text-align:left;">46545465</td>
              <td style="width:50px; text-align:left;">ref1</td>
           </tr>
       </table>
</div>


var multiselect = 
    document.getElementById(
               'ctl00_ContentPlaceHolder1_Jobs_dlItems_ctl01_a_table'
            ).rows[0].cells,
    timeXaddr = [multiselect[0].innerHTML, multiselect[2].innerHTML];

//=> timeXaddr now an array containing ['09:15 AM', 'Address1'];

TypeError: 'DataFrame' object is not callable

It seems you need DataFrame.var:

Normalized by N-1 by default. This can be changed using the ddof argument

var1 = credit_card.var()

Sample:

#random dataframe
np.random.seed(100)
credit_card = pd.DataFrame(np.random.randint(10, size=(5,5)), columns=list('ABCDE'))
print (credit_card)
   A  B  C  D  E
0  8  8  3  7  7
1  0  4  2  5  2
2  2  2  1  0  8
3  4  0  9  6  2
4  4  1  5  3  4

var1 = credit_card.var()
print (var1)
A     8.8
B    10.0
C    10.0
D     7.7
E     7.8
dtype: float64

var2 = credit_card.var(axis=1)
print (var2)
0     4.3
1     3.8
2     9.8
3    12.2
4     2.3
dtype: float64

If need numpy solutions with numpy.var:

print (np.var(credit_card.values, axis=0))
[ 7.04  8.    8.    6.16  6.24]

print (np.var(credit_card.values, axis=1))
[ 3.44  3.04  7.84  9.76  1.84]

Differences are because by default ddof=1 in pandas, but you can change it to 0:

var1 = credit_card.var(ddof=0)
print (var1)
A    7.04
B    8.00
C    8.00
D    6.16
E    6.24
dtype: float64

var2 = credit_card.var(ddof=0, axis=1)
print (var2)
0    3.44
1    3.04
2    7.84
3    9.76
4    1.84
dtype: float64