Programs & Examples On #Vi

vi is a family of text mode-oriented text editors.

vi/vim editor, copy a block (not usual action)

You can do it as you do in vi, for example to yank lines from 3020 to the end, execute this command (write the block to a file):

:3020,$ w /tmp/yank

And to write this block in another line/file, go to the desired position and execute next command (insert file written before):

:r /tmp/yank

(Reminder: don't forget to remove file: /tmp/yank)

Copy and paste content from one file to another file in vi

Another way could be to open the two files in two split buffers and use the following "snippet" after visual selection of the lines of interest.

:vnoremap <F4> :y<CR><C-W>Wr<Esc>p

How do I exit the Vim editor?

This is for the worst-case scenario of exiting Vim if you just want out, have no idea what you've done and you don't care what will happen to the files you opened.

Ctrl-cEnterEnterviEnterCtrl-\Ctrl-n:qa!Enter

This should get you out most of the time.

Some interesting cases where you need something like this:

  • iCtrl-ovg (you enter insert mode, then visual mode and then operator pending mode)

  • QappendEnter

  • iCtrl-ogQCtrl-r=Ctrl-k (thanks to porges for this case)

  • :set insertmode (this is a case when Ctrl-\Ctrl-n returns you to normal mode)


Edit: This answer was corrected due to cases above. It used to be:

EscEscEsc:qa!Enter

However, that doesn't work if you have entered Ex mode. In that case you would need to do:

viEnter:qa!Enter

So a complete command for "I don't want to know what I've done and I don't want to save anything, I just want out now!" would be

viEnterEscEscEsc:qa!Enter

How do I move to end of line in Vim?

Press A to enter edit mode starting at the end of the line.

What are the dark corners of Vim your mom never told you about?

% is also good when you want to diff files across two different copies of a project without wearing out the pinkies (from root of project1):

:vert diffs /project2/root/%

How do I use vim registers?

From vim's help page:

CTRL-R {0-9a-z"%#:-=.}                  *c_CTRL-R* *c_<C-R>*
        Insert the contents of a numbered or named register.  Between
        typing CTRL-R and the second character '"' will be displayed
        <...snip...>
        Special registers:
            '"' the unnamed register, containing the text of
                the last delete or yank
            '%' the current file name
            '#' the alternate file name
            '*' the clipboard contents (X11: primary selection)
            '+' the clipboard contents
            '/' the last search pattern
            ':' the last command-line
            '-' the last small (less than a line) delete
            '.' the last inserted text
                            *c_CTRL-R_=*
            '=' the expression register: you are prompted to
                enter an expression (see |expression|)
                (doesn't work at the expression prompt; some
                things such as changing the buffer or current
                window are not allowed to avoid side effects)
                When the result is a |List| the items are used
                as lines.  They can have line breaks inside
                too.
                When the result is a Float it's automatically
                converted to a String.
        See |registers| about registers.  {not in Vi}
        <...snip...>

How to run vi on docker container?

The command to run depends on what base image you are using.

For Alpine, vi is installed as part of the base OS. Installing vim would be:

apk -U add vim

For Debian and Ubuntu:

apt-get update && apt-get install -y vim

For CentOS, vi is usually installed with the base OS. For vim:

yum install -y vim

This should only be done in early development. Once you get a working container, the changes to files should be made to your image or configs stored outside of your container. Update your Dockerfile and other files it uses to build a new image. This certainly shouldn't be done in production since changes inside the container are by design ephemeral and will be lost when the container is replaced.

How do I tidy up an HTML file's indentation in VI?

I use this script: https://github.com/maksimr/vim-jsbeautify

In the above link you have all the info:

  1. Install
  2. Configure (copy from the first example)
  3. Run :call HtmlBeautify()

Does the job beautifully!

Copy all the lines to clipboard

I couldn't copy files using the answers above but I have putty and I found a workaround on Quora.

  1. Change settings of your PuTTY session, go to logging and change it to "printable characters". Set the log file
  2. Do a cat of the respective file
  3. Go to the file you set in step #1 and you will have your content in the log file.

Note: it copies all the printed characters of that session to the log file, so it will get big eventually. In that case, delete the log file and cat the target file so you get that particular file's content copied on your machine.

How to duplicate a whole line in Vim?

For someone who doesn't know vi, some answers from above might mislead him with phrases like "paste ... after/before current line".
It's actually "paste ... after/before cursor".

yy or Y to copy the line
or
dd to delete the line

then

p to paste the copied or deleted text after the cursor
or
P to paste the copied or deleted text before the cursor


For more key bindings, you can visit this site: vi Complete Key Binding List

How do I fix the indentation of an entire file in Vi?

For vi Editor, use :insert. This will keep all your formatting and not insert auto-indenting.Once done press escape to view the actual formatted file otherwise you'l see some garbage characters. like ^I e.g:

public static void main(String[] args) {
^I
^I System.out.println("Some Garbage printed upon using :insert"); 
}

Delete newline in Vim

If you are on the first line, pressing (upper case) J will join that line and the next line together, removing the newline. You can also combine this with a count, so pressing 3J will combine all 3 lines together.

How to go back (ctrl+z) in vi/vim

On a mac you can also use command Z and that will go undo. I'm not sure why, but sometimes it stops, and if your like me and vimtutor is on the bottom of that long list of things you need to learn, than u can just close the window and reopen it and should work fine.

How can I delete multiple lines in vi?

If you prefer a non-visual mode method and acknowledge the line numbers, I would like to suggest you an another straightforward way.

Example

I want to delete text from line 45 to line 101.

My method suggests you to type a below command in command-mode:

45Gd101G

It reads:

Go to line 45 (45G) then delete text (d) from the current line to the line 101 (101G).

Note that on vim you might use gg in stead of G.

Compare to the @Bonnie Varghese's answer which is:

:45,101d[enter]

The command above from his answer requires 9 times typing including enter, where my answer require 8 - 10 times typing. Thus, a speed of my method is comparable.

Personally, I myself prefer 45Gd101G over :45,101d because I like to stick to the syntax of the vi's command, in this case is:

+---------+----------+--------------------+
| syntax  | <motion> | <operator><motion> |
+---------+----------+--------------------+
| command |   45G    |        d101G       |
+---------+----------+--------------------+

Auto-indent spaces with C in vim?

Simply run:

user@host:~ $ echo set autoindent >> .vimrc

Vim delete blank lines

Press delete key in insert mode to remove blank lines.

Move entire line up and down in Vim

Assuming the cursor is on the line you like to move.

Moving up and down: :m for move

:m +1 - moves down 1 line

:m -2 - move up 1 lines

(Note you can replace +1 with any numbers depending on how many lines you want to move it up or down, ie +2 would move it down 2 lines, -3 would move it up 2 lines)

To move to specific line

:set number - display number lines (easier to see where you are moving it to)

:m 3 - move the line after 3rd line (replace 3 to any line you'd like)

Moving multiple lines:

V (i.e. Shift-V) and move courser up and down to select multiple lines in VIM

once selected hit : and run the commands above, m +1 etc

Tab key == 4 spaces and auto-indent after curly braces in Vim

The auto-indent is based on the current syntax mode. I know that if you are editing Foo.java, then entering a { and hitting Enter indents the following line.

As for tabs, there are two settings. Within Vim, type a colon and then "set tabstop=4" which will set the tabs to display as four spaces. Hit colon again and type "set expandtab" which will insert spaces for tabs.

You can put these settings in a .vimrc (or _vimrc on Windows) in your home directory, so you only have to type them once.

Renaming the current file in Vim

sav person.haml_spec.rb | call delete(expand('#'))

Indent multiple lines quickly in vi

Use the > command. To indent five lines, 5>>. To mark a block of lines and indent it, Vjj> to indent three lines (Vim only). To indent a curly-braces block, put your cursor on one of the curly braces and use >% or from anywhere inside block use >iB.

If you’re copying blocks of text around and need to align the indent of a block in its new location, use ]p instead of just p. This aligns the pasted block with the surrounding text.

Also, the shiftwidth setting allows you to control how many spaces to indent.

How to replace a character by a newline in Vim

In the syntax s/foo/bar, \r and \n have different meanings, depending on context.


Short:

For foo:

\r == "carriage return" (CR / ^M)
\n == matches "line feed" (LF) on Linux/Mac, and CRLF on Windows

For bar:

\r == produces LF on Linux/Mac, CRLF on Windows
\n == "null byte" (NUL / ^@)

When editing files in linux (i.e. on a webserver) that were initially created in a windows environment and uploaded (i.e. FTP/SFTP) - all the ^M's you see in vim, are the CR's which linux does not translate as it uses only LF's to depict a line break.


Longer (with ASCII numbers):

NUL == 0x00 == 0 == Ctrl + @ == ^@ shown in vim
LF == 0x0A == 10 == Ctrl + J
CR == 0x0D == 13 == Ctrl + M == ^M shown in vim

Here is a list of the ASCII control characters. Insert them in Vim via Ctrl + V,Ctrl + ---key---.

In Bash or the other Unix/Linux shells, just type Ctrl + ---key---.

Try Ctrl + M in Bash. It's the same as hitting Enter, as the shell realizes what is meant, even though Linux systems use line feeds for line delimiting.

To insert literal's in bash, prepending them with Ctrl + V will also work.

Try in Bash:

echo ^[[33;1mcolored.^[[0mnot colored.

This uses ANSI escape sequences. Insert the two ^['s via Ctrl + V, Esc.

You might also try Ctrl + V,Ctrl + M, Enter, which will give you this:

bash: $'\r': command not found

Remember the \r from above? :>

This ASCII control characters list is different from a complete ASCII symbol table, in that the control characters, which are inserted into a console/pseudoterminal/Vim via the Ctrl key (haha), can be found there.

Whereas in C and most other languages, you usually use the octal codes to represent these 'characters'.

If you really want to know where all this comes from: The TTY demystified. This is the best link you will come across about this topic, but beware: There be dragons.


TL;DR

Usually foo = \n, and bar = \r.

Search for string and get count in vi editor

I suggest doing:

  1. Search either with * to do a "bounded search" for what's under the cursor, or do a standard /pattern search.
  2. Use :%s///gn to get the number of occurrences. Or you can use :%s///n to get the number of lines with occurrences.

** I really with I could find a plug-in that would giving messaging of "match N of N1 on N2 lines" with every search, but alas.

Note: Don't be confused by the tricky wording of the output. The former command might give you something like 4 matches on 3 lines where the latter might give you 3 matches on 3 lines. While technically accurate, the latter is misleading and should say '3 lines match'. So, as you can see, there really is never any need to use the latter ('n' only) form. You get the same info, more clearly, and more by using the 'gn' form.

Go to beginning of line without opening new line in VI

You can also use

:-0

This sets the cursor at the present line (blank here) at the 0 column.

What is your most productive shortcut with Vim?

After mapping the below to a simple key combo, the following are very useful for me:

Jump into a file while over its path

gf

get full path name of existing file

:r!echo %:p

get directory of existing file

:r!echo %:p:h

run code:

:!ruby %:p

ruby abbreviations:

ab if_do if end<esc>bi<cr><esc>xhxO
ab if_else if end<esc>bi<cr><esc>xhxO else<esc>bhxA<cr> <esc>k$O
ab meth def method<cr>end<esc>k<esc>:s/method/
ab klas class KlassName<cr>end<esc>k<esc>:s/KlassName/
ab mod module ModName<cr>end<esc>k<esc>:s/ModName/

run current program:

   map ,rby :w!<cr>:!ruby %:p<cr>

check syntax of current program:

   map ,c :w!<cr>:!ruby -c %:p<cr>

run all specs for current spec program:

   map ,s :w!<cr>:!rspec %:p<cr>

crack it open irb:

   map ,i :w!<cr>:!irb<cr>

rspec abreviations:

   ab shared_examples shared_examples_for "behavior here" do<cr>end
   ab shared_behavior describe "description here" do<cr>  before :each do<cr>end<cr>it_should_behave_like "behavior here"<cr><bs>end<cr>
   ab describe_do describe "description here" do<cr>end
   ab context_do describe "description here" do<cr>end
   ab it_do it "description here" do<cr>end
   ab before_each before :each do<cr>end<cr>

rails abbreviations:

user authentication:

     ab userc <esc>:r $VIMRUNTIME/Templates/Ruby/c-users.rb<cr>
     ab userv <esc>:r $VIMRUNTIME/Templates/Ruby/v-users.erb<cr>
     ab userm <esc>:r $VIMRUNTIME/Templates/Ruby/m-users.rb<cr>

open visually selected url in firefox:

"function
   function open_url_in_firefox:(copy_text)
     let g:open_url_in_firefox="silent !open -a \"firefox\" \"".a:copy_text."\""
     exe g:open_url_in_firefox
   endfunction

"abbreviations
   map ,d :call open_url_in_firefox:(expand("%:p"))<cr>
   map go y:call open_url_in_firefox:(@0)<cr> 

rspec: run spec containing current line:

"function
   function run_single_rspec_test:(the_test)
     let g:rake_spec="!rspec ".a:the_test.":".line(".")
     exe g:rake_spec
   endfunction

"abbreviations
   map ,s :call run_single_rspec_test:(expand("%:p"))<cr>

rspec-rails: run spec containing current line:

"function
   function run_single_rails_rspec_test:(the_test)
     let g:rake_spec="!rake spec SPEC=\"".a:the_test.":".line(".")."\""
     exe g:rake_spec
   endfunction

"abbreviations
   map ,r :call run_single_rails_rspec_test:(expand("%:p"))<cr>

rspec-rails: run spec containing current line with debugging:

"function
   function run_spec_containing_current_line_with_debugging:(the_test)
     let g:rake_spec="!rake spec SPEC=\"".a:the_test.":".line(".")." -d\""
     exe g:rake_spec
   endfunction

"abbreviations
   map ,p :call run_spec_containing_current_line_with_debugging:(expand("%:p")) <cr>

html

"abbreviations

  "ab htm <html><cr><tab><head><cr></head><cr><body><cr></body><cr><bs><bs></html>
   ab template_html <script type = 'text/template' id = 'templateIdHere'></script>
   ab script_i <script src=''></script>
   ab script_m <script><cr></script>
   ab Tpage <esc>:r ~/.vim/templates/pageContainer.html<cr>
   ab Ttable <esc>:r ~/.vim/templates/listTable.html<cr>

"function to render common html template

   function html:() 
     call feedkeys( "i", 't' )
     call feedkeys("<html>\<cr>  <head>\<cr></head>\<cr><body>\<cr> ", 't')
     call feedkeys( "\<esc>", 't' )
     call feedkeys( "i", 't' )
     call include_js:()
     call feedkeys("\<bs>\<bs></body>\<cr> \<esc>hxhxi</html>", 't')
   endfunction

javascript

"jasmine.js
  "abbreviations
   ab describe_js describe('description here', function(){<cr>});
   ab context_js context('context here', function(){<cr>});
   ab it_js it('expectation here', function(){<cr>});
   ab expect_js expect().toEqual();
   ab before_js beforeEach(function(){<cr>});
   ab after_js afterEach(function(){<cr>});

"function abbreviations

   ab fun1 function(){}<esc>i<cr><esc>ko
   ab fun2 x=function(){};<esc>hi<cr>
   ab fun3 var x=function(){<cr>};

"method for rendering inclusion of common js files

   function include_js:()
     let includes_0  = "  <link   type = 'text\/css' rel = 'stylesheet' href = '\/Users\/johnjimenez\/common\/stylesheets\/jasmine-1.1.0\/jasmine.css'\/>"
     let includes_1  = "  <link   type = 'text\/css' rel = 'stylesheet' href = '\/Users\/johnjimenez\/common\/stylesheets\/screen.css'\/>"
     let includes_2  = "<script type = 'text\/javascript' src = '\/Users\/johnjimenez\/common\/javascripts\/jquery-1.7.2\/jquery-1.7.2.js'><\/script>"
     let includes_3  = "<script type = 'text\/javascript' src = '\/Users\/johnjimenez\/common\/javascripts\/underscore\/underscore.js'><\/script>"
     let includes_4  = "<script type = 'text\/javascript' src = '\/Users\/johnjimenez\/common\/javascripts\/backbone-0.9.2\/backbone.js'><\/script>"
     let includes_5  = "<script type = 'text\/javascript' src = '\/Users\/johnjimenez\/common\/javascripts\/jasmine-1.1.0\/jasmine.js'><\/script>"
     let includes_6  = "<script type = 'text\/javascript' src = '\/Users\/johnjimenez\/common\/javascripts\/jasmine-1.1.0\/jasmine-html.js'><\/script>"
     let includes_7  = "<script>"
     let includes_8  = "  describe('default page', function(){ "
     let includes_9  = "it('should have an html tag', function(){ "
     let includes_10 = "  expect( $( 'head' ).html() ).not.toMatch(\/^[\\s\\t\\n]*$\/);"
     let includes_11  = "});"
     let includes_12 = "});"
     let includes_13 = "$(function(){"
     let includes_14 = "jasmine.getEnv().addReporter( new jasmine.TrivialReporter() );"
     let includes_15 = "jasmine.getEnv().execute();"
     let includes_16 = "});"
     let includes_17 = "\<bs>\<bs><\/script>"

     let j = 0

     while j < 18
       let entry = 'includes_' . j
       call feedkeys( {entry}, 't' )
       call feedkeys( "\<cr>", 't' )
       let j = j + 1
     endwhile

   endfunction

"jquery

  "abbreviations

     ab docr $(document).ready(function(){});
     ab jqfun $(<cr>function(){<cr>}<cr>);

Find and replace strings in vim on multiple lines

In vim if you are confused which all lines will be affected, Use below

 :%s/foo/bar/gc  

Change each 'foo' to 'bar', but ask for confirmation first. Press 'y' for yes and 'n' for no. Dont forget to save after that

:wq

How to delete selected text in the vi editor

Do it the vi way.

To delete 5 lines press: 5dd ( 5 delete )

To select ( actually copy them to the clipboard ) you type: 10yy

It is a bit hard to grasp, but very handy to learn when using those remote terminals

Be aware of the learning curves for some editors:


(source: calver at unix.rulez.org)

Setting the Vim background colors

Try adding

set background=dark

to your .gvimrc too. This work well for me.

How to take off line numbers in Vi?

If you are talking about show line number command in vi/vim

you could use

set nu

in commandline mode to turn on and

set nonu

will turn off the line number display or

set nu!

to toggle off display of line numbers

How to effectively work with multiple files in Vim

if you're on osx and want to be able to click on your tabs, use MouseTerm and SIMBL (taken from here). Also, check out this related discussion.

How do I join two lines in vi?

In Vim you can also use gJ.

??

Is there a short cut for going back to the beginning of a file by vi editor?

After opening a file using vi

1) You can press Shift + g to go the end of the file

and

2) Press g twice to go to the beginning of the file

NOTE : - g is case-sensitive (Thanks to @Ben for pointing it out)

Replace tabs with spaces in vim

If you want to keep your \t equal to 8 spaces then consider setting:

   set softtabstop=2 tabstop=8 shiftwidth=2

This will give you two spaces per <TAB> press, but actual \t in your code will still be viewed as 8 characters.

/etc/apt/sources.list" E212: Can't open file for writing

I got this error when my directory path is incorrect, ensure your directory names and path are correct

Traversing text in Insert mode

You seem to misuse vim, but that's likely due to not being very familiar with it.

The right way is to press Esc, go where you want to do a small correction, fix it, go back and keep editing. It is effective because Vim has much more movements than usual character forward/backward/up/down. After you learn more of them, this will happen to be more productive.

Here's a couple of use-cases:

  • You accidentally typed "accifentally". No problem, the sequence EscFfrdA will correct the mistake and bring you back to where you were editing. The Ff movement will move your cursor backwards to the first encountered "f" character. Compare that with Ctrl+DeldEnd, which does virtually the same in a casual editor, but takes more keystrokes and makes you move your hand out of the alphanumeric area of the keyboard.
  • You accidentally typed "you accidentally typed", but want to correct it to "you intentionally typed". Then Esc2bcw will erase the word you want to fix and bring you to insert mode, so you can immediately retype it. To get back to editing, just press A instead of End, so you don't have to move your hand to reach the End key.
  • You accidentally typed "mouse" instead of "mice". No problem - the good old Ctrl+w will delete the previous word without leaving insert mode. And it happens to be much faster to erase a small word than to fix errors within it. I'm so used to it that I had closed the browser page when I was typing this message...!
  • Repetition count is largely underused. Before making a movement, you can type a number; and the movement will be repeated this number of times. For example, 15h will bring your cursor 15 characters back and 4j will move your cursor 4 lines down. Start using them and you'll get used to it soon. If you made a mistake ten characters back from your cursor, you'll find out that pressing the key 10 times is much slower than the iterative approach to moving the cursor. So you can instead quickly type the keys 12h (as a rough of guess how many characters back that you need to move your cursor), and immediately move forward twice with ll to quickly correct the error.

But, if you still want to do small text traversals without leaving insert mode, follow rson's advice and use Ctrl+O. Taking the first example that I mentioned above, Ctrl+OFf will move you to a previous "f" character and leave you in insert mode.

vim line numbers - how to have them on by default?

If you don't want to add/edit .vimrc, you can start with

vi "+set number" /path/to/file

Make Vim show ALL white spaces as a character

highlight search

:set hlsearch 

in .vimrc that is

and search for space tabs and carriage returns

/ \|\t\|\r

or search for all whitespace characters

/\s

of search for all non white space characters (the whitespace characters are not shown, so you see the whitespace characters between words, but not the trailing whitespace characters)

/\S

to show all trailing white space characters - at the end of the line

/\s$

PHP AES encrypt / decrypt

If you are using MCRYPT_RIJNDAEL_128, try rtrim($output, "\0\3"). If the length of the string is less than 16, the decrypt function will return a string with length of 16 characters, adding 03 at the end.

You can easily check this, e.g. by trying:

$string = "TheString";
$decrypted_string = decrypt_function($stirng, $key);

echo bin2hex($decrypted_string)."=".bin2hex("TheString");

Move textfield when keyboard appears swift

Just enclose your textbox inside a view and then override inputAccessoryView returning the view. Important: Your view should be created programmatically. Do not use @IBOutlets.

 override var inputAccessoryView: UIView? {
    get {
        return newlyProgramaticallyCreatedView
    }}

How to check if a variable is null or empty string or all whitespace in JavaScript?

A non-jQuery solution that more closely mimics IsNullOrWhiteSpace, but to detect null, empty or all-spaces only:

function isEmptyOrSpaces(str){
    return str === null || str.match(/^ *$/) !== null;
}

...then:

var addr = '  ';

if(isEmptyOrSpaces(addr)){
    // error 
}

* EDIT * Please note that op specifically states:

I need to check to see if a var is null or has any empty spaces or for that matter just blank.

So while yes, "white space" encompasses more than null, spaces or blank my answer is intended to answer op's specific question. This is important because op may NOT want to catch things like tabs, for example.

Swift UIView background color opacity

You can set background color of view to the UIColor with alpha, and not affect view.alpha:

view.backgroundColor = UIColor(white: 1, alpha: 0.5)

or

view.backgroundColor = UIColor.red.withAlphaComponent(0.5)

Do on-demand Mac OS X cloud services exist, comparable to Amazon's EC2 on-demand instances?

List last updated on December 1, 2020:

As of November 30, 2020, AWS now has EC2 Mac instances:

We previously used and had good experiences with:

Here are some other sites that I am aware of:

When we were with MacStadium, we loved them. We had great connectivity/uptime. When I've needed hands-on support to plug in a Time Machine backup, they've been great. They performed a seamless upgrade to better hardware for us over one weekend (when we could afford a bit of downtime), and that went off without a hitch. Highly recommended. (Not affiliated - just happy).

In April of 2020, we stopped using MacStadium, simply because we no longer needed a Mac server. If I need another Mac host, I would be happy to go back to them.

Callback function for JSONP with jQuery AJAX

$.ajax({
        url: 'http://url.of.my.server/submit',
        dataType: "jsonp",
        jsonp: 'callback',
        jsonpCallback: 'jsonp_callback'
    });

jsonp is the querystring parameter name that is defined to be acceptable by the server while the jsonpCallback is the javascript function name to be executed at the client.
When you use such url:

url: 'http://url.of.my.server/submit?callback=?'

the question mark ? at the end instructs jQuery to generate a random function while the predfined behavior of the autogenerated function will just invoke the callback -the sucess function in this case- passing the json data as a parameter.

$.ajax({
        url: 'http://url.of.my.server/submit?callback=?',
        success: function (data, status) {
            mySurvey.closePopup();
        },
        error: function (xOptions, textStatus) {
            mySurvey.closePopup();
        }
    });


The same goes here if you are using $.getJSON with ? placeholder it will generate a random function while the predfined behavior of the autogenerated function will just invoke the callback:

$.getJSON('http://url.of.my.server/submit?callback=?',function(data){
//process data here
});

How to delete the contents of a folder?

As a oneliner:

import os

# Python 2.7
map( os.unlink, (os.path.join( mydir,f) for f in os.listdir(mydir)) )

# Python 3+
list( map( os.unlink, (os.path.join( mydir,f) for f in os.listdir(mydir)) ) )

A more robust solution accounting for files and directories as well would be (2.7):

def rm(f):
    if os.path.isdir(f): return os.rmdir(f)
    if os.path.isfile(f): return os.unlink(f)
    raise TypeError, 'must be either file or directory'

map( rm, (os.path.join( mydir,f) for f in os.listdir(mydir)) )

React - how to pass state to another component

Move all of your state and your handleClick function from Header to your MainWrapper component.

Then pass values as props to all components that need to share this functionality.

class MainWrapper extends React.Component {
    constructor() {
        super();
        this.state = {
            sidbarPushCollapsed: false,
            profileCollapsed: false
        };
        this.handleClick = this.handleClick.bind(this);
    }
    handleClick() {
        this.setState({
            sidbarPushCollapsed: !this.state.sidbarPushCollapsed,
            profileCollapsed: !this.state.profileCollapsed

        });
    }
    render() {
        return (
           //...
           <Header 
               handleClick={this.handleClick} 
               sidbarPushCollapsed={this.state.sidbarPushCollapsed}
               profileCollapsed={this.state.profileCollapsed} />
        );

Then in your Header's render() method, you'd use this.props:

<button type="button" id="sidbarPush" onClick={this.props.handleClick} profile={this.props.profileCollapsed}>

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

As @FelixKling pointed out, the most likely scenario is that the nodes you are looking for do not exist (yet).

However, modern development practices can often manipulate document elements outside of the document tree either with DocumentFragments or simply detaching/reattaching current elements directly. Such techniques may be used as part of JavaScript templating or to avoid excessive repaint/reflow operations while the elements in question are being heavily altered.

Similarly, the new "Shadow DOM" functionality being rolled out across modern browsers allows elements to be part of the document, but not query-able by document.getElementById and all of its sibling methods (querySelector, etc.). This is done to encapsulate functionality and specifically hide it.

Again, though, it is most likely that the element you are looking for simply is not (yet) in the document, and you should do as Felix suggests. However, you should also be aware that that is increasingly not the only reason that an element might be unfindable (either temporarily or permanently).

Laravel Eloquent: How to get only certain columns from joined tables

For Laravel >= 5.2

Use the ->pluck() method

$roles = DB::table('roles')->pluck('title');

If you would like to retrieve an array containing the values of a single column, you may use the pluck method


For Laravel <= 5.1

Use the ->lists() method

$roles = DB::table('roles')->lists('title');

This method will return an array of role titles. You may also specify a custom key column for the returned array:

How to tell which row number is clicked in a table?

A simple and jQuery free solution:

document.querySelector('#elitable').onclick = function(ev) {
   // ev.target <== td element
   // ev.target.parentElement <== tr
   var index = ev.target.parentElement.rowIndex;
}

Bonus: It works even if rows are added/removed dynamically

How would I extract a single file (or changes to a file) from a git stash?

Short answer

To see the whole file: git show stash@{0}:<filename>

To see the diff: git diff stash@{0}^1 stash@{0} -- <filename>

I need to learn Web Services in Java. What are the different types in it?

The SOAP WS supports both remote procedure call (i.e. RPC) and message oriented middle-ware (MOM) integration styles. The Restful Web Service supports only RPC integration style.

The SOAP WS is transport protocol neutral. Supports multiple protocols like HTTP(S), Messaging, TCP, UDP SMTP, etc. The REST is transport protocol specific. Supports only HTTP or HTTPS protocols.

The SOAP WS permits only XML data format.You define operations, which tunnels through the POST. The focus is on accessing the named operations and exposing the application logic as a service. The REST permits multiple data formats like XML, JSON data, text, HTML, etc. Any browser can be used because the REST approach uses the standard GET, PUT, POST, and DELETE Web operations. The focus is on accessing the named resources and exposing the data as a service. REST has AJAX support. It can use the XMLHttpRequest object. Good for stateless CRUD (Create, Read, Update, and Delete) operations. GET - represent() POST - acceptRepresention() PUT - storeRepresention() DELETE - removeRepresention()

SOAP based reads cannot be cached. REST based reads can be cached. Performs and scales better. SOAP WS supports both SSL security and WS-security, which adds some enterprise security features like maintaining security right up to the point where it is needed, maintaining identities through intermediaries and not just point to point SSL only, securing different parts of the message with different security algorithms, etc. The REST supports only point-to-point SSL security. The SSL encrypts the whole message, whether all of it is sensitive or not. The SOAP has comprehensive support for both ACID based transaction management for short-lived transactions and compensation based transaction management for long-running transactions. It also supports two-phase commit across distributed resources. The REST supports transactions, but it is neither ACID compliant nor can provide two phase commit across distributed transactional resources as it is limited by its HTTP protocol.

The SOAP has success or retry logic built in and provides end-to-end reliability even through SOAP intermediaries. REST does not have a standard messaging system, and expects clients invoking the service to deal with communication failures by retrying.

source http://java-success.blogspot.in/2012/02/java-web-services-interview-questions.html

How to convert IPython notebooks to PDF and HTML?

  1. Save as HTML ;
  2. Ctrl + P ;
  3. Save as PDF.

Can I scale a div's height proportionally to its width using CSS?

You can use the view width to set the height. 100 vw is 100% of the width. height: 60vw; would make the height 60% of the width.

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

That's simple. You can set option to display only week days in toLocaleDateString() to get the names. For example:

(new Date()).toLocaleDateString('en-US',{ weekday: 'long'}) will return only the day of the week. And (new Date()).toLocaleDateString('en-US',{ month: 'long'}) will return only the month of the year.

Skip first entry in for loop in python?

The best way to skip the first item(s) is:

from itertools import islice
for car in islice(cars, 1, None):
    # do something

islice in this case is invoked with a start-point of 1, and an end point of None, signifying the end of the iterator.

To be able to skip items from the end of an iterable, you need to know its length (always possible for a list, but not necessarily for everything you can iterate on). for example, islice(cars, 1, len(cars)-1) will skip the first and last items in the cars list.

How to pass variable as a parameter in Execute SQL Task SSIS?

A little late to the party, but this is how I did it for an insert:

DECLARE @ManagerID AS Varchar (25) = 'NA'
DECLARE @ManagerEmail AS Varchar (50) = 'NA'
Declare @RecordCount AS int = 0

SET @ManagerID = ?
SET @ManagerEmail = ?
SET @RecordCount = ?

INSERT INTO...

Oracle "Partition By" Keyword

the over partition keyword is as if we are partitioning the data by client_id creation a subset of each client id

select client_id, operation_date,
       row_number() count(*) over (partition by client_id order by client_id ) as operationctrbyclient
from client_operations e
order by e.client_id;

this query will return the number of operations done by the client_id

Can I call curl_setopt with CURLOPT_HTTPHEADER multiple times to set multiple headers?

/**
 * If $header is an array of headers
 * It will format and return the correct $header
 * $header = [
 *  'Accept' => 'application/json',
 *  'Content-Type' => 'application/x-www-form-urlencoded'
 * ];
 */
$i_header = $header;
if(is_array($i_header) === true){
    $header = [];
    foreach ($i_header as $param => $value) {
        $header[] = "$param: $value";
    }
}

Javascript validation: Block special characters

I think checking keypress events is not completely adequate, as I believe users can copy/paste into input boxes without triggering a keypress.

So onblur is probably somewhat more reliable (but is less immediate).

To truly make sure characters you don't want are not entered into input boxes (or textareas, etc.), I think you will need to

  1. check keypress (if you want to give immediate feedback) and
  2. also check onblur,
  3. as well as validating inputs on the server (which is the only real way to make sure nothing unwanted gets into your data).

The code samples in the other answers will work fine for doing the client-side checks (just don't rely only on checking keypress events), but as was pointed out in the accepted answer, a server-side check is really required.

Create a directly-executable cross-platform GUI app using Python

For the GUI itself:

PyQT is pretty much the reference.

Another way to develop a rapid user interface is to write a web app, have it run locally and display the app in the browser.

Plus, if you go for the Tkinter option suggested by lubos hasko you may want to try portablepy to have your app run on Windows environment without Python.

How to stop/shut down an elasticsearch node?

Stopping the service and killing the daemon are indeed the correct ways to shutdown a node. However, it's not recommended to do so directly if you want to take down a node for maintenance. In fact, if you don't have replicas you will lose data.

When you directly shutdown a node, Elasticsearch will wait for 1m (default time) for it to come back online. If it doesn't, then it will start to allocate the shards from that node to other nodes wasting lots of IO.

A typical approach would be to disable shard allocation temporarily by issuing:

PUT _cluster/settings
{
  "persistent": {
    "cluster.routing.allocation.enable": "none"
  }
}

Now, when you take down a node, ES won't try to allocate shard from that node to other nodes and you can perform you maintenance activity and then once the node is up, you can enable shard allocation again:

PUT _cluster/settings
{
  "persistent": {
    "cluster.routing.allocation.enable": "all"
  }
}

Source: https://www.elastic.co/guide/en/elasticsearch/reference/5.5/restart-upgrade.html

If you don't have replicas for all your indexes, then performing this type of activity will have downtime on some of the indexes. A cleaner way in this case would be to migrate all the shards to other nodes before taking the node down:

PUT _cluster/settings
{
  "transient" : {
    "cluster.routing.allocation.exclude._ip" : "10.0.0.1"
  }
}

This will move all shards from 10.0.0.1 to other nodes (will take time depending on the data). Once everything is done, you can kill the node, perform maintenance and get it back online. This is a slower operation and is not required if you have replicas.

(Instead of _ip, _id, _name with wildcards will work just fine.)

More information: https://www.elastic.co/guide/en/elasticsearch/reference/5.5/allocation-filtering.html

Other answers have explained how to kill a process.

delete image from folder PHP

You can delete files in PHP using the unlink() function.

unlink('path/to/file.jpg');

Convert a string date into datetime in Oracle

Hey I had the same problem. I tried to convert '2017-02-20 12:15:32' varchar to a date with TO_DATE('2017-02-20 12:15:32','YYYY-MM-DD HH24:MI:SS') and all I received was 2017-02-20 the time disappeared

My solution was to use TO_TIMESTAMP('2017-02-20 12:15:32','YYYY-MM-DD HH24:MI:SS') now the time doesn't disappear.

Heatmap in matplotlib with pcolor?

Main issue is that you first need to set the location of your x and y ticks. Also, it helps to use the more object-oriented interface to matplotlib. Namely, interact with the axes object directly.

import matplotlib.pyplot as plt
import numpy as np
column_labels = list('ABCD')
row_labels = list('WXYZ')
data = np.random.rand(4,4)
fig, ax = plt.subplots()
heatmap = ax.pcolor(data)

# put the major ticks at the middle of each cell, notice "reverse" use of dimension
ax.set_yticks(np.arange(data.shape[0])+0.5, minor=False)
ax.set_xticks(np.arange(data.shape[1])+0.5, minor=False)


ax.set_xticklabels(row_labels, minor=False)
ax.set_yticklabels(column_labels, minor=False)
plt.show()

Hope that helps.

Error : getaddrinfo ENOTFOUND registry.npmjs.org registry.npmjs.org:443

First you need to use this command

npm config set registry https://registry.your-registry.npme.io/

This we are doing to set our companies Enterprise registry as our default registry.

You can try other given solutions also.

Insert multiple rows with one query MySQL

Here are a few ways to do it

INSERT INTO pxlot (realname,email,address,phone,status,regtime,ip) 
select '$realname','$email','$address','$phone','0','$dateTime','$ip' 
from SOMETABLEWITHTONSOFROWS LIMIT 3;

or

INSERT INTO pxlot (realname,email,address,phone,status,regtime,ip) 
select '$realname','$email','$address','$phone','0','$dateTime','$ip'
union all select '$realname','$email','$address','$phone','0','$dateTime','$ip'
union all select '$realname','$email','$address','$phone','0','$dateTime','$ip'

or

INSERT INTO pxlot (realname,email,address,phone,status,regtime,ip) 
values ('$realname','$email','$address','$phone','0','$dateTime','$ip')
,('$realname','$email','$address','$phone','0','$dateTime','$ip')
,('$realname','$email','$address','$phone','0','$dateTime','$ip')

To prevent a memory leak, the JDBC Driver has been forcibly unregistered

This is purely driver registration/deregistration issue in mysql`s driver or tomcats webapp-classloader. Copy mysql driver into tomcats lib folder (so its loaded by jvm directly, not by tomcat), and message will be gone. That makes mysql jdbc driver to be unloaded only at JVM shutdown, and noone cares about memory leaks then.

How to continue the code on the next line in VBA

(i, j, n + 1) = k * b_xyt(xi, yi, tn) / (4 * hx * hy) * U_matrix(i + 1, j + 1, n) + _
(k * (a_xyt(xi, yi, tn) / hx ^ 2 + d_xyt(xi, yi, tn) / (2 * hx)))

From ms support

To continue a statement from one line to the next, type a space followed by the line-continuation character [the underscore character on your keyboard (_)].

You can break a line at an operator, list separator, or period.

The type or namespace cannot be found (are you missing a using directive or an assembly reference?)

You need to add the following line:

using FootballLeagueSystem;

into your all your classes (MainMenu.cs, programme.cs, etc.) that use Login.

At the moment the compiler can't find the Login class.

Running EXE with parameters

To start the process with parameters, you can use following code:

string filename = Path.Combine(cPath,"HHTCtrlp.exe");
var proc = System.Diagnostics.Process.Start(filename, cParams);

To kill/exit the program again, you can use following code:

proc.CloseMainWindow(); 
proc.Close();

How do I delete rows in a data frame?

Here's a quick and dirty function to remove a row by index.

removeRowByIndex <- function(x, row_index) {
  nr <- nrow(x)
  if (nr < row_index) {
    print('row_index exceeds number of rows')
  } else if (row_index == 1)
  {
    return(x[2:nr, ])
  } else if (row_index == nr) {
    return(x[1:(nr - 1), ])
  } else {
    return (x[c(1:(row_index - 1), (row_index + 1):nr), ])
  }
}

It's main flaw is it the row_index argument doesn't follow the R pattern of being a vector of values. There may be other problems as I only spent a couple of minutes writing and testing it, and have only started using R in the last few weeks. Any comments and improvements on this would be very welcome!

'Access-Control-Allow-Origin' issue when API call made from React (Isomorphic app)

Create-React-App has a simple way to deal with this problem: add a proxy field to the package.json file as shown below

"proxy": "http://localhost:8081",

vim line numbers - how to have them on by default?

Terminal > su > password > vim /etc/vimrc

Click here and edit as in line number (13):

set nu

click here and Edit as "Line number (13)"

Use querystring variables in MVC controller

Davids, I had the exact same problem as you. MVC is not intuitive and it seems when they designed it the kiddos didn't understand the purpose or importance of an intuitive querystring system for MVC.

Querystrings are not set in the routes at all (RouteConfig). They are add-on "extra" parameters to Actions in the Controller. This is very confusing as the Action parameters are designed to process BOTH paths AND Querystrings. If you added parameters and they did not work, add a second one for the querystring as so:

This would be your action in your Controller class that catches the ID (which is actually just a path set in your RouteConfig file as a typical default path in MVC):

public ActionResult Hello(int id)

But to catch querystrings an additional parameter in your Controller needs to be the added (which is NOT set in your RouteConfig file, by the way):

public ActionResult Hello(int id, string start, string end)

This now listens for "/Hello?start=&end=" or "/Hello/?start=&end=" or "/Hello/45?start=&end=" assuming the "id" is set to optional in the RouteConfig.cs file.

If you wanted to create a "custom route" in the RouteConfig file that has no "id" path, you could leave off the "id" or other parameter after the action in that file. In that case your parameters in your Action method in the controller would process just querystrings.

I found this extremely confusing myself so you are not alone! They should have designed a simple way to add querystring routes for both specific named strings, any querystring name, and any number of querystrings in the RouteConfig file configuration design. By not doing that it leaves the whole use of querystrings in MVC web applications as questionable, which is pretty bizarre since querystrings have been a stable part of the World Wide Web since the mid-1990's. :(

Generate your own Error code in swift 3

You can create enums to deal with errors :)

enum RikhError: Error {
    case unknownError
    case connectionError
    case invalidCredentials
    case invalidRequest
    case notFound
    case invalidResponse
    case serverError
    case serverUnavailable
    case timeOut
    case unsuppotedURL
 }

and then create a method inside enum to receive the http response code and return the corresponding error in return :)

static func checkErrorCode(_ errorCode: Int) -> RikhError {
        switch errorCode {
        case 400:
            return .invalidRequest
        case 401:
            return .invalidCredentials
        case 404:
            return .notFound
        //bla bla bla
        default:
            return .unknownError
        }
    }

Finally update your failure block to accept single parameter of type RikhError :)

I have a detailed tutorial on how to restructure traditional Objective - C based Object Oriented network model to modern Protocol Oriented model using Swift3 here https://learnwithmehere.blogspot.in Have a look :)

Hope it helps :)

How do I get the "id" after INSERT into MySQL database with Python?

Python DBAPI spec also define 'lastrowid' attribute for cursor object, so...

id = cursor.lastrowid

...should work too, and it's per-connection based obviously.

First Or Create

Previous answer is obsolete. It's possible to achieve in one step since Laravel 5.3, firstOrCreate now has second parameter values, which is being used for new record, but not for search

$user = User::firstOrCreate([
    'email' => '[email protected]'
], [
    'firstName' => 'Taylor',
    'lastName' => 'Otwell'
]);

Convert DataSet to List

var myData = ds.Tables[0].AsEnumerable().Select(r => new Employee {
    Name = r.Field<string>("Name"),
    Age = r.Field<int>("Age")
});
var list = myData.ToList(); // For if you really need a List and not IEnumerable

REST API Best practices: Where to put parameters?

It depends on a design. There are no rules for URIs at REST over HTTP (main thing is that they are unique). Often it comes to the matter of taste and intuition...

I take following approach:

  • url path-element: The resource and its path-element forms a directory traversal and a subresource (e.g. /items/{id} , /users/items). When unsure ask your colleagues, if they think that traversal and they think in "another directory" most likely path-element is the right choice
  • url parameter: when there is no traversal really (search resources with multiple query parameters are a very nice example for that)

How do I get the name of the active user via the command line in OS X?

whoami

EDIT

The whoami utility has been obsoleted by the id(1) utility, and is equivalent to id -un. The command id -p is suggested for normal interactive use.

Java java.sql.SQLException: Invalid column index on preparing statement

Everywhere inside the query string, the wildcard should be ? instead of '?'. That should solve the problem.

EDIT :

To add to that, you need to change date '?' to to_date(?, 'yyyy-mm-dd'). Please try that and let me know.

Why does my JavaScript code receive a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error, while Postman does not?

Only for .NET Core Web API project, add following changes:

  1. Add the following code after the services.AddMvc() line in the ConfigureServices() method of the Startup.cs file:
services.AddCors(allowsites=>{allowsites.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin());
            });
  1. Add the following code after app.UseMvc() line in the Configure() method of the Startup.cs file:
app.UseCors(options => options.AllowAnyOrigin());
  1. Open the controller which you want to access outside the domain and add this following attribute at the controller level:
[EnableCors("AllowOrigin")]

javascript create empty array of a given size

Try using while loop, Array.prototype.push()

var myArray = [], X = 3;
while (myArray.length < X) {
  myArray.push("")
}

Alternatively, using Array.prototype.fill()

var myArray = Array(3).fill("");

Difference between View and Request scope in managed beans

A @ViewScoped bean lives exactly as long as a JSF view. It usually starts with a fresh new GET request, or with a navigation action, and will then live as long as the enduser submits any POST form in the view to an action method which returns null or void (and thus navigates back to the same view). Once you refresh the page, or return a non-null string (even an empty string!) navigation outcome, then the view scope will end.

A @RequestScoped bean lives exactly as long a HTTP request. It will thus be garbaged by end of every request and recreated on every new request, hereby losing all changed properties.

A @ViewScoped bean is thus particularly more useful in rich Ajax-enabled views which needs to remember the (changed) view state across Ajax requests. A @RequestScoped one would be recreated on every Ajax request and thus fail to remember all changed view state. Note that a @ViewScoped bean does not share any data among different browser tabs/windows in the same session like as a @SessionScoped bean. Every view has its own unique @ViewScoped bean.

See also:

CodeIgniter - How to return Json response from controller

For CodeIgniter 4, you can use the built-in API Response Trait

Here's sample code for reference:

<?php namespace App\Controllers;

use CodeIgniter\API\ResponseTrait;

class Home extends BaseController
{
    use ResponseTrait;

    public function index()
    {
        $data = [
            'data' => 'value1',
            'data2' => 'value2',
        ];

        return $this->respond($data);
    }
}

Octave/Matlab: Adding new elements to a vector

Just to add to @ThijsW's answer, there is a significant speed advantage to the first method over the concatenation method:

big = 1e5;
tic;
x = rand(big,1);
toc

x = zeros(big,1);
tic;
for ii = 1:big
    x(ii) = rand;
end
toc

x = []; 
tic; 
for ii = 1:big
    x(end+1) = rand; 
end; 
toc 

x = []; 
tic; 
for ii = 1:big
    x = [x rand]; 
end; 
toc

   Elapsed time is 0.004611 seconds.
   Elapsed time is 0.016448 seconds.
   Elapsed time is 0.034107 seconds.
   Elapsed time is 12.341434 seconds.

I got these times running in 2012b however when I ran the same code on the same computer in matlab 2010a I get

Elapsed time is 0.003044 seconds.
Elapsed time is 0.009947 seconds.
Elapsed time is 12.013875 seconds.
Elapsed time is 12.165593 seconds.

So I guess the speed advantage only applies to more recent versions of Matlab

How do I create a MessageBox in C#?

MessageBox.Show also returns a DialogResult, which if you put some buttons on there, means you can have it returned what the user clicked. Most of the time I write something like

if (MessageBox.Show("Do you want to continue?", "Question", MessageBoxButtons.YesNo) == MessageBoxResult.Yes) {
     //some interesting behaviour here
}

which I guess is a bit unwieldy but it gets the job done.

See https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.dialogresult for additional enum options you can use here.

Detect when an HTML5 video finishes

Here is a simple approach which triggers when the video ends.

<html>
<body>

    <video id="myVideo" controls="controls">
        <source src="video.mp4" type="video/mp4">
        etc ...
    </video>

</body>
<script type='text/javascript'>

    document.getElementById('myVideo').addEventListener('ended', function(e) {

        alert('The End');

    })

</script>
</html> 

In the 'EventListener' line substitute the word 'ended' with 'pause' or 'play' to capture those events as well.

Extract time from date String

The other answers were good answers when the question was asked. Time moves on, Date and SimpleDateFormat get replaced by newer and better classes and go out of use. In 2017, use the classes in the java.time package:

    String timeString = LocalDateTime.parse(dateString, DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss"))
            .format(DateTimeFormatter.ofPattern("H:mm"));

The result is the desired, 9:00.

When should an IllegalArgumentException be thrown?

Throwing runtime exceptions "sparingly" isn't really a good policy -- Effective Java recommends that you use checked exceptions when the caller can reasonably be expected to recover. (Programmer error is a specific example: if a particular case indicates programmer error, then you should throw an unchecked exception; you want the programmer to have a stack trace of where the logic problem occurred, not to try to handle it yourself.)

If there's no hope of recovery, then feel free to use unchecked exceptions; there's no point in catching them, so that's perfectly fine.

It's not 100% clear from your example which case this example is in your code, though.

Flask at first run: Do not use the development server in a production environment

When running the python file, you would normally do this

python app.py
This will display these messages.

To avoid these messsages. Inside the CLI (Command Line Interface), run these commands.

export FLASK_APP=app.py
export FLASK_RUN_HOST=127.0.0.1
export FLASK_ENV=development
export FLASK_DEBUG=0
flask run

This should work perfectlly. :) :)

How do I get an empty array of any size in python?

You can use numpy:

import numpy as np

Example from Empty Array:

np.empty([2, 2])
array([[ -9.74499359e+001,   6.69583040e-309],
       [  2.13182611e-314,   3.06959433e-309]])  

How to reset the bootstrap modal when it gets closed and open it fresh again?

Just reset any content manually when modal is hidden:

$(".modal").on("hidden.bs.modal", function(){
    $(".modal-body1").html("");
});

There is more events. More about them here

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $(".modal").on("hidden.bs.modal", function() {_x000D_
    $(".modal-body1").html("Where did he go?!?!?!");_x000D_
  });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" />_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>_x000D_
_x000D_
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">_x000D_
  Launch modal_x000D_
</button>_x000D_
_x000D_
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">_x000D_
  <div class="modal-dialog">_x000D_
    <div class="modal-content">_x000D_
      <div class="modal-header">_x000D_
        <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span>_x000D_
        </button>_x000D_
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>_x000D_
      </div>_x000D_
      <div class="modal-body">_x000D_
        <div class='modal-body1'>_x000D_
          <h3>Close and open, I will be gone!</h3>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="modal-footer">_x000D_
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

What are the proper permissions for an upload folder with PHP/Apache?

Based on the answer from @Ryan Ahearn, following is what I did on Ubuntu 16.04 to create a user front that only has permission for nginx's web dir /var/www/html.

Steps:

* pre-steps:
    * basic prepare of server,
    * create user 'dev'
        which will be the owner of "/var/www/html",
    * 
    * install nginx,
    * 
* 
* create user 'front'
    sudo useradd -d /home/front -s /bin/bash front
    sudo passwd front

    # create home folder, if not exists yet,
    sudo mkdir /home/front
    # set owner of new home folder,
    sudo chown -R front:front /home/front

    # switch to user,
    su - front

    # copy .bashrc, if not exists yet,
    cp /etc/skel/.bashrc ~front/
    cp /etc/skel/.profile ~front/

    # enable color,
    vi ~front/.bashrc
    # uncomment the line start with "force_color_prompt",

    # exit user
    exit
* 
* add to group 'dev',
    sudo usermod -a -G dev front
* change owner of web dir,
    sudo chown -R dev:dev /var/www
* change permission of web dir,
    chmod 775 $(find /var/www/html -type d)
    chmod 664 $(find /var/www/html -type f)
* 
* re-login as 'front'
    to make group take effect,
* 
* test
* 
* ok
* 

Anaconda Installed but Cannot Launch Navigator

I faced the same problem on Windows 10. As soon as I cleared my Path variable from edit environment variables option, the icon started to appear. It was occurring because I had previously installed python 3.6.1 on my computer and added it to my path variable as C:\Python36;C:\Python36\DLL; and so on. There isn't any need to uninstall Anaconda Navigator and start from scratch if you have correctly followed the steps mentioned at the documentation for it.

Pass variables to AngularJS controller, best practice?

I'm not very advanced in AngularJS, but my solution would be to use a simple JS class for you cart (in the sense of coffee script) that extend Array.

The beauty of AngularJS is that you can pass you "model" object with ng-click like shown below.

I don't understand the advantage of using a factory, as I find it less pretty that a CoffeeScript class.

My solution could be transformed in a Service, for reusable purpose. But otherwise I don't see any advantage of using tools like factory or service.

class Basket extends Array
  constructor: ->

  add: (item) ->
    @push(item)

  remove: (item) ->
    index = @indexOf(item)
    @.splice(index, 1)

  contains: (item) ->
    @indexOf(item) isnt -1

  indexOf: (item) ->
    indexOf = -1
    @.forEach (stored_item, index) ->
      if (item.id is stored_item.id)
        indexOf = index
    return indexOf

Then you initialize this in your controller and create a function for that action:

 $scope.basket = new Basket()
 $scope.addItemToBasket = (item) ->
   $scope.basket.add(item)

Finally you set up a ng-click to an anchor, here you pass your object (retreived from the database as JSON object) to the function:

li ng-repeat="item in items"
  a href="#" ng-click="addItemToBasket(item)" 

How do I implement onchange of <input type="text"> with jQuery?

If you want to trigger the event as you type, use the following:

$('input[name=myInput]').on('keyup', function() { ... });

If you want to trigger the event on leaving the input field, use the following:

$('input[name=myInput]').on('change', function() { ... });

Origin <origin> is not allowed by Access-Control-Allow-Origin

You have to enable CORS to solve this

if your app is created with simple node.js

set it in your response headers like

var http = require('http');

http.createServer(function (request, response) {
response.writeHead(200, {
    'Content-Type': 'text/plain',
    'Access-Control-Allow-Origin' : '*',
    'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE'
});
response.end('Hello World\n');
}).listen(3000);

if your app is created with express framework

use a CORS middleware like

var allowCrossDomain = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', "*");
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    next();
}

and apply via

app.configure(function() {
    app.use(allowCrossDomain);
    //some other code
});    

Here are two reference links

  1. how-to-allow-cors-in-express-nodejs
  2. diving-into-node-js-very-first-app #see the Ajax section

How do I do base64 encoding on iOS?

Since this seems to be the number one google hit on base64 encoding and iphone, I felt like sharing my experience with the code snippet above.

It works, but it is extremely slow. A benchmark on a random image (0.4 mb) took 37 seconds on native iphone. The main reason is probably all the OOP magic - single char NSStrings etc, which are only autoreleased after the encoding is done.

Another suggestion posted here (ab)uses the openssl library, which feels like overkill as well.

The code below takes 70 ms - that's a 500 times speedup. This only does base64 encoding (decoding will follow as soon as I encounter it)

+ (NSString *) base64StringFromData: (NSData *)data length: (int)length {
int lentext = [data length]; 
if (lentext < 1) return @"";

char *outbuf = malloc(lentext*4/3+4); // add 4 to be sure

if ( !outbuf ) return nil;

const unsigned char *raw = [data bytes];

int inp = 0;
int outp = 0;
int do_now = lentext - (lentext%3);

for ( outp = 0, inp = 0; inp < do_now; inp += 3 )
{
    outbuf[outp++] = base64EncodingTable[(raw[inp] & 0xFC) >> 2];
    outbuf[outp++] = base64EncodingTable[((raw[inp] & 0x03) << 4) | ((raw[inp+1] & 0xF0) >> 4)];
    outbuf[outp++] = base64EncodingTable[((raw[inp+1] & 0x0F) << 2) | ((raw[inp+2] & 0xC0) >> 6)];
    outbuf[outp++] = base64EncodingTable[raw[inp+2] & 0x3F];
}

if ( do_now < lentext )
{
    char tmpbuf[2] = {0,0};
    int left = lentext%3;
    for ( int i=0; i < left; i++ )
    {
        tmpbuf[i] = raw[do_now+i];
    }
    raw = tmpbuf;
    outbuf[outp++] = base64EncodingTable[(raw[inp] & 0xFC) >> 2];
    outbuf[outp++] = base64EncodingTable[((raw[inp] & 0x03) << 4) | ((raw[inp+1] & 0xF0) >> 4)];
    if ( left == 2 ) outbuf[outp++] = base64EncodingTable[((raw[inp+1] & 0x0F) << 2) | ((raw[inp+2] & 0xC0) >> 6)];
}

NSString *ret = [[[NSString alloc] initWithBytes:outbuf length:outp encoding:NSASCIIStringEncoding] autorelease];
free(outbuf);

return ret;
}

I left out the line-cutting since I didn't need it, but it's trivial to add.

For those who are interested in optimizing: the goal is to minimize what happens in the main loop. Therefore all logic to deal with the last 3 bytes is treated outside the loop.

Also, try to work on data in-place, without additional copying to/from buffers. And reduce any arithmetic to the bare minimum.

Observe that the bits that are put together to look up an entry in the table, would not overlap when they were to be orred together without shifting. A major improvement could therefore be to use 4 separate 256 byte lookup tables and eliminate the shifts, like this:

outbuf[outp++] = base64EncodingTable1[(raw[inp] & 0xFC)];
outbuf[outp++] = base64EncodingTable2[(raw[inp] & 0x03) | (raw[inp+1] & 0xF0)];
outbuf[outp++] = base64EncodingTable3[(raw[inp+1] & 0x0F) | (raw[inp+2] & 0xC0)];
outbuf[outp++] = base64EncodingTable4[raw[inp+2] & 0x3F];

Of course you could take it a whole lot further, but that's beyond the scope here.

Serializing enums with Jackson

@JsonFormat(shape= JsonFormat.Shape.OBJECT)
public enum SomeEnum

available since https://github.com/FasterXML/jackson-databind/issues/24

just tested it works with version 2.1.2

answer to TheZuck:

I tried your example, got Json:

{"events":[{"type":"ADMIN"}]}

My code:

@RequestMapping(value = "/getEvent") @ResponseBody
  public EventContainer getEvent() {
    EventContainer cont = new EventContainer();
    cont.setEvents(Event.values());
    return cont;
 }

class EventContainer implements Serializable {

  private Event[] events;

  public Event[] getEvents() {
    return events;
 }

 public void setEvents(Event[] events) {
   this.events = events;
 }
}

and dependencies are:

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-annotations</artifactId>
  <version>${jackson.version}</version>
</dependency>

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-core</artifactId>
  <version>${jackson.version}</version>
</dependency>

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>${jackson.version}</version>
  <exclusions>
    <exclusion>
      <artifactId>jackson-annotations</artifactId>
      <groupId>com.fasterxml.jackson.core</groupId>
    </exclusion>
    <exclusion>
      <artifactId>jackson-core</artifactId>
      <groupId>com.fasterxml.jackson.core</groupId>
    </exclusion>
  </exclusions>
</dependency>

<jackson.version>2.1.2</jackson.version>

How To Make Circle Custom Progress Bar in Android

Circle Android Custom Progress Bar

for more information on How to create Circle Android Custom Progress Bar view this link

Step 01 You should create an xml file on drawable file for configure the appearance of progress bar . So Im creating my xml file as circular_progress_bar.xml.

<?xml version="1.0" encoding="UTF-8"?>

<layer-list xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="120"
android:pivotX="50%"
android:pivotY="50%"
android:toDegrees="140">
<item android:id="@android:id/background">
<shape
    android:innerRadiusRatio="3"
    android:shape="ring"
    android:useLevel="false"
     android:angle="0"
     android:type="sweep"
    android:thicknessRatio="50.0">
    <solid android:color="#000000"/>
</shape>

 </item>
 <item android:id="@android:id/progress">
   <rotate
    android:fromDegrees="120"
    android:toDegrees="120">
<shape
    android:innerRadiusRatio="3"
    android:shape="ring"
     android:angle="0"
     android:type="sweep"
    android:thicknessRatio="50.0">
    <solid android:color="#ffffff"/>
</shape>
</rotate>
</item>
</layer-list>

Step 02 Then create progress bar on your xml file Then give the name of xml file on your drawable folder as the parth of android:progressDrawable

 <ProgressBar
            android:id="@+id/progressBar"
            style="?android:attr/progressBarStyleHorizontal"
            android:layout_width="150dp"
            android:layout_height="150dp"
            android:layout_marginLeft="0dp"
            android:layout_centerHorizontal="true"
            android:indeterminate="false"
            android:max="100"
            android:progressDrawable="@drawable/circular_progress_bar" />

Step 03 Visual the progress bar using thread

package com.example.progress;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.view.Menu;
import android.view.animation.Animation;
 import android.view.animation.TranslateAnimation;
 import android.widget.ProgressBar;
 import android.widget.TextView;

 public class MainActivity extends Activity {

  private ProgressBar progBar;
  private TextView text;
     private Handler mHandler = new Handler();
     private int mProgressStatus=0;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    progBar= (ProgressBar)findViewById(R.id.progressBar);
    text = (TextView)findViewById(R.id.textView1);

    dosomething();
}



  public void dosomething() {

  new Thread(new Runnable() {
        public void run() {
        final int presentage=0;
            while (mProgressStatus < 63) {
                mProgressStatus += 1;
                // Update the progress bar
                mHandler.post(new Runnable() {
                    public void run() {
                        progBar.setProgress(mProgressStatus);
                        text.setText(""+mProgressStatus+"%");

                    }
                });
                try {



                    Thread.sleep(50);

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }).start();
  }


 }

How to send authorization header with axios

res.setHeader('Access-Control-Allow-Headers',
            'Access-Control-Allow-Headers, Origin,OPTIONS,Accept,Authorization, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers');

Blockquote : you have to add OPTIONS & Authorization to the setHeader()

this change has fixed my problem, just give a try!

How do I reformat HTML code using Sublime Text 2?

For me, the HTML Prettify solution was extremely simple. I went to the HTML Prettify page.

  1. Needed the Sublime Package Manager
  2. Followed the Instructions for installing the package manager here
  3. typed cmd + shift + p to bring up the menu
  4. Typed prettify
  5. Chose the HTML prettify selection in the menu

Boom. Done. Looks great

Web.Config Debug/Release

To make the transform work in development (using F5 or CTRL + F5) I drop ctt.exe (https://ctt.codeplex.com/) in the packages folder (packages\ConfigTransform\ctt.exe).

Then I register a pre- or post-build event in Visual Studio...

$(SolutionDir)packages\ConfigTransform\ctt.exe source:"$(ProjectDir)connectionStrings.config" transform:"$(ProjectDir)connectionStrings.$(ConfigurationName).config" destination:"$(ProjectDir)connectionStrings.config"
$(SolutionDir)packages\ConfigTransform\ctt.exe source:"$(ProjectDir)web.config" transform:"$(ProjectDir)web.$(ConfigurationName).config" destination:"$(ProjectDir)web.config"

For the transforms I use SlowCheeta VS extension (https://visualstudiogallery.msdn.microsoft.com/69023d00-a4f9-4a34-a6cd-7e854ba318b5).

How to identify object types in java

You forgot the .class:

if (value.getClass() == Integer.class) {
    System.out.println("This is an Integer");
} 
else if (value.getClass() == String.class) {
    System.out.println("This is a String");
}
else if (value.getClass() == Float.class) {
    System.out.println("This is a Float");
}

Note that this kind of code is usually the sign of a poor OO design.

Also note that comparing the class of an object with a class and using instanceof is not the same thing. For example:

"foo".getClass() == Object.class

is false, whereas

"foo" instanceof Object

is true.

Whether one or the other must be used depends on your requirements.

Add line break to 'git commit -m' from the command line

Adding line breaks to your Git commit

Try the following to create a multi-line commit message:

git commit -m "Demonstrate multi-line commit message in Powershell" -m "Add a title to your commit after -m enclosed in quotes,
then add the body of your comment after a second -m.
Press ENTER before closing the quotes to add a line break.
Repeat as needed.
Then close the quotes and hit ENTER twice to apply the commit."

Then verify what you've done:

git log -1

You should end up with something like this:

Multi-line Git commit message in PowerShell

The screenshot is from an example I set up using PowerShell with Poshgit.

I want to exception handle 'list index out of range.'

You have two options; either handle the exception or test the length:

if len(dlist) > 1:
    newlist.append(dlist[1])
    continue

or

try:
    newlist.append(dlist[1])
except IndexError:
    pass
continue

Use the first if there often is no second item, the second if there sometimes is no second item.

how to change default python version?

Navigate to:

My Computer -> Properties -> Advanced -> Environment Variables -> System Variables

Suppose you had already having python 2.7 added in path variable and you want to change default path to python 3.x

then add path of python3.5.x folder before python2.7 path.

open cmd: type "python --version"

python version will be changed to python 3.5.x

How to use pip with python 3.4 on windows?

I had the same problem when I install python3.5.3. And finally I find the pip.exe in this folder: ~/python/scripts/pip.exe. Hope that help.

Call php function from JavaScript

I recently published a jQuery plugin which allows you to make PHP function calls in various ways: https://github.com/Xaxis/jquery.php

Simple example usage:

// Both .end() and .data() return data to variables
var strLenA = P.strlen('some string').end();
var strLenB = P.strlen('another string').end();
var totalStrLen = strLenA + strLenB;
console.log( totalStrLen ); // 25

// .data Returns data in an array
var data1 = P.crypt("Some Crypt String").data();
console.log( data1 ); // ["$1$Tk1b01rk$shTKSqDslatUSRV3WdlnI/"]

How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure?

The linked list holds operations on the shared data structure.

For example, if I have a stack, it will be manipulated with pushes and pops. The linked list would be a set of pushes and pops on the pseudo-shared stack. Each thread sharing that stack will actually have a local copy, and to get to the current shared state, it'll walk the linked list of operations, and apply each operation in order to its local copy of the stack. When it reaches the end of the linked list, its local copy holds the current state (though, of course, it's subject to becoming stale at any time).

In the traditional model, you'd have some sort of locks around each push and pop. Each thread would wait to obtain a lock, then do a push or pop, then release the lock.

In this model, each thread has a local snapshot of the stack, which it keeps synchronized with other threads' view of the stack by applying the operations in the linked list. When it wants to manipulate the stack, it doesn't try to manipulate it directly at all. Instead, it simply adds its push or pop operation to the linked list, so all the other threads can/will see that operation and they can all stay in sync. Then, of course, it applies the operations in the linked list, and when (for example) there's a pop it checks which thread asked for the pop. It uses the popped item if and only if it's the thread that requested this particular pop.

Remove Backslashes from Json Data in JavaScript

You need to deserialize the JSON once before returning it as response. Please refer below code. This works for me:

JavaScriptSerializer jss = new JavaScriptSerializer();
Object finalData = jss.DeserializeObject(str);

Java: Convert String to TimeStamp

This is what I did:

Timestamp timestamp = Timestamp.valueOf(stringValue);

where stringValue can be any format of Date/Time.

What is the first character in the sort order used by Windows Explorer?

If you google for sort order windows explorer you will find out that Windows Explorer (since Windows XP) obviously uses the function StrCmpLogicalW in the sort order "by name". I did not find information about the treatment of the underscore character. I was amused by the following note in the documentation:

Behavior of this function, and therefore the results it returns, can change from release to release. ...

Get Date Object In UTC format in Java

You can subtract the time zone difference from now.

final Calendar calendar  = Calendar.getInstance();
final int      utcOffset = calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET);
final long     tempDate  = new Date().getTime();

return new Date(tempDate - utcOffset);

Is there a way in Pandas to use previous row value in dataframe.apply when previous value is also calculated in the apply?

Applying the recursive function on numpy arrays will be faster than the current answer.

df = pd.DataFrame(np.repeat(np.arange(2, 6),3).reshape(4,3), columns=['A', 'B', 'D'])
new = [df.D.values[0]]
for i in range(1, len(df.index)):
    new.append(new[i-1]*df.A.values[i]+df.B.values[i])
df['C'] = new

Output

      A  B  D    C
   0  1  1  1    1
   1  2  2  2    4
   2  3  3  3   15
   3  4  4  4   64
   4  5  5  5  325

how to properly display an iFrame in mobile safari

Yeah, you can't constrain the iframe itself with height and width. You should put a div around it. If you control the content in the iframe, you can put some JS within the iframe content that will tell the parent to scroll the div when the touch event is received.

like this:

The JS:

setTimeout(function () {
var startY = 0;
var startX = 0;
var b = document.body;
b.addEventListener('touchstart', function (event) {
    parent.window.scrollTo(0, 1);
    startY = event.targetTouches[0].pageY;
    startX = event.targetTouches[0].pageX;
});
b.addEventListener('touchmove', function (event) {
    event.preventDefault();
    var posy = event.targetTouches[0].pageY;
    var h = parent.document.getElementById("scroller");
    var sty = h.scrollTop;

    var posx = event.targetTouches[0].pageX;
    var stx = h.scrollLeft;
    h.scrollTop = sty - (posy - startY);
    h.scrollLeft = stx - (posx - startX);
    startY = posy;
    startX = posx;
});
}, 1000);

The HTML:

<div id="scroller" style="height: 400px; width: 100%; overflow: auto;">
<iframe height="100%" id="iframe" scrolling="no" width="100%" id="iframe" src="url" />
</div>

If you don't control the iframe content, you can use an overlay over the iframe in a similar manner, but then you can't interact with the iframe contents other than to scroll it - so you can't, for example, click links in the iframe.

It used to be that you could use two fingers to scroll within an iframe, but that doesn't work anymore.

Update: iOS 6 broke this solution for us. I've been attempting to get a new fix for it, but nothing has worked yet. In addition, it is no longer possible to debug javascript on the device since they introduced Remote Web Inspector, which requires a Mac to use.

Rails - passing parameters in link_to

Try this

link_to "+ Service", my_services_new_path(:account_id => acct.id)

it will pass the account_id as you want.

For more details on link_to use this http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to

how to call scalar function in sql server 2008

You have a scalar valued function as opposed to a table valued function. The from clause is used for tables. Just query the value directly in the column list.

select dbo.fun_functional_score('01091400003')

Displaying files (e.g. images) stored in Google Drive on a website

Function title: goobox

tags: image hosting, regex, URL, google drive, dropbox, advanced

  • return: string, Returns a string URL that can be used directly as the source of an image.
  • when you host an image on google drive or dropbox you can't use the direct URL of your file to be an image source.
  • you need to make changes to this URL to use it directly as an image source.
  • goobox() will take the URL of your image file, and change it to be used directly as an image source.
  • Important: you need to check your files' permissions first, and whether it's public.
  • live example: https://ybmex.csb.app/
cconst goobox = (url)=>{

    let dropbox_regex = /(http(s)*:\/\/)*(www\.)*(dropbox.com)/;
    let drive_regex =/(http(s)*:\/\/)*(www\.)*(drive.google.com\/file\/d\/)/;

    if(url.match(dropbox_regex)){
       return url.replace(/(http(s)*:\/\/)*(www\.)*/, "https://dl.");
    }
    if(url.match(drive_regex)){
        return `https://drive.google.com/uc?id=${url.replace(drive_regex, "").match(/[\w]*\//)[0].replace(/\//,"")}`;
    }
    return console.error('Wrong URL, not a vlid drobox or google drive url');
}
let url = 'https://drive.google.com/file/d/1PiCWHIwyQWrn4YxatPZDkB8EfegRIkIV/view' 

goobox(URL); //  https://drive.google.com/uc?id=1PiCWHIwyQWrn4YxatPZDkB8EfegRIkIV 

What is Ad Hoc Query?

Ad hoc is latin for "for this purpose". You might call it an "on the fly" query, or a "just so" query. It's the kind of SQL query you just loosely type out where you need it

var newSqlQuery = "SELECT * FROM table WHERE id = " + myId;

...which is an entirely different query each time that line of code is executed, depending on the value of myId. The opposite of an ad hoc query is a predefined query such as a Stored Procedure, where you have created a single query for the entire generalized purpose of selecting from that table (say), and pass the ID as a variable.

How to retrieve absolute path given relative

echo "mydir/doc/ mydir/usoe ./mydir/usm" |  awk '{ split($0,array," "); for(i in array){ system("cd "array[i]" && echo $PWD") } }'

How to add 20 minutes to a current date?

var d = new Date();
var v = new Date();
v.setMinutes(d.getMinutes()+20);

What does "#pragma comment" mean?

#pragma comment is a compiler directive which indicates Visual C++ to leave a comment in the generated object file. The comment can then be read by the linker when it processes object files.

#pragma comment(lib, libname) tells the linker to add the 'libname' library to the list of library dependencies, as if you had added it in the project properties at Linker->Input->Additional dependencies

See #pragma comment on MSDN

Lodash - difference between .extend() / .assign() and .merge()

If you want a deep copy without override while retaining the same obj reference

obj = _.assign(obj, _.merge(obj, [source]))

how to transfer a file through SFTP in java?

Try this code.

public void send (String fileName) {
    String SFTPHOST = "host:IP";
    int SFTPPORT = 22;
    String SFTPUSER = "username";
    String SFTPPASS = "password";
    String SFTPWORKINGDIR = "file/to/transfer";

    Session session = null;
    Channel channel = null;
    ChannelSftp channelSftp = null;
    System.out.println("preparing the host information for sftp.");

    try {
        JSch jsch = new JSch();
        session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
        session.setPassword(SFTPPASS);
        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.connect();
        System.out.println("Host connected.");
        channel = session.openChannel("sftp");
        channel.connect();
        System.out.println("sftp channel opened and connected.");
        channelSftp = (ChannelSftp) channel;
        channelSftp.cd(SFTPWORKINGDIR);
        File f = new File(fileName);
        channelSftp.put(new FileInputStream(f), f.getName());
        log.info("File transfered successfully to host.");
    } catch (Exception ex) {
        System.out.println("Exception found while tranfer the response.");
    } finally {
        channelSftp.exit();
        System.out.println("sftp Channel exited.");
        channel.disconnect();
        System.out.println("Channel disconnected.");
        session.disconnect();
        System.out.println("Host Session disconnected.");
    }
}   

It says that TypeError: document.getElementById(...) is null

Found similar problem within student's work, script element was put after closing body tag, so, obviously, JavaScript could not find any HTML element.

But, there was one more serious error: there was a reference to an external javascript file with some code, which removed all contents of a certain HTML element before inserting new content. After commenting out this reference, everything worked properly.

So, sometimes the error might be that some previously called Javascript changed content or even DOM, so calling for instance getElementById later doesn't make sense, since that element was removed.

Find common substring between two strings

def common_start(sa, sb):
    """ returns the longest common substring from the beginning of sa and sb """
    def _iter():
        for a, b in zip(sa, sb):
            if a == b:
                yield a
            else:
                return

    return ''.join(_iter())
>>> common_start("apple pie available", "apple pies")
'apple pie'

Or a slightly stranger way:

def stop_iter():
    """An easy way to break out of a generator"""
    raise StopIteration

def common_start(sa, sb):
    return ''.join(a if a == b else stop_iter() for a, b in zip(sa, sb))

Which might be more readable as

def terminating(cond):
    """An easy way to break out of a generator"""
    if cond:
        return True
    raise StopIteration

def common_start(sa, sb):
    return ''.join(a for a, b in zip(sa, sb) if terminating(a == b))

How to debug ORA-01775: looping chain of synonyms?

If you are compiling a PROCEDURE, possibly this is referring to a table or view that does not exist as it is created in the same PROCEDURE. In this case the solution is to make the query declared as String eg v_query: = 'insert into table select * from table2 and then execute immediate on v_query;

This is because the compiler does not yet recognize the object and therefore does not find the reference. Greetings.

add Shadow on UIView using swift 3

Swift 5 Just call this function and pass your view

public func setViewSettingWithBgShade(view: UIView)
{
    view.layer.cornerRadius = 8
    view.layer.borderWidth = 1
    view.layer.borderColor = AppTextFieldBorderColor.cgColor

    //MARK:- Shade a view
    view.layer.shadowOpacity = 0.5
    view.layer.shadowOffset = CGSize(width: 1.0, height: 1.0)
    view.layer.shadowRadius = 3.0
    view.layer.shadowColor = UIColor.black.cgColor
    view.layer.masksToBounds = false
}

How to check if input date is equal to today's date?

The Best way and recommended way of comparing date in typescript is:

var today = new Date().getTime();
var reqDateVar = new Date(somedate).getTime();

if(today === reqDateVar){
 // NOW
} else {
 // Some other time
}

How to multiply a BigDecimal by an integer in Java

You have a lot of type-mismatches in your code such as trying to put an int value where BigDecimal is required. The corrected version of your code:

public class Payment
{
    BigDecimal itemCost  = BigDecimal.ZERO;
    BigDecimal totalCost = BigDecimal.ZERO;

    public BigDecimal calculateCost(int itemQuantity, BigDecimal itemPrice)
    {
        itemCost  = itemPrice.multiply(new BigDecimal(itemQuantity));
        totalCost = totalCost.add(itemCost);
        return totalCost;
    }
}

How to change colour of blue highlight on select box dropdown

i just found this site that give a cool themes for the select box http://gregfranko.com/jquery.selectBoxIt.js/

and you can try this themes if your problem with the overall look blue - yellow - grey

The request was aborted: Could not create SSL/TLS secure channel

I had this problem trying to hit https://ct.mob0.com/Styles/Fun.png, which is an image distributed by CloudFlare on its CDN that supports crazy stuff like SPDY and weird redirect SSL certs.

Instead of specifying Ssl3 as in Simons answer I was able to fix it by going down to Tls12 like this:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
new WebClient().DownloadData("https://ct.mob0.com/Styles/Fun.png");

Convert dictionary to bytes and back again python?

This should work:

s=json.dumps(variables)
variables2=json.loads(s)
assert(variables==variables2)

XSD - how to allow elements in any order any number of times?

You should find that the following schema allows the what you have proposed.

  <xs:element name="foo">
    <xs:complexType>
      <xs:sequence minOccurs="0" maxOccurs="unbounded">
        <xs:choice>
          <xs:element maxOccurs="unbounded" name="child1" type="xs:unsignedByte" />
          <xs:element maxOccurs="unbounded" name="child2" type="xs:string" />
        </xs:choice>
      </xs:sequence>
    </xs:complexType>
  </xs:element>

This will allow you to create a file such as:

<?xml version="1.0" encoding="utf-8" ?>
<foo>
  <child1>2</child1>
  <child1>3</child1>
  <child2>test</child2>
  <child2>another-test</child2>
</foo>

Which seems to match your question.

How to override Bootstrap's Panel heading background color?

.panel-default >.panel-heading
{
    background: #ffffff;
}

This is what worked for me to change the color to white.

What is the difference between primary, unique and foreign key constraints, and indexes?

  1. A primary key is a column or a set of columns that uniquely identify a row in a table. A primary key should be short, stable and simple. A foreign key is a column (or set of columns) in a second table whose value is required to match the value of the primary key in the original table. Usually a foreign key is in a table that is different from the table whose primary key is required to match. A table can have multiple foreign keys.
  2. The primary key cannot accept null values. Foreign keys can accept multiple.
  3. We can have only one primary key in a table. We can have more than one foreign key in a table.
  4. By default, Primary key is clustered index and data in the database table is physically organized in the sequence of clustered index. Foreign keys do not automatically create an index, clustered or non-clustered. You can manually create an index on a foreign key.

python - if not in list

How about this?

for item in mylist:
    if item in checklist:
        pass
    else:
       # do something
       print item

Why is document.write considered a "bad practice"?

There's actually nothing wrong with document.write, per se. The problem is that it's really easy to misuse it. Grossly, even.

In terms of vendors supplying analytics code (like Google Analytics) it's actually the easiest way for them to distribute such snippets

  1. It keeps the scripts small
  2. They don't have to worry about overriding already established onload events or including the necessary abstraction to add onload events safely
  3. It's extremely compatible

As long as you don't try to use it after the document has loaded, document.write is not inherently evil, in my humble opinion.

How do I run Selenium in Xvfb?

You can use PyVirtualDisplay (a Python wrapper for Xvfb) to run headless WebDriver tests.

#!/usr/bin/env python

from pyvirtualdisplay import Display
from selenium import webdriver

display = Display(visible=0, size=(800, 600))
display.start()

# now Firefox will run in a virtual display. 
# you will not see the browser.
browser = webdriver.Firefox()
browser.get('http://www.google.com')
print browser.title
browser.quit()

display.stop()

more info


You can also use xvfbwrapper, which is a similar module (but has no external dependencies):

from xvfbwrapper import Xvfb

vdisplay = Xvfb()
vdisplay.start()

# launch stuff inside virtual display here

vdisplay.stop()

or better yet, use it as a context manager:

from xvfbwrapper import Xvfb

with Xvfb() as xvfb:
    # launch stuff inside virtual display here.
    # It starts/stops in this code block.

How to check if string input is a number?

If you wanted to evaluate floats, and you wanted to accept NaNs as input but not other strings like 'abc', you could do the following:

def isnumber(x):
    import numpy
    try:
        return type(numpy.float(x)) == float
    except ValueError:
        return False

How do I get video durations with YouTube API version 3?

You can get the duration from the 'contentDetails' field in the json response.

enter image description here

How to write DataFrame to postgres table?

Pandas 0.24.0+ solution

In Pandas 0.24.0 a new feature was introduced specifically designed for fast writes to Postgres. You can learn more about it here: https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#io-sql-method

import csv
from io import StringIO

from sqlalchemy import create_engine

def psql_insert_copy(table, conn, keys, data_iter):
    # gets a DBAPI connection that can provide a cursor
    dbapi_conn = conn.connection
    with dbapi_conn.cursor() as cur:
        s_buf = StringIO()
        writer = csv.writer(s_buf)
        writer.writerows(data_iter)
        s_buf.seek(0)

        columns = ', '.join('"{}"'.format(k) for k in keys)
        if table.schema:
            table_name = '{}.{}'.format(table.schema, table.name)
        else:
            table_name = table.name

        sql = 'COPY {} ({}) FROM STDIN WITH CSV'.format(
            table_name, columns)
        cur.copy_expert(sql=sql, file=s_buf)

engine = create_engine('postgresql://myusername:mypassword@myhost:5432/mydatabase')
df.to_sql('table_name', engine, method=psql_insert_copy)

Getting unique values in Excel by using formulas only

Solution

I created a function in VBA for you, so you can do this now in an easy way.
Create a VBA code module (macro) as you can see in this tutorial.

  1. Press Alt+F11
  2. Click to Module in Insert.
  3. Paste code.
  4. If Excel says that your file format is not macro friendly than save it as Excel Macro-Enabled in Save As.

Source code

Function listUnique(rng As Range) As Variant
    Dim row As Range
    Dim elements() As String
    Dim elementSize As Integer
    Dim newElement As Boolean
    Dim i As Integer
    Dim distance As Integer
    Dim result As String

    elementSize = 0
    newElement = True

    For Each row In rng.Rows
        If row.Value <> "" Then
            newElement = True
            For i = 1 To elementSize Step 1
                If elements(i - 1) = row.Value Then
                    newElement = False
                End If
            Next i
            If newElement Then
                elementSize = elementSize + 1
                ReDim Preserve elements(elementSize - 1)
                elements(elementSize - 1) = row.Value
            End If
        End If
    Next

    distance = Range(Application.Caller.Address).row - rng.row

    If distance < elementSize Then
        result = elements(distance)
        listUnique = result
    Else
        listUnique = ""
    End If
End Function

Usage

Just enter =listUnique(range) to a cell. The only parameter is range that is an ordinary Excel range. For example: A$1:A$28 or H$8:H$30.

Conditions

  • The range must be a column.
  • The first cell where you call the function must be in the same row where the range starts.

Example

Regular case

  1. Enter data and call function.
    Enter data and call function
  2. Grow it.
    Grow it
  3. Voilà.
    Voilà

Empty cell case

It works in columns that have empty cells in them. Also the function outputs nothing (not errors) if you overwind the cells (calling the function) into places where should be no output, as I did it in the previous example's "2. Grow it" part.

Empty cell case

DateTime fields from SQL Server display incorrectly in Excel

Try the following: Paste "2004-06-01 00:00:00.000" into Excel.

Now try paste "2004-06-01 00:00:00" into Excel.

Excel doesn't seem to be able to handle milliseconds when pasting...

How to call a method in MainActivity from another class?

MainActivity.java

public class MainActivity extends AppCompatActivity {

    private static MainActivity instance;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        instance = this;
    }

    public static MainActivity getInstance() {
        return instance;
    }

    public void myMethod() {
       // do something...
    }
)

AnotherClass.java

public Class AnotherClass() {
     // call this method
     MainActivity.getInstance().myMethod();
}

How to delete object?

You can proxyfy references to your object with, for example, dictionary singleton. You may store not object, but its ID or hash and access it trought the dictionary. Then when you need to remove the object you set value for its key to null.

How to crop(cut) text files based on starting and ending line-numbers in cygwin?

This is an old thread but I was surprised nobody mentioned grep. The -A option allows specifying a number of lines to print after a search match and the -B option includes lines before a match. The following command would output 10 lines before and 10 lines after occurrences of "my search string" in the file "mylogfile.log":

grep -A 10 -B 10 "my search string" mylogfile.log

If there are multiple matches within a large file the output can rapidly get unwieldy. Two helpful options are -n which tells grep to include line numbers and --color which highlights the matched text in the output.

If there is more than file to be searched grep allows multiple files to be listed separated by spaces. Wildcards can also be used. Putting it all together:

grep -A 10 -B 10 -n --color "my search string" *.log someOtherFile.txt

Java error - "invalid method declaration; return type required"

You forgot to declare double as a return type

public double diameter()
{
    double d = radius * 2;
    return d;
}

CSS3 Transparency + Gradient

I just came across this more recent example . To simplify and use the most recent examples, giving the css a selector class of 'grad',(I've included backwards compatibility)

.grad {
    background-color: #F07575; /* fallback color if gradients are not supported */
    background-image: -webkit-linear-gradient(top left, red, rgba(255,0,0,0));/* For Chrome 25 and Safari 6, iOS 6.1, Android 4.3 */
    background-image: -moz-linear-gradient(top left, red, rgba(255,0,0,0));/* For Firefox (3.6 to 15) */
    background-image: -o-linear-gradient(top left, red, rgba(255,0,0,0));/* For old Opera (11.1 to 12.0) */
    background-image: linear-gradient(to bottom right, red, rgba(255,0,0,0)); /* Standard syntax; must be last */
}

from https://developer.mozilla.org/en-US/docs/Web/CSS/linear-gradient

How do I detach objects in Entity Framework Code First?

If you want to detach existing object follow @Slauma's advice. If you want to load objects without tracking changes use:

var data = context.MyEntities.AsNoTracking().Where(...).ToList();

As mentioned in comment this will not completely detach entities. They are still attached and lazy loading works but entities are not tracked. This should be used for example if you want to load entity only to read data and you don't plan to modify them.

.includes() not working in Internet Explorer

It works for me:

function stringIncludes(a, b) {
      return a.indexOf(b) !== -1;
}

Why does PEP-8 specify a maximum line length of 79 characters?

I agree with Justin. To elaborate, overly long lines of code are harder to read by humans and some people might have console widths that only accommodate 80 characters per line.

The style recommendation is there to ensure that the code you write can be read by as many people as possible on as many platforms as possible and as comfortably as possible.

How to count down in for loop?

First I recommand you can try use print and observe the action:

for i in range(0, 5, 1):
    print i

the result:

0
1
2
3
4

You can understand the function principle. In fact, range scan range is from 0 to 5-1. It equals 0 <= i < 5

When you really understand for-loop in python, I think its time we get back to business. Let's focus your problem.

You want to use a DECREMENT for-loop in python. I suggest a for-loop tutorial for example.

for i in range(5, 0, -1):
    print i

the result:

5
4
3
2
1

Thus it can be seen, it equals 5 >= i > 0

You want to implement your java code in python:

for (int index = last-1; index >= posn; index--)

It should code this:

for i in range(last-1, posn-1, -1)

regex to match a single character that is anything but a space

  • \s matches any white-space character
  • \S matches any non-white-space character
  • You can match a space character with just the space character;
  • [^ ] matches anything but a space character.

Pick whichever is most appropriate.

How to make a Bootstrap accordion collapse when clicking the header div?

Here is the working example for Bootstrap 4.3

_x000D_
_x000D_
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>_x000D_
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">_x000D_
_x000D_
_x000D_
<div class="accordion" id="accordionExample">_x000D_
                <div class="card">_x000D_
                    <div class="card-header" id="headingOne" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">_x000D_
                        <h2 class="mb-0">_x000D_
                            <button class="btn btn-link" type="button" >_x000D_
                                Collapsible Group Item #1_x000D_
                            </button>_x000D_
                        </h2>_x000D_
                    </div>_x000D_
_x000D_
                    <div id="collapseOne" class="collapse show" aria-labelledby="headingOne" data-parent="#accordionExample">_x000D_
                        <div class="card-body">_x000D_
                            _x000D_
                        </div>_x000D_
                    </div>_x000D_
                </div>_x000D_
                <div class="card">_x000D_
                    <div class="card-header" id="headingTwo" data-toggle="collapse" data-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">_x000D_
                        <h2 class="mb-0">_x000D_
                            <button class="btn btn-link collapsed" type="button" >_x000D_
                                Collapsible Group Item #2_x000D_
                            </button>_x000D_
                        </h2>_x000D_
                    </div>_x000D_
                    <div id="collapseTwo" class="collapse" aria-labelledby="headingTwo" data-parent="#accordionExample">_x000D_
                        <div class="card-body">_x000D_
                            _x000D_
                        </div>_x000D_
                    </div>_x000D_
                </div>_x000D_
                <div class="card">_x000D_
                    <div class="card-header" id="headingThree" data-toggle="collapse" data-target="#collapseThree" aria-expanded="false" aria-controls="collapseThree">_x000D_
                        <h2 class="mb-0">_x000D_
                            <button class="btn btn-link collapsed" type="button" >_x000D_
                                Collapsible Group Item #3_x000D_
                            </button>_x000D_
                        </h2>_x000D_
                    </div>_x000D_
                    <div id="collapseThree" class="collapse" aria-labelledby="headingThree" data-parent="#accordionExample">_x000D_
                        <div class="card-body">_x000D_
                            _x000D_
                        </div>_x000D_
                    </div>_x000D_
                </div>_x000D_
            </div>
_x000D_
_x000D_
_x000D_

How to check whether a select box is empty using JQuery/Javascript

Another correct way to get selected value would be using this selector:

$("option[value="0"]:selected")

Best for you!

What's the difference between all the Selection Segues?

For those who prefer a bit more practical learning, select the segue in dock, open the attribute inspector and switch between different kinds of segues (dropdown "Kind"). This will reveal options specific for each of them: for example you can see that "present modally" allows you to choose a transition type etc.

What's wrong with nullable columns in composite primary keys?

The answer by Tony Andrews is a decent one. But the real answer is that this has been a convention used by relational database community and is NOT a necessity. Maybe it is a good convention, maybe not.

Comparing anything to NULL results in UNKNOWN (3rd truth value). So as has been suggested with nulls all traditional wisdom concerning equality goes out the window. Well that's how it seems at first glance.

But I don't think this is necessarily so and even SQL databases don't think that NULL destroys all possibility for comparison.

Run in your database the query SELECT * FROM VALUES(NULL) UNION SELECT * FROM VALUES(NULL)

What you see is just one tuple with one attribute that has the value NULL. So the union recognized here the two NULL values as equal.

When comparing a composite key that has 3 components to a tuple with 3 attributes (1, 3, NULL) = (1, 3, NULL) <=> 1 = 1 AND 3 = 3 AND NULL = NULL The result of this is UNKNOWN.

But we could define a new kind of comparison operator eg. ==. X == Y <=> X = Y OR (X IS NULL AND Y IS NULL)

Having this kind of equality operator would make composite keys with null components or non-composite key with null value unproblematic.

Is there a way to view past mysql queries with phpmyadmin?

I am using phpMyAdmin Server version: 5.1.41.

It offers possibility for view sql history through phpmyadmin.pma_history table.

You can search your query in this table.

pma_history table has below structure:

enter image description here

How do I assert equality on two classes without an equals method?

You can use reflection to "automate" the full equality testing. you can implement the equality "tracking" code you wrote for a single field, then use reflection to run that test on all fields in the object.

if, elif, else statement issues in Bash

[ is a command (or a builtin in some shells). It must be separated by whitespace from the preceding statement:

elif [

Convert objective-c typedef to its string equivalent

I combined several approaches here. I like the idea of the preprocessor and the indexed list.

There's no extra dynamic allocation, and because of the inlining the compiler might be able to optimize the lookup.

typedef NS_ENUM(NSUInteger, FormatType) { FormatTypeJSON = 0, FormatTypeXML, FormatTypeAtom, FormatTypeRSS, FormatTypeCount };

NS_INLINE NSString *FormatTypeToString(FormatType t) {
  if (t >= FormatTypeCount)
    return nil;

#define FormatTypeMapping(value) [value] = @#value

  NSString *table[FormatTypeCount] = {FormatTypeMapping(FormatTypeJSON),
                                      FormatTypeMapping(FormatTypeXML),
                                      FormatTypeMapping(FormatTypeAtom),
                                      FormatTypeMapping(FormatTypeRSS)};

#undef FormatTypeMapping

  return table[t];
}

Why am I getting the error "connection refused" in Python? (Sockets)

I was being able to ping my connection but was STILL getting the 'connection refused' error. Turns out I was pinging myself! That's what the problem was.

Excel Define a range based on a cell value

You can also use OFFSET:

OFFSET($A$10,-$B$1+1,0,$B$1)

It moves the range $A$10 up by $B$1-1 (becomes $A$6 ($A$5)) and then resizes the range to $B$1 rows (becomes $A$6:$A$10 ($A$5:$A$10))

Getting the class of the element that fired an event using JQuery

You will get all the class in below array

event.target.classList

How to generate Entity Relationship (ER) Diagram of a database using Microsoft SQL Server Management Studio?

From Object Explorer in SQL Server Management Studio, find your database and expand the node (click on the + sign beside your database). The first item from that expanded tree is Database Diagrams. Right-click on that and you'll see various tasks including creating a new database diagram. If you've never created one before, it'll ask if you want to install the components for creating diagrams. Click yes then proceed.

How to create a library project in Android Studio and an application project that uses the library project

The simplest way for me to create and reuse a library project:

  1. On an opened project file > new > new module (and answer the UI questions)

enter image description here

  1. check/or add if in the file settings.gradle: include ':myLibrary'
  2. check/or add if in the file build.gradle:

    dependencies { ... compile project(':myLibrary') }

  3. To reuse this library module in another project, copy it's folder in the project instead of step 1 and do the steps 2 and 3.

You can also create a new studio application project You can easily change an existing application module to a library module by changing the plugin assignment in the build.gradle file to com.android.library.

apply plugin: 'com.android.application'

android {...}

to

apply plugin: 'com.android.library'

android {...}

more here

JQuery - how to select dropdown item based on value

_x000D_
_x000D_
$('#dropdownid').val('selectedvalue');
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<select id='dropdownid'>_x000D_
    <option value=''>- Please choose -</option>_x000D_
    <option value='1'>1</option>_x000D_
    <option value='2'>2</option>_x000D_
    <option value='selectedvalue'>There we go!</option>_x000D_
    <option value='3'>3</option>_x000D_
    <option value='4'>4</option>_x000D_
    <option value='5'>5</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Merge PDF files with PHP

I've done this before. I had a pdf that I generated with fpdf, and I needed to add on a variable amount of PDFs to it.

So I already had an fpdf object and page set up (http://www.fpdf.org/) And I used fpdi to import the files (http://www.setasign.de/products/pdf-php-solutions/fpdi/) FDPI is added by extending the PDF class:

class PDF extends FPDI
{

} 



    $pdffile = "Filename.pdf";
    $pagecount = $pdf->setSourceFile($pdffile);  
    for($i=0; $i<$pagecount; $i++){
        $pdf->AddPage();  
        $tplidx = $pdf->importPage($i+1, '/MediaBox');
        $pdf->useTemplate($tplidx, 10, 10, 200); 
    }

This basically makes each pdf into an image to put into your other pdf. It worked amazingly well for what I needed it for.

ES6 Map in Typescript

With the lib config option your are able to cherry pick Map into your project. Just add es2015.collection to your lib section. When you have no lib config add one with the defaults and add es2015.collection.

So when you have target: es5, change tsconfig.json to:

"target": "es5",
"lib": [ "dom", "es5", "scripthost", "es2015.collection" ],

Regex to remove letters, symbols except numbers

Simple:

var removedText = self.val().replace(/[^0-9]+/, '');

^ - means NOT

How to join two sets in one line without using "|"

If you are fine with modifying the original set (which you may want to do in some cases), you can use set.update():

S.update(T)

The return value is None, but S will be updated to be the union of the original S and T.

Regular expression include and exclude special characters

You haven't actually asked a question, but assuming you have one, this could be your answer...

Assuming all characters, except the "Special Characters" are allowed you can write

String regex = "^[^<>'\"/;`%]*$";

Best way to pass parameters to jQuery's .load()

In the first case, the data are passed to the script via GET, in the second via POST.

http://docs.jquery.com/Ajax/load#urldatacallback

I don't think there are limits to the data size, but the completition of the remote call will of course take longer with great amount of data.

Remove directory from remote repository after adding them to .gitignore

The answer from Blundell should work, but for some bizarre reason it didn't do with me. I had to pipe first the filenames outputted by the first command into a file and then loop through that file and delete that file one by one.

git ls-files -i --exclude-from=.gitignore > to_remove.txt
while read line; do `git rm -r --cached "$line"`; done < to_remove.txt
rm to_remove.txt
git commit -m 'Removed all files that are in the .gitignore' 
git push origin master

MySQL select statement with CASE or IF ELSEIF? Not sure how to get the result

Syntax:

CASE value WHEN [compare_value] THEN result 
[WHEN [compare_value] THEN result ...] 
[ELSE result] 
END

Alternative: CASE WHEN [condition] THEN result [WHEN [condition] THEN result ...]

mysql> SELECT CASE  WHEN 2>3 THEN 'this is true' ELSE 'this is false' END; 
+-------------------------------------------------------------+
| CASE  WHEN 2>3 THEN 'this is true' ELSE 'this is false' END |
+-------------------------------------------------------------+
| this is false                                               | 
+-------------------------------------------------------------+

I am use:

SELECT  act.*,
    CASE 
        WHEN (lises.session_date IS NOT NULL AND ses.session_date IS NULL) THEN lises.location_id
        WHEN (lises.session_date IS NULL AND ses.session_date IS NOT NULL) THEN ses.location_id
        WHEN (lises.session_date IS NOT NULL AND ses.session_date IS NOT NULL AND lises.session_date>ses.session_date) THEN ses.location_id
        WHEN (lises.session_date IS NOT NULL AND ses.session_date IS NOT NULL AND lises.session_date<ses.session_date) THEN lises.location_id
    END AS location_id
FROM activity AS act
LEFT JOIN li_sessions AS lises ON lises.activity_id = act.id AND  lises.session_date >= now()
LEFT JOIN session AS ses ON  ses.activity_id = act.id AND  ses.session_date >= now()
WHERE act.id

What are the true benefits of ExpandoObject?

It's example from great MSDN article about using ExpandoObject for creating dynamic ad-hoc types for incoming structured data (i.e XML, Json).

We can also assign delegate to ExpandoObject's dynamic property:

dynamic person = new ExpandoObject();
person.FirstName = "Dino";
person.LastName = "Esposito";

person.GetFullName = (Func<String>)(() => { 
  return String.Format("{0}, {1}", 
    person.LastName, person.FirstName); 
});

var name = person.GetFullName();
Console.WriteLine(name);

Thus it allows us to inject some logic into dynamic object at runtime. Therefore, together with lambda expressions, closures, dynamic keyword and DynamicObject class, we can introduce some elements of functional programming into our C# code, which we knows from dynamic languages as like JavaScript or PHP.

Hexadecimal string to byte array in C

Here's my version:

/* Convert a hex char digit to its integer value. */
int hexDigitToInt(char digit) {
    digit = tolower(digit);
    if ('0' <= digit && digit <= '9') //if it's decimal
        return (int)(digit - '0');
    else if ('a' <= digit && digit <= 'f') //if it's abcdef
        return (int)(digit - ('a' - 10));
    else
        return -1; //value not in [0-9][a-f] range
}

/* Decode a hex string. */
char *decodeHexString(const char *hexStr) {
    char* decoded = malloc(strlen(hexStr)/2+1);
    char* hexStrPtr = (char *)hexStr;
    char* decodedPtr = decoded;

    while (*hexStrPtr != '\0') { /* Step through hexStr, two chars at a time. */
        *decodedPtr = 16 * hexDigitToInt(*hexStrPtr) + hexDigitToInt(*(hexStrPtr+1));
        hexStrPtr += 2;
        decodedPtr++;
    }

    *decodedPtr = '\0'; /* final null char */
    return decoded;
}

How to get the selected date value while using Bootstrap Datepicker?

I was able to find the moment.js object for the selected date with the following:

$('#datepicker').data('DateTimePicker').date()

More info about moment.js and how to format the date using the moment.js object

Generate random numbers following a normal distribution in C/C++

C++11

C++11 offers std::normal_distribution, which is the way I would go today.

C or older C++

Here are some solutions in order of ascending complexity:

  1. Add 12 uniform random numbers from 0 to 1 and subtract 6. This will match mean and standard deviation of a normal variable. An obvious drawback is that the range is limited to ±6 – unlike a true normal distribution.

  2. The Box-Muller transform. This is listed above, and is relatively simple to implement. If you need very precise samples, however, be aware that the Box-Muller transform combined with some uniform generators suffers from an anomaly called Neave Effect1.

  3. For best precision, I suggest drawing uniforms and applying the inverse cumulative normal distribution to arrive at normally distributed variates. Here is a very good algorithm for inverse cumulative normal distributions.

1. H. R. Neave, “On using the Box-Muller transformation with multiplicative congruential pseudorandom number generators,” Applied Statistics, 22, 92-97, 1973

Map over object preserving keys

A mix fix for the underscore map bug :P

_.mixin({ 
    mapobj : function( obj, iteratee, context ) {
        if (obj == null) return [];
        iteratee = _.iteratee(iteratee, context);
        var keys = obj.length !== +obj.length && _.keys(obj),
            length = (keys || obj).length,
            results = {},
            currentKey;
        for (var index = 0; index < length; index++) {
          currentKey = keys ? keys[index] : index;
          results[currentKey] = iteratee(obj[currentKey], currentKey, obj);
        }
        if ( _.isObject( obj ) ) {
            return _.object( results ) ;
        } 
        return results;
    }
}); 

A simple workaround that keeps the right key and return as object It is still used the same way as i guest you could used this function to override the bugy _.map function

or simply as me used it as a mixin

_.mapobj ( options , function( val, key, list ) 

How to check if the user can go back in browser history or not

Be careful with window.history.length because it includes also entries for window.history.forward()

So you may have maybe window.history.length with more than 1 entries, but no history back entries. This means that nothing happens if you fire window.history.back()

jQuery dialog popup

It's quite simple, first HTML must be added:

<div id="dialog"></div>

Then, it must be initialized:

<script type="text/javascript">
  jQuery( document ).ready( function() {
    jQuery( '#dialog' ).dialog( { 'autoOpen': false } );
  });
</script>

After this you can show it by code:

jQuery( '#dialog' ).dialog( 'open' );

Update cordova plugins in one command

ionic state is deprecated as on [email protected]

If you happen to be using ionic and the ionic cli you can run:

ionic state reset

As long as all your plugin information was saved in your package.json earlier, this will essentially perform an rm/add for all your plugins. Just note that this will also rm/add your platforms as well, but that shouldn't matter.

This is also nice for when you ignore your plugin folders from your repo, and want to setup the project on another machine.

Obviously this doesn't directly answer the question, but many people are currently using both, and will end up here.

How to submit a form when the return key is pressed?

Using the "autofocus" attribute works to give input focus to the button by default. In fact clicking on any control within the form also gives focus to the form, a requirement for the form to react to the RETURN. So, the "autofocus" does that for you in case the user never clicked on any other control within the form.

So, the "autofocus" makes the crucial difference if the user never clicked on any of the form controls before hitting RETURN.

But even then, there are still 2 conditions to be met for this to work without JS:

a) you have to specify a page to go to (if left empty it wont work). In my example it is hello.php

b) the control has to be visible. You could conceivably move it off the page to hide, but you cannot use display:none or visibility:hidden. What I did, was to use inline style to just move it off the page to the left by 200px. I made the height 0px so that it does not take up space. Because otherwise it can still disrupt other controls above and below. Or you could float the element too.

<form action="hello.php" method="get">
  Name: <input type="text" name="name"/><br/>
  Pwd: <input type="password" name="password"/><br/>
  <div class="yourCustomDiv"/>
  <input autofocus type="submit" style="position:relative; left:-200px; height:0px;" />
</form>

Android 5.0 - Add header/footer to a RecyclerView

I know I come late, but only recently I was able to implement such "addHeader" to the Adapter. In my FlexibleAdapter project you can call setHeader on a Sectionable item, then you call showAllHeaders. If you need only 1 header then the first item should have the header. If you delete this item, then the header is automatically linked to the next one.

Unfortunately footers are not covered (yet).

The FlexibleAdapter allows you to do much more than create headers/sections. You really should have a look: https://github.com/davideas/FlexibleAdapter.

How to unmount, unrender or remove a component, from itself in a React/Redux/Typescript notification message

Just like that nice warning you got, you are trying to do something that is an Anti-Pattern in React. This is a no-no. React is intended to have an unmount happen from a parent to child relationship. Now if you want a child to unmount itself, you can simulate this with a state change in the parent that is triggered by the child. let me show you in code.

class Child extends React.Component {
    constructor(){}
    dismiss() {
        this.props.unmountMe();
    } 
    render(){
        // code
    }
}

class Parent ...
    constructor(){
        super(props)
        this.state = {renderChild: true};
        this.handleChildUnmount = this.handleChildUnmount.bind(this);
    }
    handleChildUnmount(){
        this.setState({renderChild: false});
    }
    render(){
        // code
        {this.state.renderChild ? <Child unmountMe={this.handleChildUnmount} /> : null}
    }

}

this is a very simple example. but you can see a rough way to pass through to the parent an action

That being said you should probably be going through the store (dispatch action) to allow your store to contain the correct data when it goes to render

I've done error/status messages for two separate applications, both went through the store. It's the preferred method... If you'd like I can post some code as to how to do that.

EDIT: Here is how I set up a notification system using React/Redux/Typescript

Few things to note first. this is in typescript so you would need to remove the type declarations :)

I am using the npm packages lodash for operations, and classnames (cx alias) for inline classname assignment.

The beauty of this setup is I use a unique identifier for each notification when the action creates it. (e.g. notify_id). This unique ID is a Symbol(). This way if you want to remove any notification at any point in time you can because you know which one to remove. This notification system will let you stack as many as you want and they will go away when the animation is completed. I am hooking into the animation event and when it finishes I trigger some code to remove the notification. I also set up a fallback timeout to remove the notification just in case the animation callback doesn't fire.

notification-actions.ts

import { USER_SYSTEM_NOTIFICATION } from '../constants/action-types';

interface IDispatchType {
    type: string;
    payload?: any;
    remove?: Symbol;
}

export const notifySuccess = (message: any, duration?: number) => {
    return (dispatch: Function) => {
        dispatch({ type: USER_SYSTEM_NOTIFICATION, payload: { isSuccess: true, message, notify_id: Symbol(), duration } } as IDispatchType);
    };
};

export const notifyFailure = (message: any, duration?: number) => {
    return (dispatch: Function) => {
        dispatch({ type: USER_SYSTEM_NOTIFICATION, payload: { isSuccess: false, message, notify_id: Symbol(), duration } } as IDispatchType);
    };
};

export const clearNotification = (notifyId: Symbol) => {
    return (dispatch: Function) => {
        dispatch({ type: USER_SYSTEM_NOTIFICATION, remove: notifyId } as IDispatchType);
    };
};

notification-reducer.ts

const defaultState = {
    userNotifications: []
};

export default (state: ISystemNotificationReducer = defaultState, action: IDispatchType) => {
    switch (action.type) {
        case USER_SYSTEM_NOTIFICATION:
            const list: ISystemNotification[] = _.clone(state.userNotifications) || [];
            if (_.has(action, 'remove')) {
                const key = parseInt(_.findKey(list, (n: ISystemNotification) => n.notify_id === action.remove));
                if (key) {
                    // mutate list and remove the specified item
                    list.splice(key, 1);
                }
            } else {
                list.push(action.payload);
            }
            return _.assign({}, state, { userNotifications: list });
    }
    return state;
};

app.tsx

in the base render for your application you would render the notifications

render() {
    const { systemNotifications } = this.props;
    return (
        <div>
            <AppHeader />
            <div className="user-notify-wrap">
                { _.get(systemNotifications, 'userNotifications') && Boolean(_.get(systemNotifications, 'userNotifications.length'))
                    ? _.reverse(_.map(_.get(systemNotifications, 'userNotifications', []), (n, i) => <UserNotification key={i} data={n} clearNotification={this.props.actions.clearNotification} />))
                    : null
                }
            </div>
            <div className="content">
                {this.props.children}
            </div>
        </div>
    );
}

user-notification.tsx

user notification class

/*
    Simple notification class.

    Usage:
        <SomeComponent notifySuccess={this.props.notifySuccess} notifyFailure={this.props.notifyFailure} />
        these two functions are actions and should be props when the component is connect()ed

    call it with either a string or components. optional param of how long to display it (defaults to 5 seconds)
        this.props.notifySuccess('it Works!!!', 2);
        this.props.notifySuccess(<SomeComponentHere />, 15);
        this.props.notifyFailure(<div>You dun goofed</div>);

*/

interface IUserNotifyProps {
    data: any;
    clearNotification(notifyID: symbol): any;
}

export default class UserNotify extends React.Component<IUserNotifyProps, {}> {
    public notifyRef = null;
    private timeout = null;

    componentDidMount() {
        const duration: number = _.get(this.props, 'data.duration', '');
       
        this.notifyRef.style.animationDuration = duration ? `${duration}s` : '5s';

        
        // fallback incase the animation event doesn't fire
        const timeoutDuration = (duration * 1000) + 500;
        this.timeout = setTimeout(() => {
            this.notifyRef.classList.add('hidden');
            this.props.clearNotification(_.get(this.props, 'data.notify_id') as symbol);
        }, timeoutDuration);

        TransitionEvents.addEndEventListener(
            this.notifyRef,
            this.onAmimationComplete
        );
    }
    componentWillUnmount() {
        clearTimeout(this.timeout);

        TransitionEvents.removeEndEventListener(
            this.notifyRef,
            this.onAmimationComplete
        );
    }
    onAmimationComplete = (e) => {
        if (_.get(e, 'animationName') === 'fadeInAndOut') {
            this.props.clearNotification(_.get(this.props, 'data.notify_id') as symbol);
        }
    }
    handleCloseClick = (e) => {
        e.preventDefault();
        this.props.clearNotification(_.get(this.props, 'data.notify_id') as symbol);
    }
    assignNotifyRef = target => this.notifyRef = target;
    render() {
        const {data, clearNotification} = this.props;
        return (
            <div ref={this.assignNotifyRef} className={cx('user-notification fade-in-out', {success: data.isSuccess, failure: !data.isSuccess})}>
                {!_.isString(data.message) ? data.message : <h3>{data.message}</h3>}
                <div className="close-message" onClick={this.handleCloseClick}>+</div>
            </div>
        );
    }
}

input checkbox true or checked or yes

Only checked and checked="checked" are valid. Your other options depend on error recovery in browsers.

checked="yes" and checked="true" are particularly bad as they imply that checked="no" and checked="false" will set the default state to be unchecked … which they will not.

How to install ADB driver for any android device?

I have found a solution by myself. I use the PDANet tool to find the driver automatically.

http://www.junefabrics.com/android/download.php

Default FirebaseApp is not initialized

If you recently update your Android Studio to 3.3.1 that have a problem with com.google.gms:google-services (Below 4.2.0) dependencies So please update com.google.gms:google-services to 4.2.0.

dependencies {
    classpath 'com.android.tools.build:gradle:3.3.1'
    classpath 'com.google.gms:google-services:4.2.0'
    }

JSON Naming Convention (snake_case, camelCase or PascalCase)

Premise

There is no standard naming of keys in JSON. According to the Objects section of the spec:

The JSON syntax does not impose any restrictions on the strings used as names,...

Which means camelCase or snake_case should work fine.

Driving factors

Imposing a JSON naming convention is very confusing. However, this can easily be figured out if you break it down into components.

  1. Programming language for generating JSON

    • Python - snake_case
    • PHP - snake_case
    • Java - camelCase
    • JavaScript - camelCase
  2. JSON itself has no standard naming of keys

  3. Programming language for parsing JSON

    • Python - snake_case
    • PHP - snake_case
    • Java - camelCase
    • JavaScript - camelCase

Mix-match the components

  1. Python » JSON » Python - snake_case - unanimous
  2. Python » JSON » PHP - snake_case - unanimous
  3. Python » JSON » Java - snake_case - please see the Java problem below
  4. Python » JSON » JavaScript - snake_case will make sense; screw the front-end anyways
  5. Python » JSON » you do not know - snake_case will make sense; screw the parser anyways
  6. PHP » JSON » Python - snake_case - unanimous
  7. PHP » JSON » PHP - snake_case - unanimous
  8. PHP » JSON » Java - snake_case - please see the Java problem below
  9. PHP » JSON » JavaScript - snake_case will make sense; screw the front-end anyways
  10. PHP » JSON » you do not know - snake_case will make sense; screw the parser anyways
  11. Java » JSON » Python - snake_case - please see the Java problem below
  12. Java » JSON » PHP - snake_case - please see the Java problem below
  13. Java » JSON » Java - camelCase - unanimous
  14. Java » JSON » JavaScript - camelCase - unanimous
  15. Java » JSON » you do not know - camelCase will make sense; screw the parser anyways
  16. JavaScript » JSON » Python - snake_case will make sense; screw the front-end anyways
  17. JavaScript » JSON » PHP - snake_case will make sense; screw the front-end anyways
  18. JavaScript » JSON » Java - camelCase - unanimous
  19. JavaScript » JSON » JavaScript - camelCase - Original

Java problem

snake_case will still make sense for those with Java entries because the existing JSON libraries for Java are using only methods to access the keys instead of using the standard dot.syntax. This means that it wouldn't hurt that much for Java to access the snake_cased keys in comparison to the other programming language which can do the dot.syntax.

Example for Java's org.json package

JsonObject.getString("snake_cased_key")

Example for Java's com.google.gson package

JsonElement.getAsString("snake_cased_key")

Some actual implementations

Conclusions

Choosing the right JSON naming convention for your JSON implementation depends on your technology stack. There are cases where one can use snake_case, camelCase, or any other naming convention.

Another thing to consider is the weight to be put on the JSON-generator vs the JSON-parser and/or the front-end JavaScript. In general, more weight should be put on the JSON-generator side rather than the JSON-parser side. This is because business logic usually resides on the JSON-generator side.

Also, if the JSON-parser side is unknown then you can declare what ever can work for you.

How to change column datatype in SQL database without losing data

You can easily do this using the following command. Any value of 0 will be turned into a 0 (BIT = false), anything else will be turned into 1 (BIT = true).

ALTER TABLE dbo.YourTable
   ALTER COLUMN YourColumnName BIT

The other option would be to create a new column of type BIT, fill it from the old column, and once you're done, drop the old column and rename the new one to the old name. That way, if something during the conversion goes wrong, you can always go back since you still have all the data..

What does AngularJS do better than jQuery?

Data-Binding

You go around making your webpage, and keep on putting {{data bindings}} whenever you feel you would have dynamic data. Angular will then provide you a $scope handler, which you can populate (statically or through calls to the web server).

This is a good understanding of data-binding. I think you've got that down.

DOM Manipulation

For simple DOM manipulation, which doesnot involve data manipulation (eg: color changes on mousehover, hiding/showing elements on click), jQuery or old-school js is sufficient and cleaner. This assumes that the model in angular's mvc is anything that reflects data on the page, and hence, css properties like color, display/hide, etc changes dont affect the model.

I can see your point here about "simple" DOM manipulation being cleaner, but only rarely and it would have to be really "simple". I think DOM manipulation is one the areas, just like data-binding, where Angular really shines. Understanding this will also help you see how Angular considers its views.

I'll start by comparing the Angular way with a vanilla js approach to DOM manipulation. Traditionally, we think of HTML as not "doing" anything and write it as such. So, inline js, like "onclick", etc are bad practice because they put the "doing" in the context of HTML, which doesn't "do". Angular flips that concept on its head. As you're writing your view, you think of HTML as being able to "do" lots of things. This capability is abstracted away in angular directives, but if they already exist or you have written them, you don't have to consider "how" it is done, you just use the power made available to you in this "augmented" HTML that angular allows you to use. This also means that ALL of your view logic is truly contained in the view, not in your javascript files. Again, the reasoning is that the directives written in your javascript files could be considered to be increasing the capability of HTML, so you let the DOM worry about manipulating itself (so to speak). I'll demonstrate with a simple example.

This is the markup we want to use. I gave it an intuitive name.

<div rotate-on-click="45"></div>

First, I'd just like to comment that if we've given our HTML this functionality via a custom Angular Directive, we're already done. That's a breath of fresh air. More on that in a moment.

Implementation with jQuery

live demo here (click).

function rotate(deg, elem) {
  $(elem).css({
    webkitTransform: 'rotate('+deg+'deg)', 
    mozTransform: 'rotate('+deg+'deg)', 
    msTransform: 'rotate('+deg+'deg)', 
    oTransform: 'rotate('+deg+'deg)', 
    transform: 'rotate('+deg+'deg)'    
  });
}

function addRotateOnClick($elems) {
  $elems.each(function(i, elem) {
    var deg = 0;
    $(elem).click(function() {
      deg+= parseInt($(this).attr('rotate-on-click'), 10);
      rotate(deg, this);
    });
  });
}

addRotateOnClick($('[rotate-on-click]'));

Implementation with Angular

live demo here (click).

app.directive('rotateOnClick', function() {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      var deg = 0;
      element.bind('click', function() {
        deg+= parseInt(attrs.rotateOnClick, 10);
        element.css({
          webkitTransform: 'rotate('+deg+'deg)', 
          mozTransform: 'rotate('+deg+'deg)', 
          msTransform: 'rotate('+deg+'deg)', 
          oTransform: 'rotate('+deg+'deg)', 
          transform: 'rotate('+deg+'deg)'    
        });
      });
    }
  };
});

Pretty light, VERY clean and that's just a simple manipulation! In my opinion, the angular approach wins in all regards, especially how the functionality is abstracted away and the dom manipulation is declared in the DOM. The functionality is hooked onto the element via an html attribute, so there is no need to query the DOM via a selector, and we've got two nice closures - one closure for the directive factory where variables are shared across all usages of the directive, and one closure for each usage of the directive in the link function (or compile function).

Two-way data binding and directives for DOM manipulation are only the start of what makes Angular awesome. Angular promotes all code being modular, reusable, and easily testable and also includes a single-page app routing system. It is important to note that jQuery is a library of commonly needed convenience/cross-browser methods, but Angular is a full featured framework for creating single page apps. The angular script actually includes its own "lite" version of jQuery so that some of the most essential methods are available. Therefore, you could argue that using Angular IS using jQuery (lightly), but Angular provides much more "magic" to help you in the process of creating apps.

This is a great post for more related information: How do I “think in AngularJS” if I have a jQuery background?

General differences.

The above points are aimed at the OP's specific concerns. I'll also give an overview of the other important differences. I suggest doing additional reading about each topic as well.

Angular and jQuery can't reasonably be compared.

Angular is a framework, jQuery is a library. Frameworks have their place and libraries have their place. However, there is no question that a good framework has more power in writing an application than a library. That's exactly the point of a framework. You're welcome to write your code in plain JS, or you can add in a library of common functions, or you can add a framework to drastically reduce the code you need to accomplish most things. Therefore, a more appropriate question is:

Why use a framework?

Good frameworks can help architect your code so that it is modular (therefore reusable), DRY, readable, performant and secure. jQuery is not a framework, so it doesn't help in these regards. We've all seen the typical walls of jQuery spaghetti code. This isn't jQuery's fault - it's the fault of developers that don't know how to architect code. However, if the devs did know how to architect code, they would end up writing some kind of minimal "framework" to provide the foundation (achitecture, etc) I discussed a moment ago, or they would add something in. For example, you might add RequireJS to act as part of your framework for writing good code.

Here are some things that modern frameworks are providing:

  • Templating
  • Data-binding
  • routing (single page app)
  • clean, modular, reusable architecture
  • security
  • additional functions/features for convenience

Before I further discuss Angular, I'd like to point out that Angular isn't the only one of its kind. Durandal, for example, is a framework built on top of jQuery, Knockout, and RequireJS. Again, jQuery cannot, by itself, provide what Knockout, RequireJS, and the whole framework built on top them can. It's just not comparable.

If you need to destroy a planet and you have a Death Star, use the Death star.

Angular (revisited).

Building on my previous points about what frameworks provide, I'd like to commend the way that Angular provides them and try to clarify why this is matter of factually superior to jQuery alone.

DOM reference.

In my above example, it is just absolutely unavoidable that jQuery has to hook onto the DOM in order to provide functionality. That means that the view (html) is concerned about functionality (because it is labeled with some kind of identifier - like "image slider") and JavaScript is concerned about providing that functionality. Angular eliminates that concept via abstraction. Properly written code with Angular means that the view is able to declare its own behavior. If I want to display a clock:

<clock></clock>

Done.

Yes, we need to go to JavaScript to make that mean something, but we're doing this in the opposite way of the jQuery approach. Our Angular directive (which is in it's own little world) has "augumented" the html and the html hooks the functionality into itself.

MVW Architecure / Modules / Dependency Injection

Angular gives you a straightforward way to structure your code. View things belong in the view (html), augmented view functionality belongs in directives, other logic (like ajax calls) and functions belong in services, and the connection of services and logic to the view belongs in controllers. There are some other angular components as well that help deal with configuration and modification of services, etc. Any functionality you create is automatically available anywhere you need it via the Injector subsystem which takes care of Dependency Injection throughout the application. When writing an application (module), I break it up into other reusable modules, each with their own reusable components, and then include them in the bigger project. Once you solve a problem with Angular, you've automatically solved it in a way that is useful and structured for reuse in the future and easily included in the next project. A HUGE bonus to all of this is that your code will be much easier to test.

It isn't easy to make things "work" in Angular.

THANK GOODNESS. The aforementioned jQuery spaghetti code resulted from a dev that made something "work" and then moved on. You can write bad Angular code, but it's much more difficult to do so, because Angular will fight you about it. This means that you have to take advantage (at least somewhat) to the clean architecture it provides. In other words, it's harder to write bad code with Angular, but more convenient to write clean code.

Angular is far from perfect. The web development world is always growing and changing and there are new and better ways being put forth to solve problems. Facebook's React and Flux, for example, have some great advantages over Angular, but come with their own drawbacks. Nothing's perfect, but Angular has been and is still awesome for now. Just as jQuery once helped the web world move forward, so has Angular, and so will many to come.

Using set_facts and with_items together in Ansible

Jinja 2.6 does not have the map function. So an alternate way of doing this would be:

set_fact: foo="{% for i in bar_result.results %}{{ i.ansible_facts.foo_item }}{%endfor%}"

Converting Integers to Roman Numerals - Java

From Java Notes 6.0 website:

      /**
       * An object of type RomanNumeral is an integer between 1 and 3999.  It can
       * be constructed either from an integer or from a string that represents
       * a Roman numeral in this range.  The function toString() will return a
       * standardized Roman numeral representation of the number.  The function
       * toInt() will return the number as a value of type int.
       */
      public class RomanNumeral {

         private final int num;   // The number represented by this Roman numeral.

         /* The following arrays are used by the toString() function to construct
            the standard Roman numeral representation of the number.  For each i,
            the number numbers[i] is represented by the corresponding string, letters[i].
         */

         private static int[]    numbers = { 1000,  900,  500,  400,  100,   90,  
                                               50,   40,   10,    9,    5,    4,    1 };

         private static String[] letters = { "M",  "CM",  "D",  "CD", "C",  "XC",
                                             "L",  "XL",  "X",  "IX", "V",  "IV", "I" };

         /**
          * Constructor.  Creates the Roman number with the int value specified
          * by the parameter.  Throws a NumberFormatException if arabic is
          * not in the range 1 to 3999 inclusive.
          */
         public RomanNumeral(int arabic) {
            if (arabic < 1)
               throw new NumberFormatException("Value of RomanNumeral must be positive.");
            if (arabic > 3999)
               throw new NumberFormatException("Value of RomanNumeral must be 3999 or less.");
            num = arabic;
         }


         /*
          * Constructor.  Creates the Roman number with the given representation.
          * For example, RomanNumeral("xvii") is 17.  If the parameter is not a
          * legal Roman numeral, a NumberFormatException is thrown.  Both upper and
          * lower case letters are allowed.
          */
         public RomanNumeral(String roman) {

            if (roman.length() == 0)
               throw new NumberFormatException("An empty string does not define a Roman numeral.");

            roman = roman.toUpperCase();  // Convert to upper case letters.

            int i = 0;       // A position in the string, roman;
            int arabic = 0;  // Arabic numeral equivalent of the part of the string that has
                             //    been converted so far.

            while (i < roman.length()) {

               char letter = roman.charAt(i);        // Letter at current position in string.
               int number = letterToNumber(letter);  // Numerical equivalent of letter.

               i++;  // Move on to next position in the string

               if (i == roman.length()) {
                     // There is no letter in the string following the one we have just processed.
                     // So just add the number corresponding to the single letter to arabic.
                  arabic += number;
               }
               else {
                     // Look at the next letter in the string.  If it has a larger Roman numeral
                     // equivalent than number, then the two letters are counted together as
                     // a Roman numeral with value (nextNumber - number).
                  int nextNumber = letterToNumber(roman.charAt(i));
                  if (nextNumber > number) {
                       // Combine the two letters to get one value, and move on to next position in string.
                     arabic += (nextNumber - number);
                     i++;
                  }
                  else {
                       // Don't combine the letters.  Just add the value of the one letter onto the number.
                     arabic += number;
                  }
               }

            }  // end while

            if (arabic > 3999)
               throw new NumberFormatException("Roman numeral must have value 3999 or less.");

            num = arabic;

         } // end constructor


         /**
          * Find the integer value of letter considered as a Roman numeral.  Throws
          * NumberFormatException if letter is not a legal Roman numeral.  The letter 
          * must be upper case.
          */
         private int letterToNumber(char letter) {
            switch (letter) {
               case 'I':  return 1;
               case 'V':  return 5;
               case 'X':  return 10;
               case 'L':  return 50;
               case 'C':  return 100;
               case 'D':  return 500;
               case 'M':  return 1000;
               default:   throw new NumberFormatException(
                            "Illegal character \"" + letter + "\" in Roman numeral");
            }
         }


         /**
          * Return the standard representation of this Roman numeral.
          */
         public String toString() {
            String roman = "";  // The roman numeral.
            int N = num;        // N represents the part of num that still has
                                //   to be converted to Roman numeral representation.
            for (int i = 0; i < numbers.length; i++) {
               while (N >= numbers[i]) {
                  roman += letters[i];
                  N -= numbers[i];
               }
            }
            return roman;
         }


         /**
          * Return the value of this Roman numeral as an int.
          */
         public int toInt() {
            return num;
         }


      }

ArrayList - How to modify a member of an object?

Use myList.get(3) to get access to the current object and modify it, assuming instances of Customer have a way to be modified.

How to send email by using javascript or jquery

You can send Email by Jquery just follow these steps 

include this link : <script src="https://smtpjs.com/v3/smtp.js"></script>
after that use this code :

$( document ).ready(function() {
 Email.send({
Host : "smtp.yourisp.com",
Username : "username",
Password : "password",
To : '[email protected]',
From : "[email protected]",
Subject : "This is the subject",
Body : "And this is the body"}).then( message => alert(message));});

How to quickly and conveniently create a one element arraylist

With Java 8 Streams:

Stream.of(object).collect(Collectors.toList())

or if you need a set:

Stream.of(object).collect(Collectors.toSet())

jQuery - setting the selected value of a select control via its text description

Try

[...mySelect.options].forEach(o=> o.selected = o.text == 'Text C' )

_x000D_
_x000D_
[...mySelect.options].forEach(o=> o.selected = o.text == 'Text C' );
_x000D_
<select id="mySelect">
  <option value="A">Text A</option>
  <option value="B">Text B</option>
  <option value="C">Text C</option>
</select>
_x000D_
_x000D_
_x000D_

Add Variables to Tuple

Tuples are immutable; you can't change which variables they contain after construction. However, you can concatenate or slice them to form new tuples:

a = (1, 2, 3)
b = a + (4, 5, 6)  # (1, 2, 3, 4, 5, 6)
c = b[1:]  # (2, 3, 4, 5, 6)

And, of course, build them from existing values:

name = "Joe"
age = 40
location = "New York"
joe = (name, age, location)

Unable to find a @SpringBootConfiguration when doing a JpaTest

It is worth to check if you have refactored package name of your main class annotated with @SpringBootApplication. In that case the testcase should be in an appropriate package otherwise it will be looking for it in the older package . this was the case for me.

Redirecting to URL in Flask

its pretty easy if u just want to redirect to a url without any status codes or anything like that u can simple say

from flask import Flask, redirect

app = Flask(__name__)

@app.route('/')
def redirect_to_link():
    # return redirect method, NOTE: replace google.com with the link u want
    return redirect('https://google.com')

here is the link to the Flask Docs for more explanation

github: server certificate verification failed

Another possible cause is that the clock of your machine is not synced (e.g. on Raspberry Pi). Check the current date/time using:

$ date

If the date and/or time is incorrect, try to update using:

$ sudo ntpdate -u time.nist.gov

Pass variables to Ruby script via command line

Something like this:

ARGV.each do|a|
  puts "Argument: #{a}"
end

then

$ ./test.rb "test1 test2"

or

v1 = ARGV[0]
v2 = ARGV[1]
puts v1       #prints test1
puts v2       #prints test2

Creating a SOAP call using PHP with an XML body

There are a couple of ways to solve this. The least hackiest and almost what you want:

$client = new SoapClient(
    null,
    array(
        'location' => 'https://example.com/ExampleWebServiceDL/services/ExampleHandler',
        'uri' => 'http://example.com/wsdl',
        'trace' => 1,
        'use' => SOAP_LITERAL,
    )
);
$params = new \SoapVar("<Acquirer><Id>MyId</Id><UserId>MyUserId</UserId><Password>MyPassword</Password></Acquirer>", XSD_ANYXML);
$result = $client->Echo($params);

This gets you the following XML:

<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://example.com/wsdl">
    <SOAP-ENV:Body>
        <ns1:Echo>
            <Acquirer>
                <Id>MyId</Id>
                <UserId>MyUserId</UserId>
                <Password>MyPassword</Password>
            </Acquirer>
        </ns1:Echo>
    </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

That is almost exactly what you want, except for the namespace on the method name. I don't know if this is a problem. If so, you can hack it even further. You could put the <Echo> tag in the XML string by hand and have the SoapClient not set the method by adding 'style' => SOAP_DOCUMENT, to the options array like this:

$client = new SoapClient(
    null,
    array(
        'location' => 'https://example.com/ExampleWebServiceDL/services/ExampleHandler',
        'uri' => 'http://example.com/wsdl',
        'trace' => 1,
        'use' => SOAP_LITERAL,
        'style' => SOAP_DOCUMENT,
    )
);
$params = new \SoapVar("<Echo><Acquirer><Id>MyId</Id><UserId>MyUserId</UserId><Password>MyPassword</Password></Acquirer></Echo>", XSD_ANYXML);
$result = $client->MethodNameIsIgnored($params);

This results in the following request XML:

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
    <SOAP-ENV:Body>
        <Echo>
            <Acquirer>
                <Id>MyId</Id>
                <UserId>MyUserId</UserId>
                <Password>MyPassword</Password>
            </Acquirer>
        </Echo>
    </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

Finally, if you want to play around with SoapVar and SoapParam objects, you can find a good reference in this comment in the PHP manual: http://www.php.net/manual/en/soapvar.soapvar.php#104065. If you get that to work, please let me know, I failed miserably.

Is there a Python caching library?

Look at bda.cache http://pypi.python.org/pypi/bda.cache - uses ZCA and is tested with zope and bfg.

Vertical divider doesn't work in Bootstrap 3

Here is some LESS for you, in case you customize the navbar:

.navbar .divider-vertical {
    height: floor(@navbar-height - @navbar-margin-bottom);
    margin: floor(@navbar-margin-bottom / 2) 9px;
    border-left: 1px solid #f2f2f2;
    border-right: 1px solid #ffffff;
}

How to format time since xxx e.g. “4 minutes ago” similar to Stack Exchange sites

_x000D_
_x000D_
function timeSince(date) {

  var seconds = Math.floor((new Date() - date) / 1000);

  var interval = seconds / 31536000;

  if (interval > 1) {
    return Math.floor(interval) + " years";
  }
  interval = seconds / 2592000;
  if (interval > 1) {
    return Math.floor(interval) + " months";
  }
  interval = seconds / 86400;
  if (interval > 1) {
    return Math.floor(interval) + " days";
  }
  interval = seconds / 3600;
  if (interval > 1) {
    return Math.floor(interval) + " hours";
  }
  interval = seconds / 60;
  if (interval > 1) {
    return Math.floor(interval) + " minutes";
  }
  return Math.floor(seconds) + " seconds";
}
var aDay = 24*60*60*1000;
console.log(timeSince(new Date(Date.now()-aDay)));
console.log(timeSince(new Date(Date.now()-aDay*2)));
_x000D_
_x000D_
_x000D_

How to create javascript delay function

Ah yes. Welcome to Asynchronous execution.

Basically, pausing a script would cause the browser and page to become unresponsive for 3 seconds. This is horrible for web apps, and so isn't supported.

Instead, you have to think "event-based". Use setTimeout to call a function after a certain amount of time, which will continue to run the JavaScript on the page during that time.

Node.js throws "btoa is not defined" error

The solutions posted here don't work in non-ascii characters (i.e. if you plan to exchange base64 between Node.js and a browser). In order to make it work you have to mark the input text as 'binary'.

Buffer.from('Hélló wórld!!', 'binary').toString('base64')

This gives you SOlsbPMgd/NybGQhIQ==. If you make atob('SOlsbPMgd/NybGQhIQ==') in a browser it will decode it in the right way. It will do it right also in Node.js via:

Buffer.from('SOlsbPMgd/NybGQhIQ==', 'base64').toString('binary')

If you don't do the "binary part", you will decode wrongly the special chars.

I got it from the implementation of the btoa npm package:

SQL Server 2008 Connection Error "No process is on the other end of the pipe"

Forcing the TCP/IP connection (by providing 127.0.0.1 instead of localhost or .) can reveal the real reason for the error. In my case, the database name specified in connection string was incorrect.

So, here is the checklist so far:

  • Make sure Named Pipe is enabled in configuration manager (don't forget to restart the server).
  • Make sure SQL Server Authentication (or Mixed Mode) is enabled.
  • Make sure your user name and password are correct.
  • Make sure the database you are connecting to exists.

npm install gives error "can't find a package.json file"

Check this link for steps on how to install express.js for your application locally.

But, if for some reason you are installing express globally, make sure the directory you are in is the directory where Node is installed. On my Windows 10, package.json is located at

C:\Program Files\nodejs\node_modules\npm

Open command prompt as administrator and change your directory to the location where your package.json is located.

Then issue the install command.

How to override application.properties during production in Spring-Boot?

The spring configuration precedence is as follows.

  1. ServletConfig init Parameter
  2. ServletContext init parameter
  3. JNDI attributes
  4. System.getProperties()

So your configuration will be overridden at the command-line if you wish to do that. But the recommendation is to avoid overriding, though you can use multiple profiles.

Move an array element from one array position to another

This is based on @Reid's solution. Except:

  • I'm not changing the Array prototype.
  • Moving an item out of bounds to the right does not create undefined items, it just moves the item to the right-most position.

Function:

function move(array, oldIndex, newIndex) {
    if (newIndex >= array.length) {
        newIndex = array.length - 1;
    }
    array.splice(newIndex, 0, array.splice(oldIndex, 1)[0]);
    return array;
}

Unit tests:

describe('ArrayHelper', function () {
    it('Move right', function () {
        let array = [1, 2, 3];
        arrayHelper.move(array, 0, 1);
        assert.equal(array[0], 2);
        assert.equal(array[1], 1);
        assert.equal(array[2], 3);
    })
    it('Move left', function () {
        let array = [1, 2, 3];
        arrayHelper.move(array, 1, 0);
        assert.equal(array[0], 2);
        assert.equal(array[1], 1);
        assert.equal(array[2], 3);
    });
    it('Move out of bounds to the left', function () {
        let array = [1, 2, 3];
        arrayHelper.move(array, 1, -2);
        assert.equal(array[0], 2);
        assert.equal(array[1], 1);
        assert.equal(array[2], 3);
    });
    it('Move out of bounds to the right', function () {
        let array = [1, 2, 3];
        arrayHelper.move(array, 1, 4);
        assert.equal(array[0], 1);
        assert.equal(array[1], 3);
        assert.equal(array[2], 2);
    });
});

Setting up SSL on a local xampp/apache server

I did most of the suggested stuff here, still didnt work. Tried this and it worked: Open your XAMPP Control Panel, locate the Config button for the Apache module. Click on the Config button and Select PHP (php.ini). Open with any text editor and remove the semi-column before php_openssl. Save and Restart Apache. That should do!

ES6 class variable alternatives

This is a bit hackish combo of static and get works for me

class ConstantThingy{
        static get NO_REENTER__INIT() {
            if(ConstantThingy._NO_REENTER__INIT== null){
                ConstantThingy._NO_REENTER__INIT = new ConstantThingy(false,true);
            }
            return ConstantThingy._NO_REENTER__INIT;
        }
}

elsewhere used

var conf = ConstantThingy.NO_REENTER__INIT;
if(conf.init)...

JavaScript - Replace all commas in a string

var mystring = "this,is,a,test"
mystring.replace(/,/g, "newchar");

Use the global(g) flag

Simple DEMO

Trying to get property of non-object - CodeIgniter

In my case, I was looping through a series of objects from an XML file, but some of the instances apparently were not objects which was causing the error. Checking if the object was empty before processing it fixed the problem.

In other words, without checking if the object was empty, the script would error out on any empty object with the error as given below.

Trying to get property of non-object

For Example:

if (!empty($this->xml_data->thing1->thing2))
{
   foreach ($this->xml_data->thing1->thing2 as $thing)
   {

   }
}

AlertDialog.Builder with custom layout and EditText; cannot access view

Use this one

   AlertDialog.Builder builder = new AlertDialog.Builder(activity);
    // Get the layout inflater
    LayoutInflater inflater = (activity).getLayoutInflater();
    // Inflate and set the layout for the dialog
    // Pass null as the parent view because its going in the
    // dialog layout
    builder.setTitle(title);
    builder.setCancelable(false);
    builder.setIcon(R.drawable.galleryalart);
    builder.setView(inflater.inflate(R.layout.dialogue, null))
    // Add action buttons
            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int id) {

                    }
                }
            });
    builder.create();
    builder.show();

Matching exact string with JavaScript

If you do not use any placeholders (as the "exactly" seems to imply), how about string comparison instead?

If you do use placeholders, ^ and $ match the beginning and the end of a string, respectively.

Check if null Boolean is true results in exception

Or with the power of Java 8 Optional, you also can do such trick:

Optional.ofNullable(boolValue).orElse(false)

:)

Eclipse: Java was started but returned error code=13

This is often caused by the (accidental) removal of the JRE folder that is set in the Eclipse configuration. You can try following these instructions from the Eclipse wiki on how to configure the eclipse.ini file to include the the JRE location, or alternatively, launch eclipse from the command prompt using VM arguments. I have tried them both myself and in my opinion, the command prompt option works much better.

Once you are able to launch Eclipse, make sure you verify the installed JRE location under Java --> Installed JREs in the Preferences window.

Benefits of using the conditional ?: (ternary) operator

I usually choose a ternary operator when I'd have a lot of duplicate code otherwise.

if (a > 0)
    answer = compute(a, b, c, d, e);
else
    answer = compute(-a, b, c, d, e);

With a ternary operator, this could be accomplished with the following.

answer = compute(a > 0 ? a : -a, b, c, d, e); 

Call Jquery function

Try this code:

$(document).ready(function(){
    $('#YourControlID').click(function(){
        if() { //your condition
            $.messager.show({  
                title:'My Title',  
                msg:'The message content',  
                showType:'fade',  
                style:{  
                    right:'',  
                    bottom:''  
                }  
            });  
        }
    });
});

How to get date, month, year in jQuery UI datepicker?

You can use method getDate():

$('#calendar').datepicker({
    dateFormat: 'yy-m-d',
    inline: true,
    onSelect: function(dateText, inst) { 
        var date = $(this).datepicker('getDate'),
            day  = date.getDate(),  
            month = date.getMonth() + 1,              
            year =  date.getFullYear();
        alert(day + '-' + month + '-' + year);
    }
});

FIDDLE

What's the difference between a 302 and a 307 redirect?

302 is temporary redirect, which is generated by the server whereas 307 is internal redirect response generated by the browser. Internal redirect means that redirect is done automatically by browser internally, basically the browser alters the entered url from http to https in get request by itself before making the request so request for unsecured connection is never made to the internet. Whether browser will alter the url to https or not depends upon the hsts preload list that comes preinstalled with the browser. You can also add any site which support https to the list by entering the domain in the hsts preload list of your own browser which is at chrome://net-internals/#hsts.One more thing website domains can be added by their owners to preload list by filling up the form at https://hstspreload.org/ so that it comes preinstalled in browsers for every user even though I mention you can do particularly for yourself also.


Let me explain with an example:
I made a get request to http://www.pentesteracademy.com which supports only https and I don't have that domain in my hsts preload list on my browser as site owner has not registered for it to come with preinstalled hsts preload list. request and response headers
GET request for unsecure version of the site is redirected to secure version(see http header named location for that in response in above image).
Now I add the site to my own browser preload list by adding its domain in Add hsts domain form at chrome://net-internals/#hsts, which modifies my personal preload list on my chrome browser.Be sure to select include subdomains for STS option there.
Let's see the request and response for the same website now after adding it to hsts preload list.
request and response headers
you can see the internal redirect 307 there in response headers, actually this response is generated by your browser not by server.
Also HSTS preload list can help prevent users reach the unsecure version of site as 302 redirect are prone to mitm attacks.
Hope I somewhat helped you understand more about redirects.

How to get overall CPU usage (e.g. 57%) on Linux

Take a look at cat /proc/stat

grep 'cpu ' /proc/stat | awk '{usage=($2+$4)*100/($2+$4+$5)} END {print usage "%"}'

EDIT please read comments before copy-paste this or using this for any serious work. This was not tested nor used, it's an idea for people who do not want to install a utility or for something that works in any distribution. Some people think you can "apt-get install" anything.

NOTE: this is not the current CPU usage, but the overall CPU usage in all the cores since the system bootup. This could be very different from the current CPU usage. To get the current value top (or similar tool) must be used.

Current CPU usage can be potentially calculated with:

awk '{u=$2+$4; t=$2+$4+$5; if (NR==1){u1=u; t1=t;} else print ($2+$4-u1) * 100 / (t-t1) "%"; }' \
<(grep 'cpu ' /proc/stat) <(sleep 1;grep 'cpu ' /proc/stat)

How to check if a "lateinit" variable has been initialized?

If you have a lateinit property in one class and need to check if it is initialized from another class

if(foo::file.isInitialized) // this wouldn't work

The workaround I have found is to create a function to check if the property is initialized and then you can call that function from any other class.

Example:

class Foo() {

    private lateinit var myFile: File

    fun isFileInitialised() = ::file.isInitialized
}

 // in another class
class Bar() {

    val foo = Foo()

    if(foo.isFileInitialised()) // this should work
}

Explain why constructor inject is better than other options

A class that takes a required dependency as a constructor argument can only be instantiated if that argument is provided (you should have a guard clause to make sure the argument is not null.) A constructor therefore enforces the dependency requirement whether or not you're using Spring, making it container-agnostic.

If you use setter injection, the setter may or may not be called, so the instance may never be provided with its dependency. The only way to force the setter to be called is using @Required or @Autowired , which is specific to Spring and is therefore not container-agnostic.

So to keep your code independent of Spring, use constructor arguments for injection.

Update: Spring 4.3 will perform implicit injection in single-constructor scenarios, making your code more independent of Spring by potentially not requiring an @Autowired annotation at all.

Add a default value to a column through a migration

Here's how you should do it:

change_column :users, :admin, :boolean, :default => false

But some databases, like PostgreSQL, will not update the field for rows previously created, so make sure you update the field manaully on the migration too.

Create a date time with month and day only, no year

How about creating a timer with the next date?

In your timer callback you create the timer for the following year? DateTime has always a year value. What you want to express is a recurring time specification. This is another type which you would need to create. DateTime is always represents a specific date and time but not a recurring date.

OSError: [Errno 8] Exec format error

If you think the space before and after "=" is mandatory, try it as separate item in the list.

Out = subprocess.Popen(['/usr/local/bin/script', 'hostname', '=', 'actual server name', '-p', 'LONGLIST'],shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)

How to change the status bar background color and text color on iOS 7?

Swift 4

In Info.plist add this property

View controller-based status bar appearance to NO

and after that in AppDelegate inside the didFinishLaunchingWithOptions add these lines of code

UIApplication.shared.isStatusBarHidden = false
UIApplication.shared.statusBarStyle = .lightContent

Put content in HttpResponseMessage object?

You should create the response using Request.CreateResponse:

HttpResponseMessage response =  Request.CreateResponse(HttpStatusCode.BadRequest, "Error message");

You can pass objects not just strings to CreateResponse and it will serialize them based on the request's Accept header. This saves you from manually choosing a formatter.