Programs & Examples On #Ruby

Ruby is a multi-platform open-source, dynamic object-oriented interpreted language, created by Yukihiro Matsumoto (Matz) in 1995. The [ruby] tag is for questions related to the Ruby language, including its syntax and its libraries. Ruby on Rails questions should be tagged with [ruby-on-rails].

Checking if a variable is not nil and not zero in ruby

I believe the following is good enough for ruby code. I don't think I could write a unit test that shows any difference between this and the original.

if discount != 0

Get names of all files from a folder with Ruby

You also have the shortcut option of


and if you want to find all Ruby files in any folder or sub-folder:


Testing for empty or nil-value string

The second clause does not need a !variable.nil? check—if evaluation reaches that point, variable.nil is guaranteed to be false (because of short-circuiting).

This should be sufficient:

variable = id if variable.nil? || variable.empty?

If you're working with Ruby on Rails, Object.blank? solves this exact problem:

An object is blank if it’s false, empty, or a whitespace string. For example, "", " ", nil, [], and {} are all blank.

Parsing a JSON string in Ruby

It looks like a JSON string. You can use one of many JSON libraries and it's as simple as doing:


How to preserve request url with nginx proxy_pass

Note to other people finding this: The heart of the solution to make nginx not manipulate the URL, is to remove the slash at the end of the Copy: proxy_pass directive. http://my_app_upstream vs http://my_app_upstream/ – Hugo Josefson

I found this above in the comments but I think it really should be an answer.

Find value in an array


myarray.index "valuetoFind"

That will return you the index of the element you want or nil if your array doesn't contain the value.

String concatenation in Ruby

If you are just concatenating paths you can use Ruby's own File.join method.

source = File.join(ROOT_DIR, project, 'App.config')

Converting an integer to a hexadecimal string in Ruby

How about using %/sprintf:

i = 20
"%x" % i  #=> "14"

Test if string is a number in Ruby on Rails

As Jakob S suggested in his answer, Kernel#Float can be used to validate numericality of the string, only thing that I can add is one-liner version of that, without using rescue block to control flow (which is considered as a bad practice sometimes)

  Float(my_string, exception: false).present?

How to change default timezone for Active Record in Rails?

for Chinese user, just add two lines below to you config/application.rb :

config.active_record.default_timezone = :local
config.time_zone = 'Beijing'

Ruby Array find_first object?

use array detect method if you wanted to return first value where block returns true

[1,2,3,11,34].detect(&:even?) #=> 2


[1,2,3,11,34].detect{|i| i.even?} #=> 2

If you wanted to return all values where block returns true then use select

[1,2,3,11,34].select(&:even?)  #=> [2, 34]

Ruby objects and JSON serialization (without Rails)

I used to virtus. Really powerful tool, allows to create a dynamic Ruby structure structure based on your specified classes. Easy DSL, possible to create objects from ruby hashes, there is strict mode. Check it out.

How to make a HTTP request using Ruby on Rails?

OpenURI is the best; it's as simple as

require 'open-uri'
response = open('').read

Read input from console in Ruby?

If you want to make interactive console:

#!/usr/bin/env ruby

require "readline"
addends = []
while addend_string = Readline.readline("> ", true)
  addends << addend_string.to_i
  puts "#{addends.join(' + ')} = #{addends.sum}"

Usage (assuming you put above snippet into summator file in current directory):

chmod +x summator
> 1
1 = 1
> 2
1 + 2 = 3

Use Ctrl + D to exit

How to return a part of an array in Ruby?

Yes, Ruby has very similar array-slicing syntax to Python. Here is the ri documentation for the array index method:

--------------------------------------------------------------- Array#[]
     array[index]                -> obj      or nil
     array[start, length]        -> an_array or nil
     array[range]                -> an_array or nil
     array.slice(index)          -> obj      or nil
     array.slice(start, length)  -> an_array or nil
     array.slice(range)          -> an_array or nil
     Element Reference---Returns the element at index, or returns a 
     subarray starting at start and continuing for length elements, or 
     returns a subarray specified by range. Negative indices count 
     backward from the end of the array (-1 is the last element). 
     Returns nil if the index (or starting index) are out of range.

        a = [ "a", "b", "c", "d", "e" ]
        a[2] +  a[0] + a[1]    #=> "cab"
        a[6]                   #=> nil
        a[1, 2]                #=> [ "b", "c" ]
        a[1..3]                #=> [ "b", "c", "d" ]
        a[4..7]                #=> [ "e" ]
        a[6..10]               #=> nil
        a[-3, 3]               #=> [ "c", "d", "e" ]
        # special cases
        a[5]                   #=> nil
        a[6, 1]                #=> nil
        a[5, 1]                #=> []
        a[5..10]               #=> []

ruby 1.9: invalid byte sequence in UTF-8

This seems to work:

def sanitize_utf8(string)
  return nil if string.nil?
  return string if string.valid_encoding? { |c| c.valid_encoding? }.join

How to find a hash key containing a matching value

From the docs:

  • (Object?) detect(ifnone = nil) {|obj| ... }
  • (Object?) find(ifnone = nil) {|obj| ... }
  • (Object) detect(ifnone = nil)
  • (Object) find(ifnone = nil)

Passes each entry in enum to block. Returns the first for which block is not false. If no object matches, calls ifnone and returns its result when it is specified, or returns nil otherwise.

If no block is given, an enumerator is returned instead.

(1..10).detect  {|i| i % 5 == 0 and i % 7 == 0 }   #=> nil
(1..100).detect {|i| i % 5 == 0 and i % 7 == 0 }   #=> 35

This worked for me:

clients.detect{|client| client.last['client_id'] == '2180' } #=> ["orange", {"client_id"=>"2180"}] 

clients.detect{|client| client.last['client_id'] == '999999' } #=> nil 


How to break out from a ruby block?

Use the keyword next. If you do not want to continue to the next item, use break.

When next is used within a block, it causes the block to exit immediately, returning control to the iterator method, which may then begin a new iteration by invoking the block again:

f.each do |line|              # Iterate over the lines in file f
  next if line[0,1] == "#"    # If this line is a comment, go to the next
  puts eval(line)

When used in a block, break transfers control out of the block, out of the iterator that invoked the block, and to the first expression following the invocation of the iterator:

f.each do |line|             # Iterate over the lines in file f
  break if line == "quit\n"  # If this break statement is executed...
  puts eval(line)
puts "Good bye"              # ...then control is transferred here

And finally, the usage of return in a block:

return always causes the enclosing method to return, regardless of how deeply nested within blocks it is (except in the case of lambdas):

def find(array, target)
  array.each_with_index do |element,index|
    return index if (element == target)  # return from find
  nil  # If we didn't find the element, return nil

How to write to a JSON file in the correct format

This question is for ruby 1.8 but it still comes on top when googling.

in ruby >= 1.9 you can use


other than what mentioned in other answers, in ruby 1.8 you can also use one liner form"public/temp.json","w"){ |f| f.write tempHash.to_json }

Get underlined text with Markdown

Markdown doesn't have a defined syntax to underline text.

I guess this is because underlined text is hard to read, and that it's usually used for hyperlinks.

Is it ok to use `any?` to check if an array is not empty?

I'll suggest using unlessand blank to check is empty or not.

Example :

unless a.blank?
  a = "Is not empty"

This will know 'a' empty or not. If 'a' is blank then the below code will not run.

Case statement with multiple values in each 'when' block

In a case statement, a , is the equivalent of || in an if statement.

case car
   when 'toyota', 'lexus'
      # code

Some other things you can do with a Ruby case statement

Update just one gem with bundler

bundler update --source gem-name will update the revision hash in Gemfile.lock which you can compare with the last commit hash of that git branch (master by default).

GIT remote: [email protected]:organization/repo-name.git revision: c810f4a29547b60ca8106b7a6b9a9532c392c954

can be found at (I used shorthand 8 character commit hash for the url)

Rails 4 LIKE query - ActiveRecord adds quotes

If someone is using column names like "key" or "value", then you still see the same error that your mysql query syntax is bad. This should fix:

.where("`key` LIKE ?", "%#{key}%")

Output array to CSV in Ruby

I've got this down to just one line.

rows = [['a1', 'a2', 'a3'],['b1', 'b2', 'b3', 'b4'], ['c1', 'c2', 'c3'], ... ]
csv_str = rows.inject([]) { |csv, row|  csv << CSV.generate_line(row) }.join("")
#=> "a1,a2,a3\nb1,b2,b3\nc1,c2,c3\n" 

Do all of the above and save to a csv, in one line."ss.csv", "w") {|f| f.write(rows.inject([]) { |csv, row|  csv << CSV.generate_line(row) }.join(""))}


To convert an active record database to csv would be something like this I think, 'w') do |csv|
  csv << Model.column_names
  Model.where(query).each do |m|
    csv << m.attributes.values

Hmm @tamouse, that gist is somewhat confusing to me without reading the csv source, but generically, assuming each hash in your array has the same number of k/v pairs & that the keys are always the same, in the same order (i.e. if your data is structured), this should do the deed:

rowid = 0, 'w') do |csv|
  hsh_ary.each do |hsh|
    rowid += 1
    if rowid == 1
      csv << hsh.keys# adding header row (column labels)
      csv << hsh.values
    end# of if/else inside hsh
  end# of hsh's (rows)
end# of csv open

If your data isn't structured this obviously won't work

How do I encode/decode HTML entities in Ruby?

<% str="<h1> Test </h1>" %>

result: &lt; h1 &gt; Test &lt; /h1 &gt;

<%= CGI.unescapeHTML(str).html_safe %>

Checking if a variable is an integer

If you're uncertain of the type of the variable (it could be a string of number characters), say it was a credit card number passed into the params, so it would originally be a string but you want to make sure it doesn't have any letter characters in it, I would use this method:

    def is_number?(obj)
        obj.to_s == obj.to_i.to_s

    is_number? "123fh" # false
    is_number? "12345" # true

@Benny points out an oversight of this method, keep this in mind:

is_number? "01" # false. oops!

Best way to pretty print a hash

I came here through a search engine looking for a way to print hashes to end users in a human-readable format—particularly hashes with underscores in their keys.

Here's what I ended up doing using Rails do |key, val|
  key.to_s.humanize + ': ' + val.to_s
end.join('; ')

# Turns {:foo_bar => 'baz', :fee_ber => :bez} into 'Foo bar: Baz; Fee ber: Bez'.

Ruby function to remove all white spaces?

Ruby's .strip method performs the PHP equivalent to trim().

To remove all whitespace:

"  leading    trailing   ".squeeze(' ').strip
=> "leading trailing"

@Tass made me aware that my original answer removes duplicate letters in succession - YUCK! I've since switched to the squish method which is smarter about such occurrences if using the Rails framework.

require 'active_support/all'
"  leading    trailing   ".squish
=> "leading trailing"

"  good    men   ".squish
=> "good men"


Ruby: What is the easiest way to remove the first element from an array?

This is pretty neat:

head, *tail = [1, 2, 3, 4, 5]
#==> head = 1, tail = [2, 3, 4, 5]

As written in the comments, there's an advantage of not mutating the original list.

TypeError: no implicit conversion of Symbol into Integer

myHash.each{|item|..} is returning you array object for item iterative variable like the following :--

[:company_name, "MyCompany"]
[:street, "Mainstreet"]
[:postcode, "1234"]
[:city, "MyCity"]
[:free_seats, "3"]

You should do this:--

def format
  output =
  myHash.each do |k, v|
    output[k] = cleanup(v)

Ruby get object keys as array

Use the keys method: {"apple" => "fruit", "carrot" => "vegetable"}.keys == ["apple", "carrot"]

Should Gemfile.lock be included in .gitignore?

Assuming you're not writing a rubygem, Gemfile.lock should be in your repository. It's used as a snapshot of all your required gems and their dependencies. This way bundler doesn't have to recalculate all the gem dependencies each time you deploy, etc.

From cowboycoded's comment below:

If you are working on a gem, then DO NOT check in your Gemfile.lock. If you are working on a Rails app, then DO check in your Gemfile.lock.

Here's a nice article explaining what the lock file is.

How to pass command line arguments to a rake task

I couldn't figure out how to pass args and also the :environment until I worked this out:

namespace :db do
  desc 'Export product data'
  task :export, [:file_token, :file_path] => :environment do |t, args|
    args.with_defaults(:file_token => "products", :file_path => "./lib/data/")

       #do stuff [...]


And then I call like this:

rake db:export['foo, /tmp/']

How do I parse a YAML file in Ruby?

Maybe I'm missing something, but why try to parse the file? Why not just load the YAML and examine the object(s) that result?

If your sample YAML is in some.yml, then this:

require 'yaml'
thing = YAML.load_file('some.yml')
puts thing.inspect

gives me

{"javascripts"=>[{"fo_global"=>["lazyload-min", "holla-min"]}]}

Uploading a file in Rails

Okay. If you do not want to store the file in database and store in the application, like assets (custom folder), you can define non-db instance variable defined by attr_accessor: document and use form_for - f.file_field to get the file,

In controller,

 @person =

Here person_params return whitelisted params[:person] (define yourself)

Save file as,

dir = "#{Rails.root}/app/assets/custom_path"
FileUtils.mkdir(dir) unless dir
document = @person.document.document_file_name # check document uploaded params
File.copy_stream(@font.document, "#{dir}/#{document}")

Note, Add this path in .gitignore & if you want to use this file again add this path asset_pathan of application by application.rb

Whenever form read file field, it get store in tmp folder, later you can store at your place, I gave example to store at assets

note: Storing files like this will increase the size of the application, better to store in the database using paperclip.

How to create an exit message

I've never heard of such a function, but it would be trivial enough to implement...

def die(msg)
  puts msg

Then, if this is defined in some .rb file that you include in all your scripts, you are golden.... just because it's not built in doesn't mean you can't do it yourself ;-)

Append key/value pair to hash with << in Ruby

Similar as they are, merge! and store treat existing hashes differently depending on keynames, and will therefore affect your preference. Other than that from a syntax standpoint, merge!'s key: "value" syntax closely matches up against JavaScript and Python. I've always hated comma-separating key-value pairs, personally.

hash = {}
hash.merge!(key: "value")
hash.merge!(:key => "value")
puts hash


hash = {}, "value")"key", "value")
puts hash

{:key=>"value", "key"=>"value"}

To get the shovel operator << working, I would advise using Mark Thomas's answer.

How to solve error "Missing `secret_key_base` for 'production' environment" (Rails 4.1)

You can export the secret keys to as environment variables on the ~/.bashrc or ~/.bash_profile of your server:


And then, you can source your .bashrc or .bash_profile:

source ~/.bashrc 
source ~/.bash_profile

Never commit your secrets.yml

Create two-dimensional arrays and access sub-arrays in Ruby

rows, cols = x,y  # your values
grid = { }

As for accessing elements, this article is pretty good for step by step way to encapsulate an array in the way you want:

How to ruby array

How can I output leading zeros in Ruby?

As stated by the other answers, "%03d" % number works pretty well, but it goes against the rubocop ruby style guide:

Favor the use of sprintf and its alias format over the fairly cryptic String#% method

We can obtain the same result in a more readable way using the following:

format('%03d', number)

How to find where gem files are installed

This works and gives you the installed at path for each gem. This super helpful when trying to do multi-stage docker builds.. You can copy in the specific directory post-bundle install.

bash-4.4# gem list -d


aasm (5.0.6)
    Authors: Thorsten Boettger, Anil Maurya
    License: MIT
    Installed at: /usr/local/bundle

  State machine mixin for Ruby objects

How to capitalize the first letter in a String in Ruby

Use capitalize. From the String documentation:

Returns a copy of str with the first character converted to uppercase and the remainder to lowercase.

"hello".capitalize    #=> "Hello"
"HELLO".capitalize    #=> "Hello"
"123ABC".capitalize   #=> "123abc"

Ruby's gives "No such file or directory - text.txt (Errno::ENOENT)" error

Please use chomp() or chomp() with STDIN

i.e. test1.rb

print 'Enter File name: '

fname = STDIN.gets.chomp()  # or fname = gets.chomp()

fname_read =


Rails update_attributes without save?

I believe what you are looking for is assign_attributes.

It's basically the same as update_attributes but it doesn't save the record:

class User < ActiveRecord::Base
  attr_accessible :name
  attr_accessible :name, :is_admin, :as => :admin

user =
user.assign_attributes({ :name => 'Josh', :is_admin => true }) # Raises an ActiveModel::MassAssignmentSecurity::Error
user.assign_attributes({ :name => 'Bob'})        # => "Bob"
user.is_admin?   # => false
user.new_record? # => true

How to update ruby on linux (ubuntu)?

Generally the verions of programs are linked to the version of your operating system. So if you were running gutsy you would either have to upgrade to the new jaunty jackalope version which has ruby 1.9 or add the respoistories for jaunty to your /etc/apt/sources.list file. Once you have done that you can start up the synaptic package manager and you should see it in there.

rails bundle clean

If you're using RVM you may use rvm gemset empty for the current gemset - this command will remove all gems installed to the current gemset (gemset itself will stay in place). Then run bundle install in order to install actual versions of gems. Also be sure that you do not delete such general gems as rake, bundler and so on during rvm gemset empty (if it is the case then install them manually via gem install prior to bundle install).

Read binary file as string in Ruby

You can probably encode the tar file in Base64. Base 64 will give you a pure ASCII representation of the file that you can store in a plain text file. Then you can retrieve the tar file by decoding the text back.

You do something like:

require 'base64'

file_contents = Base64.encode64(tar_file_data)

Have look at the Base64 Rubydocs to get a better idea.

Titlecase all entries into a form_for text field

You don't want to take care of normalizing your data in a view - what if the user changes the data that gets submitted? Instead you could take care of it in the model using the before_save (or the before_validation) callback. Here's an example of the relevant code for a model like yours:

class Place < ActiveRecord::Base   before_save do |place| = =   end end 

You can also check out the Ruby on Rails guide for more info.

To answer you question more directly, something like this would work:

<%= f.text_field :city, :value => ( ? : '') %>   

This just means if exists, display the titlecase version of it, and if it doesn't display a blank string.

What Ruby IDE do you prefer?

NetBeans is good because you can use it on Windows and Mac OS X.

How to install PostgreSQL's pg gem on Ubuntu?

If you have libpq-dev installed and are still having this problem it is likely due to conflicting versions of OpenSSL's libssl and friends - the Ubuntu system version in /usr/lib (which libpq is built against) and a second version RVM installed in $HOME/.rvm/usr/lib (or /usr/local/rvm/usr/lib if it's a system install). You can verify this by temporarily renaming $HOME/.rvm/usr/lib and seeing if "gem install pg" works.

To solve the problem have rvm rebuild using the system OpenSSL libraries (you may need to manually remove libssl.* and libcrypto.* from the rvm/usr/lib dir):

rvm reinstall 1.9.3 --with-openssl-dir=/usr

This finally solved the problem for me on Ubunto 12.04.

How do I find the index of a character in a string in Ruby?


str.index('c') #=> 2 #String matching approach
str=~/c/ #=> 2 #Regexp approach 
$~ #=> #<MatchData "c">

Hope it helps. :)

Removing a model in rails (reverse of "rails g model Title...")

  1. To remove migration (if you already migrated the migration)

    rake db:migrate:down VERSION="20130417185845" #Your migration version
  2. To remove Model

    rails d model name  #name => Your model name

How to check if a value exists in an array in Ruby

This will tell you not only that it exists but also how many times it appears:

 a = ['Cat', 'Dog', 'Bird']
 #=> 1

SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed

A one liner fixes it for Windows in an Admin prompt

choco install wget (first see

wget -O C:\cacert.pem && setx /M SSL_CERT_FILE "C:\cacert.pem"

Or just do this:

gem sources -r
gem sources -a

Milanio's method:

gem sources -r
gem sources -a 
gem update --system
gem sources -r
gem sources -a

gem install [NAME_OF_GEM]

Error installing mysql2: Failed to build gem native extension

Got the "You have to install development tools first." error when trying to install the mysql2 gem after upgrading to Mac OS X Mountain Lion. Apparently doing this upgrade removes the command line compilers.

To fix:

  • I uninstalled my very old version of Xcode (ran the uninstall script in /Developer/Library). Then deleted the /Developer directory.
  • Went to the AppStore and downloaded Xcode.
  • Launched Xcode and went into the Preferences -> Downloads, and installed the command line tools.

How to "pretty" format JSON output in Ruby on Rails

Here's my solution which I derived from other posts during my own search.

This allows you to send the pp and jj output to a file as needed.

require "pp"
require "json"

class File
  def pp(*objs)
    objs.each {|obj|
      PP.pp(obj, self)
    objs.size <= 1 ? objs.first : objs
  def jj(*objs)
    objs.each {|obj|
      obj = JSON.parse(obj.to_json)
      self.puts JSON.pretty_generate(obj)
    objs.size <= 1 ? objs.first : objs

test_object = { :name => { first: "Christopher", last: "Mullins" }, :grades => [ "English" => "B+", "Algebra" => "A+" ] }

test_json_object = JSON.parse(test_object.to_json)"log/object_dump.txt", "w") do |file|
end"log/json_dump.txt", "w") do |file|

Ruby class instance variable vs. class variable

As others said, class variables are shared between a given class and its subclasses. Class instance variables belong to exactly one class; its subclasses are separate.

Why does this behavior exist? Well, everything in Ruby is an object—even classes. That means that each class has an object of the class Class (or rather, a subclass of Class) corresponding to it. (When you say class Foo, you're really declaring a constant Foo and assigning a class object to it.) And every Ruby object can have instance variables, so class objects can have instance variables, too.

The trouble is, instance variables on class objects don't really behave the way you usually want class variables to behave. You usually want a class variable defined in a superclass to be shared with its subclasses, but that's not how instance variables work—the subclass has its own class object, and that class object has its own instance variables. So they introduced separate class variables with the behavior you're more likely to want.

In other words, class instance variables are sort of an accident of Ruby's design. You probably shouldn't use them unless you specifically know they're what you're looking for.

How do I print out the contents of an object in Rails for easy debugging?

pp does the job too, no gem requiring is required.

@a = Accrual.first ; pp @a

 id: 4,
 year: 2018,
 Jan: #<BigDecimal:7ff521e58f08,'0.11E2',9(27)>,
 Feb: #<BigDecimal:7ff521e585d0,'0.88E2',9(27)>,
 Mar: #<BigDecimal:7ff521e58030,'0.0',9(27)>,
 Apr: #<BigDecimal:7ff521e53698,'0.88E2',9(27)>,
 May: #<BigDecimal:7ff521e52fb8,'0.8E1',9(27)>,
 June: #<BigDecimal:7ff521e52900,'0.8E1',9(27)>,
 July: #<BigDecimal:7ff521e51ff0,'0.8E1',9(27)>,
 Aug: #<BigDecimal:7ff521e51bb8,'0.88E2',9(27)>,
 Sep: #<BigDecimal:7ff521e512f8,'0.88E2',9(27)>,
 Oct: #<BigDecimal:7ff521e506c8,'0.0',9(27)>,
 Nov: #<BigDecimal:7ff521e43d38,'0.888E3',9(27)>,
 Dec: #<BigDecimal:7ff521e43478,'0.0',9(27)>,

You can also print two instances of an object:

 pp( Accrual.first , Accrual.second)

How to run Rake tasks from within Rake tasks?

task :build_all do
  [ :debug, :release ].each do |t|
    $build_type = t

Converting string from snake_case to CamelCase in Ruby

Benchmark for pure Ruby solutions

I took every possibilities I had in mind to do it with pure ruby code, here they are :

  • capitalize and gsub

  • split and map using & shorthand (thanks to user3869936’s answer)

  • split and map (thanks to Mr. Black’s answer)

    'app_user'.split('_').map{|e| e.capitalize}.join

And here is the Benchmark for all of these, we can see that gsub is quite bad for this. I used 126 080 words.

                              user     system      total        real
capitalize and gsub  :      0.360000   0.000000   0.360000 (  0.357472)
split and map, with &:      0.190000   0.000000   0.190000 (  0.189493)
split and map        :      0.170000   0.000000   0.170000 (  0.171859)

Converting camel case to underscore case in ruby

One-liner Ruby implementation:

class String
   # ruby mutation methods have the expectation to return self if a mutation occurred, nil otherwise. (see
   def to_underscore!

   def to_underscore
     dup.tap { |s| s.to_underscore! }

So "SomeCamelCase".to_underscore # =>"some_camel_case"

How to downgrade or install an older version of Cocoapods

Note that your pod specs will remain, and are located at ~/.cocoapods/ . This directory may also need to be removed if you want a completely fresh install.

They can be removed using pod spec remove SPEC_NAME then pod setup

It may help to do pod spec remove master then pod setup

Difference between map and collect in Ruby?

#collect is actually an alias for #map. That means the two methods can be used interchangeably, and effect the same behavior.

How to HTML encode/escape a string? Is there a built-in?

The h helper method:

<%=h "<p> will be preserved" %>

Uninstall all installed gems, in OSX?

When trying to remove gems installed as root, xargs seems to halt when it encounters an error trying to uninstall a default gem:

sudo gem list | cut -d" " -f1 | xargs gem uninstall -aIx
# ERROR:  While executing gem ... (Gem::InstallError)
#    gem "test-unit" cannot be uninstalled because it is a default gem

This won't work for everyone, but here's what I used instead:

sudo for gem (`gem list | cut -d" " -f1`); do gem uninstall $gem -aIx; done

How to extract URL parameters from a URL with Ruby or Rails?

I found myself needing the same thing for a recent project. Building on Levi's solution, here's a cleaner and faster method:

Rack::Utils.parse_nested_query 'param1=value1&param2=value2&param3=value3'
# => {"param1"=>"value1", "param2"=>"value2", "param3"=>"value3"}

Ruby 2.0.0p0 IRB warning: "DL is deprecated, please use Fiddle"

You may want to comment out the DL is deprecated, please use Fiddle warning at


since it’s annoying and you are not the irb/pry or some other gems code owner

How to convert a unix timestamp (seconds since epoch) to Ruby DateTime?

If you wanted just a Date, you can do Date.strptime(, '%s') where comes in the form of anFixnum and then converted to a String.

How to test if a string is basically an integer in quotes using Ruby

One liner in string.rb

def is_integer?; true if Integer(self) rescue false end

How do I use Ruby for shell scripting?

By default, you already have access to Dir and File, which are pretty useful by themselves.

Dir['*.rb'] #basic globs
Dir['**/*.rb'] #** == any depth of directory, including current dir.
#=> array of relative names

File.expand_path('~/file.txt') #=> "/User/mat/file.txt"
File.dirname('dir/file.txt') #=> 'dir'
File.basename('dir/file.txt') #=> 'file.txt'
File.join('a', 'bunch', 'of', 'strings') #=> 'a/bunch/of/strings'

__FILE__ #=> the name of the current file

Also useful from the stdlib is FileUtils

require 'fileutils' #I know, no underscore is not ruby-like
include FileUtils
# Gives you access (without prepending by 'FileUtils.') to
cd(dir, options)
cd(dir, options) {|dir| .... }
mkdir(dir, options)
mkdir(list, options)
mkdir_p(dir, options)
mkdir_p(list, options)
rmdir(dir, options)
rmdir(list, options)
ln(old, new, options)
ln(list, destdir, options)
ln_s(old, new, options)
ln_s(list, destdir, options)
ln_sf(src, dest, options)
cp(src, dest, options)
cp(list, dir, options)
cp_r(src, dest, options)
cp_r(list, dir, options)
mv(src, dest, options)
mv(list, dir, options)
rm(list, options)
rm_r(list, options)
rm_rf(list, options)
install(src, dest, mode = <src's>, options)
chmod(mode, list, options)
chmod_R(mode, list, options)
chown(user, group, list, options)
chown_R(user, group, list, options)
touch(list, options)

Which is pretty nice

Create a new Ruby on Rails application using MySQL instead of SQLite

If you are using rails 3 or greater version

rails new your_project_name -d mysql

if you have earlier version

rails new -d mysql your_project_name

So before you create your project you need to find the rails version. that you can find by

rails -v

How to avoid "cannot load such file -- utils/popen" from homebrew on OSX

To me it feels like you have missing header files for popen, which is a C system library.

Check if you have installed xcode successful with the command line tools and have accepted the license.

See this thread for more information: How to install Xcode Command Line Tools

How do I get elapsed time in milliseconds in Ruby?

Try subtracting the first from the second. Like so:

a =
puts - a # about 3.0

This gives you a floating-point number of the seconds between the two times (and with that, the milliseconds).

Installing Bootstrap 3 on Rails App

Using this branch will hopefully solve the problem:

gem 'twitter-bootstrap-rails',
  git: 'git://',
  branch: 'bootstrap3'

Is Ruby pass by reference or by value?

Lots of great answers diving into the theory of how Ruby's "pass-reference-by-value" works. But I learn and understand everything much better by example. Hopefully, this will be helpful.

def foo(bar)
  puts "bar (#{bar}) entering foo with object_id #{bar.object_id}"
  bar =  "reference"
  puts "bar (#{bar}) leaving foo with object_id #{bar.object_id}"

bar = "value"
puts "bar (#{bar}) before foo with object_id #{bar.object_id}"
puts "bar (#{bar}) after foo with object_id #{bar.object_id}"

# Output
bar (value) before foo with object_id 60
bar (value) entering foo with object_id 60
bar (reference) leaving foo with object_id 80 # <-----
bar (value) after foo with object_id 60 # <-----

As you can see when we entered the method, our bar was still pointing to the string "value". But then we assigned a string object "reference" to bar, which has a new object_id. In this case bar inside of foo, has a different scope, and whatever we passed inside the method, is no longer accessed by bar as we re-assigned it and point it to a new place in memory that holds String "reference".

Now consider this same method. The only difference is what with do inside the method

def foo(bar)
  puts "bar (#{bar}) entering foo with object_id #{bar.object_id}"
  bar.replace "reference"
  puts "bar (#{bar}) leaving foo with object_id #{bar.object_id}"

bar = "value"
puts "bar (#{bar}) before foo with object_id #{bar.object_id}"
puts "bar (#{bar}) after foo with object_id #{bar.object_id}"

# Output
bar (value) before foo with object_id 60
bar (value) entering foo with object_id 60
bar (reference) leaving foo with object_id 60 # <-----
bar (reference) after foo with object_id 60 # <-----

Notice the difference? What we did here was: we modified the contents of the String object, that variable was pointing to. The scope of bar is still different inside of the method.

So be careful how you treat the variable passed into methods. And if you modify passed-in variables-in-place (gsub!, replace, etc), then indicate so in the name of the method with a bang !, like so "def foo!"


It's important to keep in mind that the "bar"s inside and outside of foo, are "different" "bar". Their scope is different. Inside the method, you could rename "bar" to "club" and the result would be the same.

I often see variables re-used inside and outside of methods, and while it's fine, it takes away from the readability of the code and is a code smell IMHO. I highly recommend not to do what I did in my example above :) and rather do this

def foo(fiz)
  puts "fiz (#{fiz}) entering foo with object_id #{fiz.object_id}"
  fiz =  "reference"
  puts "fiz (#{fiz}) leaving foo with object_id #{fiz.object_id}"

bar = "value"
puts "bar (#{bar}) before foo with object_id #{bar.object_id}"
puts "bar (#{bar}) after foo with object_id #{bar.object_id}"

# Output
bar (value) before foo with object_id 60
fiz (value) entering foo with object_id 60
fiz (reference) leaving foo with object_id 80
bar (value) after foo with object_id 60

How to update Ruby Version 2.0.0 to the latest version in Mac OSX Yosemite?

I recommend rbenv*

* If this meets your criteria:

rbenv does…

  • Provide support for specifying application-specific Ruby versions.
  • Let you change the global Ruby version on a per-user basis.
  • Allow you to override the Ruby version with an environment variable.

In contrast with RVM, rbenv does not…

  • Need to be loaded into your shell. Instead, rbenv's shim approach works by adding a directory to your $PATH.
  • Override shell commands like cd or require prompt hacks. That's dangerous and error-prone.
  • Have a configuration file. There's nothing to configure except which version of Ruby you want to use.
  • Install Ruby. You can build and install Ruby yourself, or use ruby-build to automate the process.
  • Manage gemsets. Bundler is a better way to manage application dependencies. If you have projects that are not yet using Bundler you can install the rbenv-gemset plugin.
  • Require changes to Ruby libraries for compatibility. The simplicity of rbenv means as long as it's in your $PATH, nothing else needs to know about it.


Install Homebrew


$ brew update
$ brew install rbenv 
$ brew install rbenv ruby-build

# Add rbenv to bash so that it loads every time you open a terminal
echo 'if which rbenv > /dev/null; then eval "$(rbenv init -)"; fi' >> ~/.bash_profile
source ~/.bash_profile

There's one additional step after brew install rbenv Run rbenv init and add one line to .bash_profile as it states. After that reopen your terminal window […] SGI Sep 30 at 12:01 —

$ rbenv install --list
Available versions:
$ rbenv install 2.3.1

Set the global version:

$ rbenv global 2.3.1
$ ruby -v
ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-darwin15]

Set the local version of your repo by adding .ruby-version to your repo's root dir:

$ cd ~/whatevs/projects/new_repo
$ echo "2.3.1" > .ruby-version

For MacOS visit this link

How do you say not equal to in Ruby?

Yes. In Ruby the not equal to operator is:


You can get a full list of ruby operators here:

Difference between rake db:migrate db:reset and db:schema:load



  • rake db:migrate If you wanna make changes to the schema
  • rake db:reset If you wanna drop the database, reload the schema from schema.rb, and reseed the database
  • rake db:schema:load If you wanna reset database to schema as provided in schema.rb (This will delete all data)


rake db:schema:load will set up the schema as provided in schema.rb file. This is useful for a fresh install of app as it doesn't take as much time as db:migrate

Important note, db:schema:load will delete data on server.

rake db:migrate makes changes to the existing schema. Its like creating versions of schema. db:migrate will look in db/migrate/ for any ruby files and execute the migrations that aren't run yet starting with the oldest. Rails knows which file is the oldest by looking at the timestamp at the beginning of the migration filename. db:migrate comes with a benefit that data can also be put in the database. This is actually not a good practice. Its better to use rake db:seed to add data.

rake db:migrate provides tasks up, down etc which enables commands like rake db:rollback and makes it the most useful command.

rake db:reset does a db:drop and db:setup
It drops the database, create it again, loads the schema, and initializes with the seed data

Relevant part of the commands from databases.rake

namespace :schema do
  desc 'Creates a db/schema.rb file that is portable against any DB supported by Active Record'
  task :dump => [:environment, :load_config] do
    require 'active_record/schema_dumper'
    filename = ENV['SCHEMA'] || File.join(ActiveRecord::Tasks::DatabaseTasks.db_dir, 'schema.rb'), "w:utf-8") do |file|
      ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, file)

  desc 'Loads a schema.rb file into the database'
  task :load => [:environment, :load_config, :check_protected_environments] do
    ActiveRecord::Tasks::DatabaseTasks.load_schema_current(:ruby, ENV['SCHEMA'])

  # desc 'Drops and recreates the database from db/schema.rb for the current environment and loads the seeds.'
  task :reset => [ 'db:drop', 'db:setup' ]

namespace :migrate do
  # desc  'Rollbacks the database one migration and re migrate up (options: STEP=x, VERSION=x).'
  task :redo => [:environment, :load_config] do
    if ENV['VERSION']

Is there an opposite of include? for Ruby Arrays?

Use unless:

unless @players.include?( do

How can I find out the current route in Rails?

You can do request.env['REQUEST_URI'] to see the full requested URI.. it will output something like below


Replace words in a string - Ruby

First, you don't declare the type in Ruby, so you don't need the first string.

To replace a word in string, you do: sentence.gsub(/match/, "replacement").

Can't install gems on OS X "El Capitan"

I don't like to install stuff with sudo. once you start with sudo you can't stop..

try giving permissions to the Gems directory.

sudo chown -R $(whoami) /Library/Ruby/Gems/2.0.0

Why use Ruby's attr_accessor, attr_reader and attr_writer?

You may use the different accessors to communicate your intent to someone reading your code, and make it easier to write classes which will work correctly no matter how their public API is called.

class Person
  attr_accessor :age

Here, I can see that I may both read and write the age.

class Person
  attr_reader :age

Here, I can see that I may only read the age. Imagine that it is set by the constructor of this class and after that remains constant. If there were a mutator (writer) for age and the class were written assuming that age, once set, does not change, then a bug could result from code calling that mutator.

But what is happening behind the scenes?

If you write:

attr_writer :age

That gets translated into:

def age=(value)
  @age = value

If you write:

attr_reader :age

That gets translated into:

def age

If you write:

attr_accessor :age

That gets translated into:

def age=(value)
  @age = value

def age

Knowing that, here's another way to think about it: If you did not have the attr_... helpers, and had to write the accessors yourself, would you write any more accessors than your class needed? For example, if age only needed to be read, would you also write a method allowing it to be written?

What does %w(array) mean?

Though it's an old post, the question keep coming up and the answers don't always seem clear to me, so, here's my thoughts:

%w and %W are examples of General Delimited Input types, that relate to Arrays. There are other types that include %q, %Q, %r, %x and %i.

The difference between the upper and lower case version is that it gives us access to the features of single and double quotes. With single quotes and (lowercase) %w, we have no code interpolation (#{someCode}) and a limited range of escape characters that work (\\, \n). With double quotes and (uppercase) %W we do have access to these features.

The delimiter used can be any character, not just the open parenthesis. Play with the examples above to see that in effect.

For a full write up with examples of %w and the full list, escape characters and delimiters, have a look at "Ruby - %w vs %W – secrets revealed!"

Why do people say that Ruby is slow?

Joel on Software - Ruby Performance Revisited quite well explains it. Might be outdated though...

I would recommend to just stick with it as you're used to Ruby on Rails,
if you ever meet a performance issue you might reconsider to use a different language and framework.

In that case I would really suggest C# with ASP.NET MVC 2, works very well for CRUD apps.

How to convert a ruby hash object to JSON?

You can also use JSON.generate:

require 'json'

JSON.generate({ foo: "bar" })
=> "{\"foo\":\"bar\"}"

Or its alias, JSON.unparse:

require 'json'

JSON.unparse({ foo: "bar" })
=> "{\"foo\":\"bar\"}"

Transform DateTime into simple Date in Ruby on Rails

DateTime#to_date does exist with ActiveSupport:

$ irb
NoMethodError: undefined method 'to_date' for #<DateTime: -1/2,0,2299161>
    from (irb):1

>> require 'active_support/core_ext'
=> true

=> Mon, 01 Jan -4712

How can I find the number of days between two Date objects in Ruby?

This worked for me:

(endDate - beginDate).to_i

Is there a "do ... while" loop in Ruby?

Like this:

people = []

  info = gets.chomp
  people += [] if not info.empty?
end while not info.empty?

Reference: Ruby's Hidden do {} while () Loop

Rails formatting date

Try this:


It's a time formatting function which provides you a way to present the string representation of the date. (

From APIdock:

%Y%m%d           => 20071119                  Calendar date (basic)
%F               => 2007-11-19                Calendar date (extended)
%Y-%m            => 2007-11                   Calendar date, reduced accuracy, specific month
%Y               => 2007                      Calendar date, reduced accuracy, specific year
%C               => 20                        Calendar date, reduced accuracy, specific century
%Y%j             => 2007323                   Ordinal date (basic)
%Y-%j            => 2007-323                  Ordinal date (extended)
%GW%V%u          => 2007W471                  Week date (basic)
%G-W%V-%u        => 2007-W47-1                Week date (extended)
%GW%V            => 2007W47                   Week date, reduced accuracy, specific week (basic)
%G-W%V           => 2007-W47                  Week date, reduced accuracy, specific week (extended)
%H%M%S           => 083748                    Local time (basic)
%T               => 08:37:48                  Local time (extended)
%H%M             => 0837                      Local time, reduced accuracy, specific minute (basic)
%H:%M            => 08:37                     Local time, reduced accuracy, specific minute (extended)
%H               => 08                        Local time, reduced accuracy, specific hour
%H%M%S,%L        => 083748,000                Local time with decimal fraction, comma as decimal sign (basic)
%T,%L            => 08:37:48,000              Local time with decimal fraction, comma as decimal sign (extended)
%H%M%S.%L        => 083748.000                Local time with decimal fraction, full stop as decimal sign (basic)
%T.%L            => 08:37:48.000              Local time with decimal fraction, full stop as decimal sign (extended)
%H%M%S%z         => 083748-0600               Local time and the difference from UTC (basic)
%T%:z            => 08:37:48-06:00            Local time and the difference from UTC (extended)
%Y%m%dT%H%M%S%z  => 20071119T083748-0600      Date and time of day for calendar date (basic)
%FT%T%:z         => 2007-11-19T08:37:48-06:00 Date and time of day for calendar date (extended)
%Y%jT%H%M%S%z    => 2007323T083748-0600       Date and time of day for ordinal date (basic)
%Y-%jT%T%:z      => 2007-323T08:37:48-06:00   Date and time of day for ordinal date (extended)
%GW%V%uT%H%M%S%z => 2007W471T083748-0600      Date and time of day for week date (basic)
%G-W%V-%uT%T%:z  => 2007-W47-1T08:37:48-06:00 Date and time of day for week date (extended)
%Y%m%dT%H%M      => 20071119T0837             Calendar date and local time (basic)
%FT%R            => 2007-11-19T08:37          Calendar date and local time (extended)
%Y%jT%H%MZ       => 2007323T0837Z             Ordinal date and UTC of day (basic)
%Y-%jT%RZ        => 2007-323T08:37Z           Ordinal date and UTC of day (extended)
%GW%V%uT%H%M%z   => 2007W471T0837-0600        Week date and local time and difference from UTC (basic)
%G-W%V-%uT%R%:z  => 2007-W47-1T08:37-06:00    Week date and local time and difference from UTC (extended)

How do I search within an array of hashes by hash values in ruby?

You're looking for Enumerable#select (also called find_all): {|father| father["age"] > 35 }
# => [ { "age" => 40, "father" => "Bob" },
#      { "age" => 50, "father" => "Batman" } ]

Per the documentation, it "returns an array containing all elements of [the enumerable, in this case @fathers] for which block is not false."

How to run Ruby code from terminal?

If Ruby is installed, then

ruby yourfile.rb

where yourfile.rb is the file containing the ruby code.



to start the interactive Ruby environment, where you can type lines of code and see the results immediately.

Use YAML with variables

Rails / ruby frameworks are able to do some templating ... it's frequently used to load env variables ...

# fooz.yml
    bar: <%= $ENV[:some_var] %>

No idea if this works for javascript frameworks as I think that YML format is superset of json and it depends on what reads the yml file for you.

If you can use the template like that or the << >> or the {{ }} styles depending on your reader, after that you just ...

In another yml file ...

# boo.yml

  fooz: foo

Which allows you to basically insert a variable as your reference that original file each time which is dynamically set. When reading I was also seeing you can create or open YML files as objects on the fly for several languages which allows you to create a file & chain write a series of YML files or just have them all statically pointing to the dynamically created one.

Given a class, see if instance has method (Ruby)

While respond_to? will return true only for public methods, checking for "method definition" on a class may also pertain to private methods.

On Ruby v2.0+ checking both public and private sets can be achieved with

Foo.private_instance_methods.include?(:bar) || Foo.instance_methods.include?(:bar)

How to convert a string or integer to binary in Ruby?

If you are looking for a Ruby class/method I used this, and I have also included the tests:

class Binary
  def self.binary_to_decimal(binary)
    binary_array =
    total = 0

    binary_array.each_with_index do |n, i|
      total += 2 ** (binary_array.length-i-1) * n

class BinaryTest < Test::Unit::TestCase
  def test_1
   test1 = Binary.binary_to_decimal(0001)
   assert_equal 1, test1

 def test_8
    test8 = Binary.binary_to_decimal(1000)
    assert_equal 8, test8

 def test_15
    test15 = Binary.binary_to_decimal(1111)
    assert_equal 15, test15

 def test_12341
    test12341 = Binary.binary_to_decimal(11000000110101)
    assert_equal 12341, test12341

How to ignore a particular directory or file for tslint?

I had to use the **/* syntax to exclude the files in a folder:

    "linterOptions": {
        "exclude": [

What's the best way to test SQL Server connection programmatically?

Look for an open listener on port 1433 (the default port). If you get any response after creating a tcp connection there, the server's probably up.

How to use Monitor (DDMS) tool to debug application

I think things (location) have changed little bit. For: Android Studio Build @AI-141.1903250 - built on May 5, 2015

Franco Rondinis answer should be

To track memory allocation of objects:

  1. Start your app as described in Run Your App in Debug Mode.
  2. Click Android to open the Android DDMS tool window.
  3. Select your device from the dropdown list.
  4. Select your app by its package name from the list of running apps.
  5. On the Android DDMS tool window, select Memory tab.
  6. Click Start Allocation Tracking Interact with your app on the device. Click Stop Allocation Tracking (same icon)

how to start allocation tracking in android studio

How to disable copy/paste from/to EditText

You may try android:focusableInTouchMode="false".

create table with sequence.nextval in oracle

You can use Oracle's SQL Developer tool to do that (My Oracle DB version is 11). While creating a table choose Advanced option and click on the Identity Column tab at the bottom and from there choose Column Sequence. This will generate a AUTO_INCREMENT column (Corresponding Trigger and Squence) for you.

Check if PHP session has already started

Replace session_start(); with:

if (!isset($a)) {
    a = False;
    if ($a == TRUE) {
        $a = TRUE;

MySQL: update a field only if condition is met


Here you have another example:

UPDATE prices
SET final_price= CASE
   WHEN currency=1 THEN 0.81*final_price
   ELSE final_price

This works because MySQL doesn't update the row, if there is no change, as mentioned in docs:

If you set a column to the value it currently has, MySQL notices this and does not update it.

How can I add a PHP page to WordPress?

You will want to take a look in to WordPress' plugin API.

This explains how to "hook" and "filter" in to different parts of the WordPress mechanics, so you can execute custom PHP code pretty much anywhere at any given time. This hooking, filtering, and custom code authoring can all take place in your functions.php file in any of your themes. Happy coding :)

Django: Calling .update() on a single model instance retrieved by .get()?

As @Nils mentionned, you can use the update_fields keyword argument of the save() method to manually specify the fields to update.

obj_instance = Model.objects.get(field=value)
obj_instance.field = new_value
obj_instance.field2 = new_value2['field', 'field2'])

The update_fields value should be a list of the fields to update as strings.


How to check if variable is array?... or something array-like

PHP 7.1.0 has introduced the iterable pseudo-type and the is_iterable() function, which is specially designed for such a purpose:

This […] proposes a new iterable pseudo-type. This type is analogous to callable, accepting multiple types instead of one single type.

iterable accepts any array or object implementing Traversable. Both of these types are iterable using foreach and can be used with yield from within a generator.

function foo(iterable $iterable) {
    foreach ($iterable as $value) {
        // ...

This […] also adds a function is_iterable() that returns a boolean: true if a value is iterable and will be accepted by the iterable pseudo-type, false for other values.

var_dump(is_iterable([1, 2, 3])); // bool(true)
var_dump(is_iterable(new ArrayIterator([1, 2, 3]))); // bool(true)
var_dump(is_iterable((function () { yield 1; })())); // bool(true)
var_dump(is_iterable(1)); // bool(false)
var_dump(is_iterable(new stdClass())); // bool(false)

You can also use the function is_array($var) to check if the passed variable is an array:

    var_dump( is_array(array()) ); // true
    var_dump( is_array(array(1, 2, 3)) ); // true
    var_dump( is_array($_SERVER) ); // true

Read more in How to check if a variable is an array in PHP?

"Gradle Version 2.10 is required." Error

Go to File -> Settings -> Build, Execution, Deployment -> Gradle -> choose Use default gradle wrapper

Math.random() explanation

The Random class of Java located in the java.util package will serve your purpose better. It has some nextInt() methods that return an integer. The one taking an int argument will generate a number between 0 and that int, the latter not inclusive.

How to install wkhtmltopdf on a linux based (shared hosting) web server

Shared hosting no ssh or shell access?

Here is how i did it;

  1. Visit and download the appropriate stable release for Linux. For my case I chose 32-bit which is wkhtmltox-0.12.4_linux-generic-i386.tar.xz
  2. Unzip to a folder on your local drive.
  3. Upload the folder to public_html (or whichever location fits your need) using an FTP program just like any other file(s)
  4. Change the binary paths in snappy.php file to point the appropriate files in the folder you just uploaded. Bingo! there you have it. You should be able to generate PDF files.

How can I see the specific value of the sql_mode?

You need to login to your mysql terminal first using mysql -u username -p password

Then use this:

SELECT @@sql_mode; or SELECT @@GLOBAL.sql_mode;

output will be like this:


You can also set sql mode by this:


No shadow by default on Toolbar?

In my situation elevation doesn't work well because I haven't given any background to the toolbar. Try giving background color to the toolbar then set elevation and it will work well.

how to insert value into DataGridView Cell?

You can access any DGV cell as follows :

dataGridView1.Rows[rowIndex].Cells[columnIndex].Value = value;

But usually it's better to use databinding : you bind the DGV to a data source (DataTable, collection...) through the DataSource property, and only work on the data source itself. The DataGridView will automatically reflect the changes, and changes made on the DataGridView will be reflected on the data source

How do I remove documents using Node.js Mongoose?

Be careful with findOne and remove!

  User.findOne({name: 'Alice'}).remove().exec();

The code above removes ALL users named 'Alice' instead of the first one only.

By the way, I prefer to remove documents like this:


Or provide a callback and omit the exec()

  User.remove({...}, callback);

define a List like List<int,string>?

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

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

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

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

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

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

Check whether specific radio button is checked

WHy bother with all of the fancy selectors? If you're using those id="" attributes properly, then 'test2' must be the only tag with that id on the page, then the .checked boolean property will tell you if it's checked or not:

if ($('test2').checked) {

You've also not set any values for those radio buttons, so no matter which button you select, you'll just get a blank "testGroup=" submitted to the server.

How to declare an array of objects in C#

The reason this is happening is because initializing an array does not initialize each element in that array. You need to first set houses[0] = new GameObject() and then it will work.

expected assignment or function call: no-unused-expressions ReactJS

Instead of

    <h1>The Score is {this.state.speed};</h1>

Use Below Code

     <h1>The Score is {this.state.speed};</h1>

Basically use brace "(" in the same line of return like "return(". It will fix this issue. Thanks.

How exactly do you configure httpOnlyCookies in ASP.NET?

If you want to do it in code, use the System.Web.HttpCookie.HttpOnly property.

This is directly from the MSDN docs:

// Create a new HttpCookie.
HttpCookie myHttpCookie = new HttpCookie("LastVisit", DateTime.Now.ToString());
// By default, the HttpOnly property is set to false 
// unless specified otherwise in configuration.
myHttpCookie.Name = "MyHttpCookie";
// Show the name of the cookie.
// Create an HttpOnly cookie.
HttpCookie myHttpOnlyCookie = new HttpCookie("LastVisit", DateTime.Now.ToString());
// Setting the HttpOnly value to true, makes
// this cookie accessible only to ASP.NET.
myHttpOnlyCookie.HttpOnly = true;
myHttpOnlyCookie.Name = "MyHttpOnlyCookie";
// Show the name of the HttpOnly cookie.

Doing it in code allows you to selectively choose which cookies are HttpOnly and which are not.

Android Studio - Gradle sync project failed

After applying this fix that was found here...

in file $SDK/ndk_bundle/ replace "12.0.2753695 beta 1" to "12.0.2753695-beta1"

My project was built successfully and ran on device and emulators although 5 warnings still remains.

Ansible: copy a directory content to another directory

the ansible doc is quite clear for parameter src it says the following:

Local path to a file to copy to the remote server.
This can be absolute or relative.
If path is a directory, it is copied recursively. In this case, if path ends with "/", 
only inside contents of that directory are copied to destination. Otherwise, if it 
does not end with "/", the directory itself with all contents is copied. This behavior 
is similar to the rsync command line tool.

So what you need is skip the / at the end of your src path.

- name: copy html file
  copy: src=/home/vagrant/dist dest=/usr/share/nginx/html/

How to edit my Excel dropdown list?

Attribute_Brands is a named range that should contain your list items. Use the drop down to the left of the formula bar to jump to the named range, then edit it. If you add or remove items you will need to adjust the range the named range covers.

How to convert an ASCII character into an int in C

Are you searching for this:

int c = some_ascii_character;

Or just converting without assignment:


Reset local repository branch to be just like remote repository HEAD

Provided that the remote repository is origin, and that you're interested in branch_name:

git fetch origin
git reset --hard origin/<branch_name>

Also, you go for reset the current branch of origin to HEAD.

git fetch origin
git reset --hard origin/HEAD

How it works:

git fetch origin downloads the latest from remote without trying to merge or rebase anything.

Then the git reset resets the <branch_name> branch to what you just fetched. The --hard option changes all the files in your working tree to match the files in origin/branch_name.

SQL Server - Case Statement

We can use case statement Like this

select Name,EmailId,gender=case 
when gender='M' then 'F'
when gender='F' then 'M'
 from [dbo].[Employees]

WE can also it as follow.

select Name,EmailId,case gender
when 'M' then 'F'
when 'F' then 'M'
 from [dbo].[Employees]

Twitter Bootstrap Multilevel Dropdown Menu

Updated Answer

* Updated answer which support the v2.1.1** bootstrap version stylesheet.

**But be careful because this solution has been removed from v3

Just wanted to point out that this solution is not needed anymore as the latest bootstrap now supports multi-level dropdowns by default. You can still use it if you're on older versions but for those who updated to the latest (v2.1.1 at the time of writing) it is not needed anymore. Here is a fiddle with the updated default multi-level dropdown straight from the documentation:

Original Answer

There have been some issues raised on submenu support over at github and they are usually closed by the bootstrap developers, such as this one, so i think it is left to the developers using the bootstrap to work something out. Here is a demo i put together showing you how you can hack together a working sub-menu.

Relevant code


.dropdown-menu .sub-menu {
    left: 100%;
    position: absolute;
    top: 0;
    visibility: hidden;
    margin-top: -1px;

.dropdown-menu li:hover .sub-menu {
    visibility: visible;
    display: block;

.navbar .sub-menu:before {
    border-bottom: 7px solid transparent;
    border-left: none;
    border-right: 7px solid rgba(0, 0, 0, 0.2);
    border-top: 7px solid transparent;
    left: -7px;
    top: 10px;
.navbar .sub-menu:after {
    border-top: 6px solid transparent;
    border-left: none;
    border-right: 6px solid #fff;
    border-bottom: 6px solid transparent;
    left: 10px;
    top: 11px;
    left: -6px;

Created my own .sub-menu class to apply to the 2-level drop down menus, this way we can position them next to our menu items. Also modified the arrow to display it on the left of the submenu group.


"break;" out of "if" statement?

This is actually the conventional use of the break statement. If the break statement wasn't nested in an if block the for loop could only ever execute one time.

MSDN lists this as their example for the break statement.

How to change color in circular progress bar?

To supplement Muhamed Riyas M's top voted answer:

Faster rotation


Thinner ring


Light white


How to compare binary files to check if they are the same?

Use cmp command. This will either exit cleanly if they are binary equal, or it will print out where the first difference occurs and exit.

Mac install and open mysql using terminal

In MacOS, Mysql's executable file is located in /usr/local/mysql/bin/mysql and you can easily login to it with the following command:

/usr/local/mysql/bin/mysql -u USERNAME -p

But this is a very long command and very boring, so you can add mysql path to Os's Environment variable and access to it much easier.

For macOS Catalina and later

Starting with macOS Catalina, Mac devices use zsh as the default login shell and interactive shell and you have to update .zprofile file in your home directory.

echo 'export PATH="$PATH:/usr/local/mysql/bin"' >> ~/.zprofile
source ~/.zprofile
mysql -u USERNAME -p

For macOS Mojave and earlier

Although you can always switch to zsh, bash is the default shell in macOS Mojave and earlier and with bash you have to update .bash_profile file.

echo 'export PATH="$PATH:/usr/local/mysql/bin"' >> ~/.bash_profile
source ~/.bash_profile
mysql -u USERNAME -p

How do I open phone settings when a button is clicked?

in ios10/ Xcode 8 in simulator:




does not.

Escape invalid XML characters in C#

The RemoveInvalidXmlChars method provided by Irishman does not support surrogate characters. To test it, use the following example:

static void Main()
    const string content = "\v\U00010330";

    string newContent = RemoveInvalidXmlChars(content);


This returns an empty string but it shouldn't! It should return "\U00010330" because the character U+10330 is a valid XML character.

To support surrogate characters, I suggest using the following method:

public static string RemoveInvalidXmlChars(string text)
    if (string.IsNullOrEmpty(text))
        return text;

    int length = text.Length;
    StringBuilder stringBuilder = new StringBuilder(length);

    for (int i = 0; i < length; ++i)
        if (XmlConvert.IsXmlChar(text[i]))
        else if (i + 1 < length && XmlConvert.IsXmlSurrogatePair(text[i + 1], text[i]))
            stringBuilder.Append(text[i + 1]);

    return stringBuilder.ToString();

Change value of input onchange?

You can't access your fieldname as a global variable. Use document.getElementById:

function updateInput(ish){
    document.getElementById("fieldname").value = ish;



Check cell for a specific letter or set of letters

Just use = IF(A1="Bla*","YES","NO"). When you insert the asterisk, it acts as a wild card for any amount of characters after the specified text.

GIT: Checkout to a specific folder

I'm using this alias for checking out a branch in a temporary directory:

    cot = "!TEMP=$(mktemp -d); f() { git worktree prune && git worktree add $TEMP $1 && zsh -c \"cd $TEMP; zsh\";}; f" # checkout branch in temporary directory


git cot mybranch

You are then dropped in a new shell in the temporary directory where you can work on the branch. You can even use git commands in this directory.

When you're done, delete the directory and run:

git worktree prune

This is also done automatically in the alias, before adding a new worktree.

Is it possible to implement a Python for range loop without an iterator variable?

Off the top of my head, no.

I think the best you could do is something like this:

def loop(f,n):
    for i in xrange(n): f()

loop(lambda: <insert expression here>, 5)

But I think you can just live with the extra i variable.

Here is the option to use the _ variable, which in reality, is just another variable.

for _ in range(n):

Note that _ is assigned the last result that returned in an interactive python session:

>>> 1+2
>>> _

For this reason, I would not use it in this manner. I am unaware of any idiom as mentioned by Ryan. It can mess up your interpreter.

>>> for _ in xrange(10): pass
>>> _
>>> 1+2
>>> _

And according to Python grammar, it is an acceptable variable name:

identifier ::= (letter|"_") (letter | digit | "_")*

Loading state button in Bootstrap 3

You need to detect the click from js side, your HTML remaining same. Note: this method is deprecated since v3.5.5 and removed in v4.

$("button").click(function() {
    var $btn = $(this);
    // simulating a timeout
    setTimeout(function () {
    }, 1000);

Also, don't forget to load jQuery and Bootstrap js (based on jQuery) file in your page.


Official Documentation

How to convert a std::string to const char* or char*?

Use the .c_str() method for const char *.

You can use &mystring[0] to get a char * pointer, but there are a couple of gotcha's: you won't necessarily get a zero terminated string, and you won't be able to change the string's size. You especially have to be careful not to add characters past the end of the string or you'll get a buffer overrun (and probable crash).

There was no guarantee that all of the characters would be part of the same contiguous buffer until C++11, but in practice all known implementations of std::string worked that way anyway; see Does “&s[0]” point to contiguous characters in a std::string?.

Note that many string member functions will reallocate the internal buffer and invalidate any pointers you might have saved. Best to use them immediately and then discard.

Can I do Model->where('id', ARRAY) multiple where conditions?

There's whereIn():

$items = DB::table('items')->whereIn('id', [1, 2, 3])->get();

Converting Chart.js canvas chart to image using .toDataUrl() results in blank image

You can access afterRender hook by using plugins.

And here are all the plugin api available.

In html file:

  <canvas id="myChart"></canvas>
  <div id="imgWrap"></div>

In js file:

var chart = new Chart(ctx, {
  plugins: [{
    afterRender: function () {
      // Do anything you want

const renderIntoImage = () => {
  const canvas = document.getElementById('myChart')
  const imgWrap = document.getElementById('imgWrap')
  var img = new Image();
  img.src = canvas.toDataURL()
  imgWrap.appendChild(img) = 'none'

Converting string into datetime

See my answer.

In real-world data this is a real problem: multiple, mismatched, incomplete, inconsistent and multilanguage/region date formats, often mixed freely in one dataset. It's not ok for production code to fail, let alone go exception-happy like a fox.

We need to try...catch multiple datetime formats fmt1,fmt2,...,fmtn and suppress/handle the exceptions (from strptime()) for all those that mismatch (and in particular, avoid needing a yukky n-deep indented ladder of try..catch clauses). From my solution

def try_strptime(s, fmts=['%d-%b-%y','%m/%d/%Y']):
    for fmt in fmts:
            return datetime.strptime(s, fmt)

    return None # or reraise the ValueError if no format matched, if you prefer

How can you search Google Programmatically Java API

Google TOS have been relaxed a bit in April 2014. Now it states:

"Don’t misuse our Services. For example, don’t interfere with our Services or try to access them using a method other than the interface and the instructions that we provide."

So the passage about "automated means" and scripts is gone now. It evidently still is not the desired (by google) way of accessing their services, but I think it is now formally open to interpretation of what exactly an "interface" is and whether it makes any difference as of how exactly returned HTML is processed (rendered or parsed). Anyhow, I have written a Java convenience library and it is up to you to decide whether to use it or not:

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

Following is the solution which worked for me. The files which I updated are as follows:

  1. config.xml (Full Path: /config.xml)
  2. network_security_config.xml (Full Path: /resources/android/xml/network_security_config.xml)

Changes in the corresponding files are as follows:

1. config.xml

I have added <application android:usesCleartextTraffic="true" /> tag within <edit-config> tag in the config.xml file

<platform name="android">
    <edit-config file="app/src/main/AndroidManifest.xml" mode="merge" target="/manifest/application" xmlns:android="">
        <application android:usesCleartextTraffic="true" />
        <application android:networkSecurityConfig="@xml/network_security_config" />
<platform name="android">

2. network_security_config.xml

In this file I have added 2 <domain> tag within <domain-config> tag, the main domain and a sub domain as per my project requirement

<?xml version="1.0" encoding="utf-8"?>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true"></domain>
        <domain includeSubdomains="true"></domain>

Thanks @Ashutosh for the providing the help.

Hope it helps.

How can I change NULL to 0 when getting a single value from a SQL function?

You can use ISNULL().

SELECT ISNULL(SUM(Price), 0) AS TotalPrice 
FROM Inventory
WHERE (DateAdded BETWEEN @StartDate AND @EndDate)

That should do the trick.

C# getting its own class name

this can be omitted. All you need to get the current class name is:

GetType().Name vs PHP (What to choose)

There are a couple of topics that might provide you with an answer. You could also run some tests yourself. Doesn't see too hard to get some loops started and adding a timer to calculate the execution time ;-)

python "TypeError: 'numpy.float64' object cannot be interpreted as an integer"

for j in range(N[i]/2):

N[i]/2 will be a float64 but range() expects an integer. Just cast the call to

for j in range(int(N[i]/2)):

What do the result codes in SVN mean?

Also note that a result code in the second column refers to the properties of the file. For example:

U   filename.1
 U  filename.2  
UU  filename.3

filename.1: the file was updated
filename.2: a property or properties on the file (such as svn:keywords) was updated
filename.3: both the file and its properties were updated

Rewrite left outer join involving multiple tables from Informix to Oracle

Write one table per join, like this:

select tab1.a,tab2.b,tab3.c,tab4.d 
  table1 tab1
  inner join table2 tab2 on tab2.fg = tab1.fg
  left join table3 tab3 on = and tab3.desc = "XYZ"
  left join table4 tab4 on tab4.xya = tab3.xya and =
  left join table5 tab5 on tab5.dd = tab3.dd and tab5.kk = tab4.kk

Note that while my query contains actual left join, your query apparently doesn't. Since the conditions are in the where, your query should behave like inner joins. (Although I admit I don't know Informix, so maybe I'm wrong there).

The specfific Informix extension used in the question works a bit differently with regards to left joins. Apart from the exact syntax of the join itself, this is mainly in the fact that in Informix, you can specify a list of outer joined tables. These will be left outer joined, and the join conditions can be put in the where clause. Note that this is a specific extension to SQL. Informix also supports 'normal' left joins, but you can't combine the two in one query, it seems.

In Oracle this extension doesn't exist, and you can't put outer join conditions in the where clause, since the conditions will be executed regardless.

So look what happens when you move conditions to the where clause:

select tab1.a,tab2.b,tab3.c,tab4.d 
  table1 tab1
  inner join table2 tab2 on tab2.fg = tab1.fg
  left join table3 tab3 on =
  left join table4 tab4 on tab4.xya = tab3.xya
  left join table5 tab5 on tab5.dd = tab3.dd and tab5.kk = tab4.kk
  tab3.desc = "XYZ" and =

Now, only rows will be returned for which those two conditions are true. They cannot be true when no row is found, so if there is no matching row in table3 and/or table4, or if ss is null in either of the two, one of these conditions is going to return false, and no row is returned. This effectively changed your outer join to an inner join, and as such changes the behavior significantly.

PS: left join and left outer join are the same. It means that you optionally join the second table to the first (the left one). Rows are returned if there is only data in the 'left' part of the join. In Oracle you can also right [outer] join to make not the left, but the right table the leading table. And there is and even full [outer] join to return a row if there is data in either table.

Solving Quadratic Equation

# syntaxis:2.7
# solution for quadratic equation
# a*x**2 + b*x + c = 0

d = b**2-4*a*c # discriminant

if d < 0:
    print 'No solutions'
elif d == 0:
    x1 = -b / (2*a)
    print 'The sole solution is',x1
else: # if d > 0
    x1 = (-b + math.sqrt(d)) / (2*a)
    x2 = (-b - math.sqrt(d)) / (2*a)
    print 'Solutions are',x1,'and',x2

Trim specific character from a string

String.prototype.TrimStart = function (n) {
    if (this.charAt(0) == n)
        return this.substr(1);

String.prototype.TrimEnd = function (n) {
    if (this.slice(-1) == n)
        return this.slice(0, -1);

How to read data when some numbers contain commas as thousand separator?

We can also use readr::parse_number, the columns must be characters though. If we want to apply it for multiple columns we can loop through columns using lapply

df[2:3] <- lapply(df[2:3], readr::parse_number)

#  a        b        c
#1 a    12234       12
#2 b      123  1234123
#3 c     1234     1234
#4 d 13456234    15342
#5 e    12312 12334512

Or use mutate_at from dplyr to apply it to specific variables.

df %>% mutate_at(2:3, readr::parse_number)
df %>% mutate_at(vars(b:c), readr::parse_number)


df <- data.frame(a = letters[1:5], 
                 b = c("12,234", "123", "1,234", "13,456,234", "123,12"),
                 c = c("12", "1,234,123","1234", "15,342", "123,345,12"), 
                 stringsAsFactors = FALSE)

Is it possible to program iPhone in C++

First off, saying Objective-C is "insane" is humorous- I have the Bjarne Stroustrup C++ book sitting by my side which clocks in at 1020 pages. Apple's PDF on Objective-C is 141.

If you want to use UIKit it will be very, very difficult for you to do anything in C++. Any serious iPhone app that conforms to Apple's UI will need it's UI portions to be written in Objective-C. Only if you're writing an OpenGL game can you stick almost entirely to C/C++.

RE error: illegal byte sequence on Mac OS X

Add the following lines to your ~/.bash_profile or ~/.zshrc file(s).

export LC_CTYPE=C 
export LANG=C

Is there a typescript List<> and/or Map<> class/library?

It's very easy to write that yourself, and that way you have more control over things.. As the other answers say, TypeScript is not aimed at adding runtime types or functionality.


class Map<T> {
    private items: { [key: string]: T };

    constructor() {
        this.items = {};

    add(key: string, value: T): void {
        this.items[key] = value;

    has(key: string): boolean {
        return key in this.items;

    get(key: string): T {
        return this.items[key];


class List<T> {
    private items: Array<T>;

    constructor() {
        this.items = [];

    size(): number {
        return this.items.length;

    add(value: T): void {

    get(index: number): T {
        return this.items[index];

I haven't tested (or even tried to compile) this code, but it should give you a starting point.. you can of course then change what ever you want and add the functionality that YOU need...

As for your "special needs" from the List, I see no reason why to implement a linked list, since the javascript array lets you add and remove items.
Here's a modified version of the List to handle the get prev/next from the element itself:

class ListItem<T> {
    private list: List<T>;
    private index: number;

    public value: T;

    constructor(list: List<T>, value: T, index: number) {
        this.list = list;
        this.index = index;
        this.value = value;

    prev(): ListItem<T> {
        return this.list.get(this.index - 1);

    next(): ListItem<T> {
        return this.list.get(this.index + 1);   

class List<T> {
    private items: Array<ListItem<T>>;

    constructor() {
        this.items = [];

    size(): number {
        return this.items.length;

    add(value: T): void {
        this.items.push(new ListItem<T>(this, value, this.size()));

    get(index: number): ListItem<T> {
        return this.items[index];

Here too you're looking at untested code..

Hope this helps.

Edit - as this answer still gets some attention

Javascript has a native Map object so there's no need to create your own:

let map = new Map();
map.set("key1", "value1");
console.log(map.get("key1")); // value1

How can I get the username of the logged-in user in Django?

'request.user' has the logged in user.
'request.user.username' will return username of logged in user.

How to create an HTTPS server in Node.js?

  1. Download rar file for openssl set up from here:
  2. Just copy your folder in c drive.
  3. Create openssl.cnf file and download their content from : openssl.cnf can be put any where but path shoud be correct when we give in command prompt.
  4. Open command propmt and set openssl.cnf path C:\set OPENSSL_CONF=d:/openssl.cnf 5.Run this in cmd : C:\openssl-0.9.8r-i386-win32-rev2>openssl.exe
  5. Then Run OpenSSL> genrsa -des3 -out server.enc.key 1024
  6. Then it will ask for pass phrases : enter 4 to 11 character as your password for certificate
  7. Then run this Openssl>req -new -key server.enc.key -out server.csr
  8. Then it will ask for some details like country code state name etc. fill it freely. 10 . Then Run Openssl > rsa -in server.enc.key -out server.key
  9. Run this OpenSSL> x509 -req -days 365 -in server.csr -signkey server.key -out server.crt then use previous code that are on stack overflow Thanks

How to use Console.WriteLine in ASP.NET (C#) during debug?

If for whatever reason you'd like to catch the output of Console.WriteLine, you CAN do this:

protected void Application_Start(object sender, EventArgs e)
    var writer = new LogWriter();

public class LogWriter : TextWriter
    public override void WriteLine(string value)
        //do whatever with value

    public override Encoding Encoding
        get { return Encoding.Default; }

What could cause an error related to npm not being able to find a file? No contents in my node_modules subfolder. Why is that?

Try the following steps:
1. Make sure you have the latest npm (npm install -g npm).
2. Add an exception to your antivirus to ignore the node_modules folder in your project.
3. $ rm -rf node_modules package-lock.json .
4. $ npm install

Python: Finding differences between elements of a list

You can use itertools.tee and zip to efficiently build the result:

from itertools import tee
# python2 only:
#from itertools import izip as zip

def differences(seq):
    iterable, copied = tee(seq)
    for x, y in zip(iterable, copied):
        yield y - x

Or using itertools.islice instead:

from itertools import islice

def differences(seq):
    nexts = islice(seq, 1, None)
    for x, y in zip(seq, nexts):
        yield y - x

You can also avoid using the itertools module:

def differences(seq):
    iterable = iter(seq)
    prev = next(iterable)
    for element in iterable:
        yield element - prev
        prev = element

All these solution work in constant space if you don't need to store all the results and support infinite iterables.

Here are some micro-benchmarks of the solutions:

In [12]: L = range(10**6)

In [13]: from collections import deque
In [15]: %timeit deque(differences_tee(L), maxlen=0)
10 loops, best of 3: 122 ms per loop

In [16]: %timeit deque(differences_islice(L), maxlen=0)
10 loops, best of 3: 127 ms per loop

In [17]: %timeit deque(differences_no_it(L), maxlen=0)
10 loops, best of 3: 89.9 ms per loop

And the other proposed solutions:

In [18]: %timeit [x[1] - x[0] for x in zip(L[1:], L)]
10 loops, best of 3: 163 ms per loop

In [19]: %timeit [L[i+1]-L[i] for i in range(len(L)-1)]
1 loops, best of 3: 395 ms per loop

In [20]: import numpy as np

In [21]: %timeit np.diff(L)
1 loops, best of 3: 479 ms per loop

In [35]: %%timeit
    ...: res = []
    ...: for i in range(len(L) - 1):
    ...:     res.append(L[i+1] - L[i])
1 loops, best of 3: 234 ms per loop

Note that:

  • zip(L[1:], L) is equivalent to zip(L[1:], L[:-1]) since zip already terminates on the shortest input, however it avoids a whole copy of L.
  • Accessing the single elements by index is very slow because every index access is a method call in python
  • numpy.diff is slow because it has to first convert the list to a ndarray. Obviously if you start with an ndarray it will be much faster:

    In [22]: arr = np.array(L)
    In [23]: %timeit np.diff(arr)
    100 loops, best of 3: 3.02 ms per loop

JTable How to refresh table model after insert delete or update the data.

If you want to notify your JTable about changes of your data, use

From the documentation:

Notifies all listeners that all cell values in the table's rows may have changed. The number of rows may also have changed and the JTable should redraw the table from scratch. The structure of the table (as in the order of the columns) is assumed to be the same.

MsgBox "" vs MsgBox() in VBScript

The difference between "" and () is:

With "" you are not calling anything.
With () you are calling a sub.

Example with sub:

Sub = MsgBox("Msg",vbYesNo,vbCritical,"Title")
Select Case Sub
     Case = vbYes
          MsgBox"You said yes"
     Case = vbNo
          MsgBox"You said no"
 End Select

vs Normal:

 MsgBox"This is normal"

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

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

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

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

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

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

Hopefully that helps?

Also, its worth checking out these videos from Douglas Crockford

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

The Javascript language

Javascript - The Good Parts

Determine what user created objects in SQL Server

If each user has its own SQL Server login you could try this

select,, so.crdate 
    sysobjects so 
    sysusers su on so.uid = su.uid  
order by 

How to Create a script via batch file that will uninstall a program if it was installed on windows 7 64-bit or 32-bit

In my experience, to use wmic in a script, you need to get the nested quoting right:

wmic product where "name = 'Windows Azure Authoring Tools - v2.3'" call uninstall /nointeractive 

quoting both the query and the name. But wmic will only uninstall things installed via windows installer.

Truncate string in Laravel blade templates

In Laravel 4 & 5 (up to 5.7), you can use str_limit, which limits the number of characters in a string.

While in Laravel 7 up, you can use the Str::limit helper.

//For Laravel  to Laravel 7

{{ Illuminate\Support\Str::limit($post->title, 20, $end='...') }}

Is Python faster and lighter than C++?

I think those stats show that Python is much slower and uses more memory for those benchmarks - are you sure you're reading them the right way up?

In my experience, which is mostly with writing network- and file-system-bound programs in Python, Python isn't significantly slower in any way that matters. For that kind of work, its benefits outweigh its costs.

Use '=' or LIKE to compare strings in SQL?

There's a couple of other tricks that Postgres offers for string matching (if that happens to be your DB):

ILIKE, which is a case insensitive LIKE match:

select * from people where name ilike 'JOHN'


  • John
  • john
  • JOHN

And if you want to get really mad you can use regular expressions:

select * from people where name ~ 'John.*'


  • John
  • Johnathon
  • Johnny

Disable HttpClient logging

For apache 4.5.3, if you want to move the level for all apache http client logging to Warn, use:

How can a web application send push notifications to iOS devices?

No, only native iOS applications support push notifications.

Mac OS X 10.9 & Safari 7 websites can now also send push notifications, but this still does not apply to iOS. Read the Notification Programming Guide for Websites. Also check out WWDC 2013 Session 614.

Android: crashes with getApplicationContext

What I did to get around this was to create a base class for all my activities where I store global data. In the first activity, I saved the context in a variable in my base class like so:

Base Class

public static Context myucontext; 

First Activity derived from the Base Class

mycontext = this

Then I use mycontext instead of getApplicationContext when creating dialogs.

AlertDialog alertDialog = new AlertDialog.Builder(mycontext).create();

How can I show/hide component with JSF?

One obvious solution would be to use javascript (which is not JSF). To implement this by JSF you should use AJAX. In this example, I use a radio button group to show and hide two set of components. In the back bean, I define a boolean switch.

private boolean switchComponents;

public boolean isSwitchComponents() {
    return switchComponents;

public void setSwitchComponents(boolean switchComponents) {
    this.switchComponents = switchComponents;

When the switch is true, one set of components will be shown and when it is false the other set will be shown.

 <h:selectOneRadio value="#{backbean.switchValue}">
   <f:selectItem itemLabel="showComponentSetOne" itemValue='true'/>
   <f:selectItem itemLabel="showComponentSetTwo" itemValue='false'/>
   <f:ajax event="change" execute="@this" render="componentsRoot"/>

<H:panelGroup id="componentsRoot">
     <h:panelGroup rendered="#{backbean.switchValue}">
       <!--switchValue to be shown on switch value == true-->

   <h:panelGroup rendered="#{!backbean.switchValue}">
      <!--switchValue to be shown on switch value == false-->

Note: on the ajax event we render components root. because components which are not rendered in the first place can't be re-rendered on the ajax event.

Also, note that if the "componentsRoot" and radio buttons are under different component hierarchy. you should reference it from the root (form root).

Automatic HTTPS connection/redirect with node.js/express

Updated code for jake's answer. Run this alongside your https server.

// set up plain http server
var express = require('express');
var app = express();
var http = require('http');

var server = http.createServer(app);

// set up a route to redirect http to https
app.get('*', function(req, res) {
  res.redirect('https://' + + req.url);

// have it listen on 80

How do I configure Notepad++ to use spaces instead of tabs?

In my Notepad++ 7.2.2, the Preferences section it's a bit different.

The option is located at: Settings / Preferences / Language / Replace by space as in the Screenshot.

Screenshot of the windows with preferences

How do I convert an ANSI encoded file to UTF-8 with Notepad++?

Regarding this part:

When I convert it to UTF-8 without bom and close file, the file is again ANSI when I reopen.

The easiest solution is to avoid the problem entirely by properly configuring Notepad++.

Try Settings -> Preferences -> New document -> Encoding -> choose UTF-8 without BOM, and check Apply to opened ANSI files.

notepad++ UTF-8 apply to opened ANSI files

That way all the opened ANSI files will be treated as UTF-8 without BOM.

For explanation what's going on, read the comments below this answer.

To fully learn about Unicode and UTF-8, read this excellent article from Joel Spolsky.

reCAPTCHA ERROR: Invalid domain for site key

First of all, the keys are managed at

I ran into this error because I'm using the same key on a few different domains and I had forgotten to add one of the domains to the key.

After adding my site it took a minute or two (most likely because of cache) for things to work normally again.

Errno 10061 : No connection could be made because the target machine actively refused it ( client - server )

The below changes fixed my problem. I struggled with the same error for a week. I would like to share with you all that the solution is simply host = '' in the server and the client host = ip of the server.  

How do I print out the contents of an object in Rails for easy debugging?

define the to_s method in your model. For example

class Person < ActiveRecord::Base
  def to_s
    "Name:#{} Age:#{self.age} Weight: #{self.weight}"

Then when you go to print it with #puts it will display that string with those variables.

passing several arguments to FUN of lapply (and others *apply)

If you look up the help page, one of the arguments to lapply is the mysterious .... When we look at the Arguments section of the help page, we find the following line:

...: optional arguments to ‘FUN’.

So all you have to do is include your other argument in the lapply call as an argument, like so:

lapply(input, myfun, arg1=6)

and lapply, recognizing that arg1 is not an argument it knows what to do with, will automatically pass it on to myfun. All the other apply functions can do the same thing.

An addendum: You can use ... when you're writing your own functions, too. For example, say you write a function that calls plot at some point, and you want to be able to change the plot parameters from your function call. You could include each parameter as an argument in your function, but that's annoying. Instead you can use ... (as an argument to both your function and the call to plot within it), and have any argument that your function doesn't recognize be automatically passed on to plot.

getting integer values from textfield

As You're getting values from textfield as jTextField3.getText();.

As it is a textField it will return you string format as its format says:

String getText()

      Returns the text contained in this TextComponent.

So, convert your String to Integer as:

int jml = Integer.parseInt(jTextField3.getText());

instead of directly setting

   int jml = jTextField3.getText();

How to Logout of an Application Where I Used OAuth2 To Login With Google?

This works to sign the user out of the application, but not Google.

var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function () {
  console.log('User signed out.');


How to copy a folder via cmd?

xcopy  "C:\Documents and Settings\user\Desktop\?????????" "D:\Backup" /s /e /y /i

Probably the problem is the space.Try with quotes.

Display a float with two decimal places in Python

Using Python 3 syntax:

print('%.2f' % number)

how to load url into div tag

$(document).ready(function() {

Find the line number where a specific word appears with "grep"

You can call tail +[line number] [file] and pipe it to grep -n which shows the line number:

tail +[line number] [file] | grep -n /regex/

The only problem with this method is the line numbers reported by grep -n will be [line number] - 1 less than the actual line number in [file].

Edit a text file on the console using Powershell

If you use Windows container and you want change any file, you can get and use Vim in Powershell console easily.

To shelled to the Windows Docker container with PowerShell:

docker exec -it <name> powershell

  • First get Chocolatey package manager

    Invoke-WebRequest -UseBasicParsing | Invoke-Expression;

  • Install Vim

    choco install vim

  • Refresh ENVIRONMENTAL VARIABLE You can just exit and shell back to the container

  • Go to file location and Vim it vim file.txt

module.exports vs. export default in Node.js and ES6

The issue is with

  • how ES6 modules are emulated in CommonJS
  • how you import the module

ES6 to CommonJS

At the time of writing this, no environment supports ES6 modules natively. When using them in Node.js you need to use something like Babel to convert the modules to CommonJS. But how exactly does that happen?

Many people consider module.exports = ... to be equivalent to export default ... and ... to be equivalent to export const foo = .... That's not quite true though, or at least not how Babel does it.

ES6 default exports are actually also named exports, except that default is a "reserved" name and there is special syntax support for it. Lets have a look how Babel compiles named and default exports:

// input
export const foo = 42;
export default 21;

// output
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
var foo = = 42;
exports.default = 21; 

Here we can see that the default export becomes a property on the exports object, just like foo.

Import the module

We can import the module in two ways: Either using CommonJS or using ES6 import syntax.

Your issue: I believe you are doing something like:

var bar = require('./input');
new bar();

expecting that bar is assigned the value of the default export. But as we can see in the example above, the default export is assigned to the default property!

So in order to access the default export we actually have to do

var bar = require('./input').default;

If we use ES6 module syntax, namely

import bar from './input';

Babel will transform it to

'use strict';

var _input = require('./input');

var _input2 = _interopRequireDefault(_input);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }


You can see that every access to bar is converted to access .default.

SSRS 2008 R2 - SSRS 2012 - ReportViewer: Reports are blank in Safari and Chrome

I've used this. Add a script reference to jquery on the Report.aspx page. Use the following to link up JQuery to the microsoft events. Used a little bit of Eric's suggestion for setting the overflow.

$(document).ready(function () {
    if (navigator.userAgent.toLowerCase().indexOf("webkit") >= 0) {        
        Sys.Application.add_init(function () {
            var prm = Sys.WebForms.PageRequestManager.getInstance();
            if (!prm.get_isInAsyncPostBack()) {
                prm.add_endRequest(function () {
                    var divs = $('table[id*=_fixedTable] > tbody > tr:last > td:last > div')
                    divs.each(function (idx, element) {
                        $(element).css('overflow', 'visible');

How to get file path in iPhone app

If your tiles are not in your bundle, either copied from the bundle or downloaded from the internet you can get the directory like this

NSString *documentdir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *tileDirectory = [documentdir stringByAppendingPathComponent:@"xxxx/Tiles"];
NSLog(@"Tile Directory: %@", tileDirectory);

Create MSI or setup project with Visual Studio 2012

ISLE (InstallShield Limited Edition) is the "replacement" of the Visual Studio Setup and Deploy project, but many users think Microsoft took wrong step with removing .vdproj support from Visual Studio 2012 (and later ones) and supporting third-party company software.

Many people asked for returning it back (Bring back the basic setup and deployment project type Visual Studio Installer), but Microsoft is deaf to our voices... really sad.

As WiX is really complicated, I think it is worth to try some free installation systems - NSIS or Inno Setup. Both are scriptable and easy to learn - but powerful as original SADP.

I have created a really nice Visual Studio extension for NSIS and Inno Setup with many features (intellisense, syntax highlighting, navigation bars, compilation directly from Visual Studio, etc.). You can try it at (sorry for self promo :)

Download Inno Setup ( or NSIS ( and install V&I (

All installers are simple Next/Next/Next...

In Visual Studio, select menu File -> New -> Project, choose NSISProject or Inno Setup, and a new project will be created (with full sources).

How to compare strings in an "if" statement?

You're looking for the function strcmp, or strncmp from string.h.

Since strings are just arrays, you need to compare each character, so this function will do that for you:

if (strcmp(favoriteDairyProduct, "cheese") == 0)
    printf("You like cheese too!");
    printf("I like cheese more.");

Further reading: strcmp at

How do I get the current timezone name in Postgres 9.3?

This may or may not help you address your problem, OP, but to get the timezone of the current server relative to UTC (UT1, technically), do:


The above works by extracting the UT1-relative offset in minutes, and then converting it to hours using the factor of 3600 secs/hour.


SET SESSION timezone TO 'Asia/Kabul';
-- output: 4.5 (as of the writing of this post)


How do I import from Excel to a DataSet using Microsoft.Office.Interop.Excel?

What about using Excel Data Reader (previously hosted here) an open source project on codeplex? Its works really well for me to export data from excel sheets.

The sample code given on the link specified:

FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read);

//1. Reading from a binary Excel file ('97-2003 format; *.xls)
IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
//2. Reading from a OpenXml Excel file (2007 format; *.xlsx)
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
//3. DataSet - The result of each spreadsheet will be created in the result.Tables
DataSet result = excelReader.AsDataSet();
//4. DataSet - Create column names from first row
excelReader.IsFirstRowAsColumnNames = true;
DataSet result = excelReader.AsDataSet();

//5. Data Reader methods
while (excelReader.Read())

//6. Free resources (IExcelDataReader is IDisposable)


After some search around, I came across this article: Faster MS Excel Reading using Office Interop Assemblies. The article only uses Office Interop Assemblies to read data from a given Excel Sheet. The source code is of the project is there too. I guess this article can be a starting point on what you trying to achieve. See if that helps


The code below takes an excel workbook and reads all values found, for each excel worksheet inside the excel workbook.

private static void TestExcel()
        ApplicationClass app = new ApplicationClass();
        Workbook book = null;
        Range range = null;

            app.Visible = false;
            app.ScreenUpdating = false;
            app.DisplayAlerts = false;

            string execPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);

            book = app.Workbooks.Open(@"C:\data.xls", Missing.Value, Missing.Value, Missing.Value
                                              , Missing.Value, Missing.Value, Missing.Value, Missing.Value
                                             , Missing.Value, Missing.Value, Missing.Value, Missing.Value
                                            , Missing.Value, Missing.Value, Missing.Value);
            foreach (Worksheet sheet in book.Worksheets)

                Console.WriteLine(@"Values for Sheet "+sheet.Index);

                // get a range to work with
                range = sheet.get_Range("A1", Missing.Value);
                // get the end of values to the right (will stop at the first empty cell)
                range = range.get_End(XlDirection.xlToRight);
                // get the end of values toward the bottom, looking in the last column (will stop at first empty cell)
                range = range.get_End(XlDirection.xlDown);

                // get the address of the bottom, right cell
                string downAddress = range.get_Address(
                    false, false, XlReferenceStyle.xlA1,
                    Type.Missing, Type.Missing);

                // Get the range, then values from a1
                range = sheet.get_Range("A1", downAddress);
                object[,] values = (object[,]) range.Value2;

                // View the values
                for (int i = 1; i <= values.GetLength(0); i++)
                    for (int j = 1; j <= values.GetLength(1); j++)
                        Console.Write("{0}\t", values[i, j]);

        catch (Exception e)
            range = null;
            if (book != null)
                book.Close(false, Missing.Value, Missing.Value);
            book = null;
            if (app != null)
            app = null;

In the above code, values[i, j] is the value that you need to be added to the dataset. i denotes the row, whereas, j denotes the column.

How to refresh Android listview?

If I talked about my scenario here, non of above answers will not worked because I had activity that show list of db values along with a delete button and when a delete button is pressed, I wanted to delete that item from the list.

The cool thing was, I did not used recycler view but a simple list view and that list view initialized in the adapter class. So, calling the notifyDataSetChanged() will not do anything inside the adapter class and even in the activity class where adapter object is initialized because delete method was in the adapter class.

So, the solution was to remove the object from the adapter in the adapter class getView method(to only delete that specific object but if you want to delete all, call clear()).

To you to get some idea, what was my code look like,

public class WordAdapter extends ArrayAdapter<Word> {
  Context context;

  public WordAdapter(Activity context, ArrayList<Word> words) {}

    public View getView(final int position, View convertView, ViewGroup group) {
     ImageButton deleteBt = listItemView.findViewById(;
     deleteBt.setOnClickListener(new View.OnClickListener() {
         public void onClick(View v) {
             if (vocabDb.deleteWord( {
             } else{
             remove(getItem(position)); // <---- here is the trick ---<
             //clear() // if you want to clear everything

Note: here remove() and getItem() methods are inherit from the Adapter class.

  • remove() - to remove the specific item that is clicked
  • getItem(position) - is to get the item(here, thats my Word object that I have added to the list) from the clicked position.

This is how I set the adapter to the listview in the activity class,

    ArrayList<Word> wordList = new ArrayList();
    WordAdapter adapter = new WordAdapter(this, wordList);

    ListView list_view = (ListView) findViewById(;

How to combine paths in Java?

The main answer is to use File objects. However Commons IO does have a class FilenameUtils that can do this kind of thing, such as the concat() method.

Keystore change passwords

[How can I] Change the password, so I can share it with others and let them sign

Using keytool:

keytool -storepasswd -keystore /path/to/keystore
Enter keystore password:  changeit
New keystore password:  new-password
Re-enter new keystore password:  new-password

How to rotate x-axis tick labels in Pandas barplot

Try this -


enter image description here

how to do bitwise exclusive or of two strings in python?

def strxor (s0, s1):
  l = [ chr ( ord (a) ^ ord (b) ) for a,b in zip (s0, s1) ]
  return ''.join (l)

(Based on Mark Byers answer.)

Checking whether a variable is an integer or not

>>> isinstance(val,int ) 

will work.

What is Linux’s native GUI API?

Wayland is also worth mentioning as it is mostly referred as a "future X11 killer".

Also note that Android and some other mobile operating systems don't include X11 although they have a Linux kernel, so in that sense X11 is not native to all Linux systems.

Being cross-platform has nothing to do with being native. Cocoa has also been ported to other platforms via GNUStep but it is still native to OS X / macOS.

What's the difference between Perl's backticks, system, and exec?

In general I use system, open, IPC::Open2, or IPC::Open3 depending on what I want to do. The qx// operator, while simple, is too constraining in its functionality to be very useful outside of quick hacks. I find open to much handier.

system: run a command and wait for it to return

Use system when you want to run a command, don't care about its output, and don't want the Perl script to do anything until the command finishes.

#doesn't spawn a shell, arguments are passed as they are
system("command", "arg1", "arg2", "arg3");


#spawns a shell, arguments are interpreted by the shell, use only if you
#want the shell to do globbing (e.g. *.txt) for you or you want to redirect
system("command arg1 arg2 arg3");

qx// or ``: run a command and capture its STDOUT

Use qx// when you want to run a command, capture what it writes to STDOUT, and don't want the Perl script to do anything until the command finishes.

#arguments are always processed by the shell

#in list context it returns the output as a list of lines
my @lines = qx/command arg1 arg2 arg3/;

#in scalar context it returns the output as one string
my $output = qx/command arg1 arg2 arg3/;

exec: replace the current process with another process.

Use exec along with fork when you want to run a command, don't care about its output, and don't want to wait for it to return. system is really just

sub my_system {
    die "could not fork\n" unless defined(my $pid = fork);
    return waitpid $pid, 0 if $pid; #parent waits for child
    exec @_; #replace child with new process

You may also want to read the waitpid and perlipc manuals.

open: run a process and create a pipe to its STDIN or STDERR

Use open when you want to write data to a process's STDIN or read data from a process's STDOUT (but not both at the same time).

#read from a gzip file as if it were a normal file
open my $read_fh, "-|", "gzip", "-d", $filename
    or die "could not open $filename: $!";

#write to a gzip compressed file as if were a normal file
open my $write_fh, "|-", "gzip", $filename
    or die "could not open $filename: $!";

IPC::Open2: run a process and create a pipe to both STDIN and STDOUT

Use IPC::Open2 when you need to read from and write to a process's STDIN and STDOUT.

use IPC::Open2;

open2 my $out, my $in, "/usr/bin/bc"
    or die "could not run bc";

print $in "5+6\n";

my $answer = <$out>;

IPC::Open3: run a process and create a pipe to STDIN, STDOUT, and STDERR

use IPC::Open3 when you need to capture all three standard file handles of the process. I would write an example, but it works mostly the same way IPC::Open2 does, but with a slightly different order to the arguments and a third file handle.

How to get All input of POST in Laravel

its better to use the Dependency than to attache it to the class.

public function add_question(Request $request)
    return Request::all();

or if you prefer using input variable use

public function add_question(Request $input)
    return $input::all();

you can now use the global request method provided by laravel


for example to get the first_name of a form input.

// or

Ruby - test for array

Also consider using Array(). From the Ruby Community Style Guide:

Use Array() instead of explicit Array check or [*var], when dealing with a variable you want to treat as an Array, but you're not certain it's an array.

# bad
paths = [paths] unless paths.is_a? Array
paths.each { |path| do_something(path) }

# bad (always creates a new Array instance)
[*paths].each { |path| do_something(path) }

# good (and a bit more readable)
Array(paths).each { |path| do_something(path) }

How to schedule a stored procedure in MySQL

If you're open to out-of-the-DB solution: You could set up a cron job that runs a script that will itself call the procedure.

Finding length of char array

You can try this:

   char tab[7]={'a','b','t','u','a','y','t'};

WooCommerce: Finding the products in database

Bulk add new categories to Woo:

Insert category id, name, url key

INSERT INTO wp_terms 
  (57, 'Apples', 'fruit-apples', '0'),
  (58, 'Bananas', 'fruit-bananas', '0');

Set the term values as catergories

INSERT INTO wp_term_taxonomy 
  (57, 57, 'product_cat', '', 17, 0),
  (58, 58, 'product_cat', '', 17, 0)

17 - is parent category, if there is one

key here is to make sure the wp_term_taxonomy table term_taxonomy_id, term_id are equal to wp_term table's term_id

After doing the steps above go to wordpress admin and save any existing category. This will update the DB to include your bulk added categories

Get current rowIndex of table in jQuery

Try this,

   var row_index = $(this).parent().index();
   var col_index = $(this).index();

If you need the index of table contain td then you can change it to

var row_index = $(this).parent('table').index(); 

Onclick function based on element id

Make sure your code is in DOM Ready as pointed by rocket-hazmat


  //do something

document.getElementById("RootNode").onclick = function(){//do something}


Use event Delegation/

$(document).on("click", "#RootNode", function(){
   //do something


Wrap Code in Dom Ready

     //do something

Reverse colormap in matplotlib

The standard colormaps also all have reversed versions. They have the same names with _r tacked on to the end. (Documentation here.)

What is the best way to implement a "timer"?

It's not clear what type of application you're going to develop (desktop, web, console...)

The general answer, if you're developing Windows.Forms application, is use of

System.Windows.Forms.Timer class. The benefit of this is that it runs on UI thread, so it's simple just define it, subscribe to its Tick event and run your code on every 15 second.

If you do something else then windows forms (it's not clear from the question), you can choose System.Timers.Timer, but this one runs on other thread, so if you are going to act on some UI elements from the its Elapsed event, you have to manage it with "invoking" access.

What are bitwise shift (bit-shift) operators and how do they work?

Some useful bit operations/manipulations in Python.

I implemented Ravi Prakash's answer in Python.

# Basic bit operations
# Integer to binary

# Binary to integer
print(int('1010', 2))

# Multiplying x with 2 .... x**2 == x << 1
print(200 << 1)

# Dividing x with 2 .... x/2 == x >> 1
print(200 >> 1)

# Modulo x with 2 .... x % 2 == x & 1
if 20 & 1 == 0:
    print("20 is a even number")

# Check if n is power of 2: check !(n & (n-1))
print(not(33 & (33-1)))

# Getting xth bit of n: (n >> x) & 1
print((10 >> 2) & 1) # Bin of 10 == 1010 and second bit is 0

# Toggle nth bit of x : x^(1 << n)
# take bin(10) == 1010 and toggling second bit in bin(10) we get 1110 === bin(14)
print(10^(1 << 2))

CSS hover vs. JavaScript mouseover

If you don't need 100% support for IE6 with javascript disabled you could use something like ie7-js with IE conditional comments. Then you just use css rules to apply hover effects. I don't know exactly how it works but it uses javascript to make a lot of css rules work that don't normally in IE7 and 8.

Nullable DateTime conversion

Cast the null literal: (DateTime?)null or (Nullable<DateTime>)null.

You can also use default(DateTime?) or default(Nullable<DateTime>)

And, as other answers have noted, you can also apply the cast to the DateTime value rather than to the null literal.

EDIT (adapted from my comment to Prutswonder's answer):

The point is that the conditional operator does not consider the type of its assignment target, so it will only compile if there is an implicit conversion from the type of its second operand to the type of its third operand, or from the type of its third operand to the type of its second operand.

For example, this won't compile:

bool b = GetSomeBooleanValue();
object o = b ? "Forty-two" : 42;

Casting either the second or third operand to object, however, fixes the problem, because there is an implicit conversion from int to object and also from string to object:

object o = b ? "Forty-two" : (object)42;


object o = b ? (object)"Forty-two" : 42;

Best way to replace multiple characters in a string?

Late to the party, but I lost a lot of time with this issue until I found my answer.

Short and sweet, translate is superior to replace. If you're more interested in funcionality over time optimization, do not use replace.

Also use translate if you don't know if the set of characters to be replaced overlaps the set of characters used to replace.

Case in point:

Using replace you would naively expect the snippet "1234".replace("1", "2").replace("2", "3").replace("3", "4") to return "2344", but it will return in fact "4444".

Translation seems to perform what OP originally desired.

How to merge specific files from Git branches

The solution I found that caused me the least headaches:

git checkout <b1>
git checkout -b dummy
git merge <b2>
git checkout <b1>
git checkout dummy <path to file>

After doing that the file in path to file in b2 is what it would be after a full merge with b1.

PHP: HTML: send HTML select option attribute in POST

<form name="add" method="post">
     <select name="age">
        <option value="1_sre">23</option>
        <option value="2_sam">24</option>
        <option value="5_john">25</option>
     <input type="submit" name="submit"/>

You will have the selected value in $_POST['age'], e.g. 1_sre. Then you will be able to split the value and get the 'stud_name'.

$stud = explode("_",$_POST['age']);
$stud_id = $stud[0];
$stud_name = $stud[1];

VBA Print to PDF and Save with Automatic File Name

Hopefully this is self explanatory enough. Use the comments in the code to help understand what is happening. Pass a single cell to this function. The value of that cell will be the base file name. If the cell contains "AwesomeData" then we will try and create a file in the current users desktop called AwesomeData.pdf. If that already exists then try AwesomeData2.pdf and so on. In your code you could just replace the lines filename = Application..... with filename = GetFileName(Range("A1"))

Function GetFileName(rngNamedCell As Range) As String
    Dim strSaveDirectory As String: strSaveDirectory = ""
    Dim strFileName As String: strFileName = ""
    Dim strTestPath As String: strTestPath = ""
    Dim strFileBaseName As String: strFileBaseName = ""
    Dim strFilePath As String: strFilePath = ""
    Dim intFileCounterIndex As Integer: intFileCounterIndex = 1

    ' Get the users desktop directory.
    strSaveDirectory = Environ("USERPROFILE") & "\Desktop\"
    Debug.Print "Saving to: " & strSaveDirectory

    ' Base file name
    strFileBaseName = Trim(rngNamedCell.Value)
    Debug.Print "File Name will contain: " & strFileBaseName

    ' Loop until we find a free file number
        If intFileCounterIndex > 1 Then
            ' Build test path base on current counter exists.
            strTestPath = strSaveDirectory & strFileBaseName & Trim(Str(intFileCounterIndex)) & ".pdf"
            ' Build test path base just on base name to see if it exists.
            strTestPath = strSaveDirectory & strFileBaseName & ".pdf"
        End If

        If (Dir(strTestPath) = "") Then
            ' This file path does not currently exist. Use that.
            strFileName = strTestPath
            ' Increase the counter as we have not found a free file yet.
            intFileCounterIndex = intFileCounterIndex + 1
        End If

    Loop Until strFileName <> ""

    ' Found useable filename
    Debug.Print "Free file name: " & strFileName
    GetFileName = strFileName

End Function

The debug lines will help you figure out what is happening if you need to step through the code. Remove them as you see fit. I went a little crazy with the variables but it was to make this as clear as possible.

In Action

My cell O1 contained the string "FileName" without the quotes. Used this sub to call my function and it saved a file.

Sub Testing()
    Dim filename As String: filename = GetFileName(Range("o1"))

    ActiveWorkbook.Worksheets("Sheet1").Range("A1:N24").ExportAsFixedFormat Type:=xlTypePDF, _
                                              filename:=filename, _
                                              Quality:=xlQualityStandard, _
                                              IncludeDocProperties:=True, _
                                              IgnorePrintAreas:=False, _
End Sub

Where is your code located in reference to everything else? Perhaps you need to make a module if you have not already and move your existing code into there.

Session unset, or session_destroy?

Unset will destroy a particular session variable whereas session_destroy() will destroy all the session data for that user.

It really depends on your application as to which one you should use. Just keep the above in mind.

unset($_SESSION['name']); // will delete just the name data

session_destroy(); // will delete ALL data associated with that user.

Understanding the Rails Authenticity Token

The authenticity token is used to prevent Cross-Site Request Forgery attacks (CSRF). To understand the authenticity token, you must first understand CSRF attacks.


Suppose that you are the author of You have a form on your site that is used to transfer money to a different account with a GET request:

enter image description here

A hacker could just send an HTTP request to the server saying GET /transfer?amount=$1000000&account-to=999999, right?

enter image description here

Wrong. The hackers attack won't work. The server will basically think?

Huh? Who is this guy trying to initiate a transfer. It's not the owner of the account, that's for sure.

How does the server know this? Because there's no session_id cookie authenticating the requester.

When you sign in with your username and password, the server sets a session_id cookie on your browser. That way, you don't have to authenticate each request with your username and password. When your browser sends the session_id cookie, the server knows:

Oh, that's John Doe. He signed in successfully 2.5 minutes ago. He's good to go.

A hacker might think:

Hmm. A normal HTTP request won't work, but if I could get my hand on that session_id cookie, I'd be golden.

The users browser has a bunch of cookies set for the domain. Every time the user makes a request to the domain, all of the cookies get sent along. Including the session_id cookie.

So if a hacker could get you to make the GET request that transfers money into his account, he'd be successful. How could he trick you into doing so? With Cross Site Request Forgery.

It's pretty simply, actually. The hacker could just get you to visit his website. On his website, he could have the following image tag:

<img src="$1000000&account-to=999999">

When the users browser comes across that image tag, it'll be making a GET request to that url. And since the request comes from his browser, it'll send with it all of the cookies associated with If the user had recently signed in to the session_id cookie will be set, and the server will think that the user meant to transfer $1,000,000 to account 999999!

enter image description here

Well, just don't visit dangerous sites and you'll be fine.

That isn't enough. What if someone posts that image to Facebook and it appears on your wall? What if it's injected into a site you're visiting with a XSS attack?

It's not so bad. Only GET requests are vulnerable.

Not true. A form that sends a POST request can be dynamically generated. Here's the example from the Rails Guide on Security:

<a href="" onclick="
  var f = document.createElement('form'); = 'none';
  f.method = 'POST';
  f.action = '';
  return false;">To the harmless survey</a>

Authenticity Token

When your ApplicationController has this:

protect_from_forgery with: :exception


<%= form_tag do %>
  Form contents
<% end %>

Is compiled into this:

<form accept-charset="UTF-8" action="/" method="post">
  <input name="utf8" type="hidden" value="&#x2713;" />
  <input name="authenticity_token" type="hidden" value="J7CBxfHalt49OSHp27hblqK20c9PgwJ108nDHX/8Cts=" />
  Form contents

In particular, the following is generated:

<input name="authenticity_token" type="hidden" value="J7CBxfHalt49OSHp27hblqK20c9PgwJ108nDHX/8Cts=" />

To protect against CSRF attacks, if Rails doesn't see the authenticity token sent along with a request, it won't consider the request safe.

How is an attacker supposed to know what this token is? A different value is generated randomly each time the form is generated:

enter image description here

A Cross Site Scripting (XSS) attack - that's how. But that's a different vulnerability for a different day.

Better way to convert an int to a boolean

I assume 0 means false (which is the case in a lot of programming languages). That means true is not 0 (some languages use -1 some others use 1; doesn't hurt to be compatible to either). So assuming by "better" you mean less typing, you can just write:

bool boolValue = intValue != 0;

Append a dictionary to a dictionary

There are two ways to add one dictionary to another.

Update (modifies orig in place)

orig.update(extra)    # Python 2.7+
orig |= extra         # Python 3.9+

Merge (creates a new dictionary)

# Python 2.7+
dest = collections.ChainMap(orig, extra)
dest = {k: v for d in (orig, extra) for (k, v) in d.items()}

# Python 3
dest = {**orig, **extra}          
dest = {**orig, 'D': 4, 'E': 5}

# Python 3.9+ 
dest = orig | extra

Note that these operations are noncommutative. In all cases, the latter is the winner. E.g.

orig  = {'A': 1, 'B': 2}
extra = {'A': 3, 'C': 3}

dest = orig | extra
# dest = {'A': 3, 'B': 2, 'C': 3}

dest = extra | orig
# dest = {'A': 1, 'B': 2, 'C': 3}

It is also important to note that only from Python 3.7 (and CPython 3.6) dicts are ordered. So, in previous versions, the order of the items in the dictionary may vary.

SQL Query Where Field DOES NOT Contain $x

SELECT * FROM table WHERE field1 NOT LIKE '%$x%'; (Make sure you escape $x properly beforehand to avoid SQL injection)

Edit: NOT IN does something a bit different - your question isn't totally clear so pick which one to use. LIKE 'xxx%' can use an index. LIKE '%xxx' or LIKE '%xxx%' can't.

Angular2 - Focusing a textbox on component load

<input id="name" type="text" #myInput />
{{ myInput.focus() }}

this is the best and simplest way, because code "myInput.focus()" runs after input created

WARNING: this solution is acceptable only if you have single element in the form (user will be not able to select other elements)

Mean Squared Error in Numpy?

The standard numpy methods for calculation mean squared error (variance) and its square root (standard deviation) are numpy.var() and numpy.std(), see here and here. They apply to matrices and have the same syntax as numpy.mean().

I suppose that the question and the preceding answers might have been posted before these functions became available.

How to get time in milliseconds since the unix epoch in Javascript?

This will do the trick :-

new Date().valueOf() 

Formatting html email for Outlook

You should definitely check out the MSDN on what Outlook will support in regards to css and html. The link is here: If you do not have at least office 2007 you really need to upgrade as there are major differences between 2007 and previous editions. Also try saving the resulting email to file and examine it with firefox you will see what is being changed by outlook and possibly have a more specific question to ask. You can use Word to view the email as a sort of preview as well (but you won't get info on what styles are/are not being applied.

Python URLLib / URLLib2 POST

u = urllib2.urlopen('http://myserver/inout-tracker', data)
h.request('POST', '/inout-tracker/index.php', data, headers)

Using the path /inout-tracker without a trailing / doesn't fetch index.php. Instead the server will issue a 302 redirect to the version with the trailing /.

Doing a 302 will typically cause clients to convert a POST to a GET request.

Stack array using pop() and push()

Stack Implementation in Java

  class stack
  {  private int top;
     private int[] element;
      {element=new int[10];
      void push(int item)


      void pop()
      void display()

      public static void main(String args[])
        stack s1=new stack();



Top=0 Element=10 Top=1 Element=20 Top=2 Element=30 Top=1 Element=20

How to do a SOAP wsdl web services call from the command line

Using CURL:


CURL request:

curl --user "${AUTHENTICATION}" --header 'Content-Type: text/xml;charset=UTF-8' --data @"${SOAPFILE}" "${URL}" --connect-timeout $TIMEOUT

I use this to verify response:

http_code=$(curl --write-out "%{http_code}\n" --silent --user "${AUTHENTICATION}" --header 'Content-Type: text/xml;charset=UTF-8' --data @"${SOAPFILE}" "${URL}" --connect-timeout $TIMEOUT --output /dev/null)
if [[ $http_code -gt 400 ]];  # 400 and 500 Client and Server Error codes
echo "Error: HTTP response ($http_code) getting URL: $URL"
echo "Please verify parameters/backend. Username: $SOAP_USER Password: $PASSWORD Press any key to continue..."
read entervalue || continue

Bootstrap 4 navbar color

To change navbar background color:

.navbar-custom {

    background-color: yourcolor !important;

Resize image in PHP

I created an easy-to-use library for image resizing. It can be found here on Github.

An example of how to use the library:

// Include PHP Image Magician library

// Open JPG image
$magicianObj = new imageLib('racecar.jpg');

// Resize to best fit then crop (check out the other options)
$magicianObj -> resizeImage(100, 200, 'crop');

// Save resized image as a PNG (or jpg, bmp, etc)
$magicianObj -> saveImage('racecar_small.png');

Other features, should you need them, are:

  • Quick and easy resize - Resize to landscape, portrait, or auto
  • Easy crop
  • Add text
  • Quality adjustment
  • Watermarking
  • Shadows and reflections
  • Transparency support
  • Read EXIF metadata
  • Borders, Rounded corners, Rotation
  • Filters and effects
  • Image sharpening
  • Image type conversion
  • BMP support

How to access the services from RESTful API in my angularjs page?

Just to expand on $http (shortcut methods) here:$http

//Snippet from the page

$'/someUrl', data).success(successCallback);

//available shortcut methods


Bulk create model objects in django

Here is how to bulk-create entities from column-separated file, leaving aside all unquoting and un-escaping routines:

    def from_file(model, file_obj, headers, delimiter):
            model(**dict(zip(headers, line.split(delimiter))))
            for line in file_obj],

What is the difference between cssSelector & Xpath and which is better with respect to performance for cross browser testing?

CSS selectors perform far better than Xpath and it is well documented in Selenium community. Here are some reasons,

  • Xpath engines are different in each browser, hence make them inconsistent
  • IE does not have a native xpath engine, therefore selenium injects its own xpath engine for compatibility of its API. Hence we lose the advantage of using native browser features that WebDriver inherently promotes.
  • Xpath tend to become complex and hence make hard to read in my opinion

However there are some situations where, you need to use xpath, for example, searching for a parent element or searching element by its text (I wouldn't recommend the later).

You can read blog from Simon here . He also recommends CSS over Xpath.

If you are testing content then do not use selectors that are dependent on the content of the elements. That will be a maintenance nightmare for every locale. Try talking with developers and use techniques that they used to externalize the text in the application, like dictionaries or resource bundles etc. Here is my blog that explains it in detail.

edit 1

Thanks to @parishodak, here is the link which provides the numbers proving that CSS performance is better

How can I reset eclipse to default settings?

Yes, Eclipse can be a pain, as almost any IDE can. Please remain factual, however.

Switching to a new workspace should help you. Eclipse has almost no settings that are stored outside your workspace.

Difference between SET autocommit=1 and START TRANSACTION in mysql (Have I missed something?)

If you want to use rollback, then use start transaction and otherwise forget all those things,

By default, MySQL automatically commits the changes to the database.

To force MySQL not to commit these changes automatically, execute following:

SET autocommit = 0;
SET autocommit = OFF

To enable the autocommit mode explicitly:

SET autocommit = 1;
SET autocommit = ON;

Hiding the address bar of a browser (popup)

There is no definite way to do that. JS may have the API, but the browser vendor may choose not to implement it or implement it in another way.

Also, as far as I remember, Opera even provides the user preferences to prevent JS from making such changes, like have the window move, change status bar content, and stuff like that.

How to get the current time in milliseconds from C in Linux?

Derived from Dan Moulding's POSIX answer, this should work :

#include <time.h>
#include <math.h>

long millis(){
    struct timespec _t;
    clock_gettime(CLOCK_REALTIME, &_t);
    return _t.tv_sec*1000 + lround(_t.tv_nsec/1.0e6);

Also as pointed out by David Guyon: compile with -lm

how to call a method in another Activity from Activity

Simple, use static.

In activity you have the method you want to call:

private static String name = "Robert";


public static String getData() {
    return name;

And in your activity where you make the call:

private static String name;


name = SplashActivity.getData();

Is there a way to specify which pytest tests to run from a file?

If you have the same method name in two different classes and you just want to run one of them, this works:

pytest -k 'TestClassName and test_method_name'

What is Shelving in TFS?

If you're using Gated builds, when a build is triggered, it creates a shelveset of your workspace that is submitted for build. If the build fails, the shelveset is rejected. If the build is successful, a changeset is created and committed to TFS. In either event, the person doing that check-in/build will have to reconcile the workspace, which is as simple as performing a Get Latest.

"Couldn't read dependencies" error with npm

Try to add this:

"private": true,

it worked for me.

EDIT (for people asking why):

The Oficial documentation states the following:

If you set "private": true in your package.json, then npm will refuse to publish it. This is a way to prevent accidental publication of private repositories. If you would like to ensure that a given package is only ever published to a specific registry (for example, an internal registry), then use the publishConfig hash described below to override the registry config param at publish-time.

The error messages you are getting may be related to violating this "rule" in a way (mine was).

  • Either you are marking a unpublished package (like your own app) as "private": false.
  • Or you are neglecting to include any value at all.

Text not wrapping inside a div element

Might benefit you to be aware of another option, word-wrap: break-word;

The difference here is that words that can completely fit on 1 line will do that, vs. being forced to break simply because there is no more real estate on the line the word starts on.

See the fiddle for an illustration

Safest way to get last record ID from a table

You can try:

SELECT id FROM your_table WHERE id = (SELECT MAX(id) FROM your_table)

Where id is a primary key of the your_table

How can I convert a .py to .exe for Python?

Now you can convert it by using PyInstaller. It works with even Python 3.


  1. Fire up your PC
  2. Open command prompt
  3. Enter command pip install pyinstaller
  4. When it is installed, use the command 'cd' to go to the working directory.
  5. Run command pyinstaller <filename>

Rails: FATAL - Peer authentication failed for user (PG::Error)

If you installed postresql on your server then just host: localhost to database.yml, I usually throw it in around where it says pool: 5. Otherwise if it's not localhost definitely tell that app where to find its database.

  adapter: postgresql
  encoding: unicode
  database: kickrstack_development
  host: localhost
  pool: 5
  username: kickrstack
  password: secret

Make sure your user credentials are set correctly by creating a database and assigning ownership to your app's user to establish the connection. To create a new user in postgresql 9 run:

sudo -u postgres psql

set the postgresql user password if you haven't, it's just backslash password.

postgres=# \password

Create a new user and password and the user's new database:

postgres=# create user "guy_on_stackoverflow" with password 'keepitonthedl';
postgres=# create database "dcaclab_development" owner "guy_on_stackoverflow"; 

Now update your database.yml file after you've confirmed creating the database, user, password and set these privileges. Don't forget host: localhost.

What is a user agent stylesheet?

Each browser provides a default stylesheet, called the user agent stylesheet, in case an HTML file does not specify one. Styles that you specify override the defaults.

Because you have not specified values for the table element’s box, the default styles have been applied.

How do you share code between projects/solutions in Visual Studio?

You could include the same project in more than one solution, but you're guaranteed to run into problems sometime down the road (relative paths can become invalid when you move directories around for example)

After years of struggling with this, I finally came up with a workable solution, but it requires you to use Subversion for source control (which is not a bad thing)

At the directory level of your solution, add a svn:externals property pointing to the projects you want to include in your solution. Subversion will pull the project from the repository and store it in a subfolder of your solution file. Your solution file can simply use relative paths to refer to your project.

If I find some more time, I'll explain this in detail.

How do I remove all non-ASCII characters with regex and Notepad++?

Click on View/Show Symbol/Show All Character - to show the [SOH] characters in the file Click on the [SOH] symbol in the file CTRL=H to bring up the replace Leave the 'Find What:' as is Change the 'Replace with:' to the character of your choosing (comma,semicolon, other...) Click 'Replace All' Done and done!

Add space between cells (td) using css

cellspacing (distance between cells) parameter of the TABLE tag is precisely what you want. The disadvantage is it's one value, used both for x and y, you can't choose different spacing or padding vertically/horizontally. There is a CSS property too, but it's not widely supported.

Addressing localhost from a VirtualBox virtual machine

I need to run on localhost, not some weird IP.

1) From your Mac terminal, do iconfig -a to find your local IP address. It's probably the last one.

en7: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500 options=10b<RXCSUM,TXCSUM,VLAN_HWTAGGING,AV> ether 38:c9:86:32:0e:69 inet6 fe80::ea:393e:a54f:635%en7 prefixlen 64 secured scopeid 0xe inet netmask 0xfffffe00 broadcast nd6 options=201<PERFORMNUD,DAD> media: autoselect (1000baseT <full-duplex,flow-control>) status: active


2) boot up your windows image. start > type cmd to get a terminal

3) notepad c:\windows\system32\drivers\etc\hosts

4) add the following line localhost

5) open IE, and the following url should hit the server running on your mac: http://localhost:3000/

How to convert a SVG to a PNG with ImageMagick?

On Linux with Inkscape 1.0 to convert from svg to png need to use

inkscape -w 1024 -h 1024 input.svg --export-file output.png


inkscape -w 1024 -h 1024 input.svg --export-filename output.png

The following artifacts could not be resolved: javax.jms:jms:jar:1.1

Thanks for the suggestions. I finally found a solution to this problem after reading this. It turns out that these dependencies were coming from a dependency to ZooKeeper.

I modified my pom.xml as following and it solved the problem:


Declaring variables inside loops, good practice or bad practice?

I didn't post to answer JeremyRR's questions (as they have already been answered); instead, I posted merely to give a suggestion.

To JeremyRR, you could do this:

  string someString = "testing";   

  for(int counter = 0; counter <= 10; counter++)
    cout << someString;

  // The variable is in scope.

// The variable is no longer in scope.

I don't know if you realize (I didn't when I first started programming), that brackets (as long they are in pairs) can be placed anywhere within the code, not just after "if", "for", "while", etc.

My code compiled in Microsoft Visual C++ 2010 Express, so I know it works; also, I have tried to to use the variable outside of the brackets that it was defined in and I received an error, so I know that the variable was "destroyed".

I don't know if it is bad practice to use this method, as a lot of unlabeled brackets could quickly make the code unreadable, but maybe some comments could clear things up.

Standardize data columns in R

The dplyr package has two functions that do this.

> require(dplyr)

To mutate specific columns of a data table, you can use the function mutate_at(). To mutate all columns, you can use mutate_all.

The following is a brief example for using these functions to standardize data.

Mutate specific columns:

dt = data.table(a = runif(3500), b = runif(3500), c = runif(3500))
dt = data.table(dt %>% mutate_at(vars("a", "c"), scale)) # can also index columns by number, e.g., vars(c(1,3))

> apply(dt, 2, mean)
            a             b             c 
 1.783137e-16  5.064855e-01 -5.245395e-17 

> apply(dt, 2, sd)
        a         b         c 
1.0000000 0.2906622 1.0000000 

Mutate all columns:

dt = data.table(a = runif(3500), b = runif(3500), c = runif(3500))
dt = data.table(dt %>% mutate_all(scale))

> apply(dt, 2, mean)
            a             b             c 
-1.728266e-16  9.291994e-17  1.683551e-16 

> apply(dt, 2, sd)
a b c 
1 1 1 

Comparing two input values in a form validation with AngularJS

Mine is similar to your solution but I got it to work. Only difference is my model. I have the following models in my html input:


and in my controller, I have this in $scope:

 $ = {
        Participant: {}

and this validation line worked:

<label class="help-block" ng-show=" !== new.Participant.confirmEmail">Emails must match! </label>

WebDriver: check if an element exists?

As I understand it, this is the default way of using the web driver.

Python debugging tips

Winpdb is very nice, and contrary to its name it's completely cross-platform.

It's got a very nice prompt-based and GUI debugger, and supports remote debugging.

Insert/Update Many to Many Entity Framework . How do I do it?

In terms of entities (or objects) you have a Class object which has a collection of Students and a Student object that has a collection of Classes. Since your StudentClass table only contains the Ids and no extra information, EF does not generate an entity for the joining table. That is the correct behaviour and that's what you expect.

Now, when doing inserts or updates, try to think in terms of objects. E.g. if you want to insert a class with two students, create the Class object, the Student objects, add the students to the class Students collection add the Class object to the context and call SaveChanges:

using (var context = new YourContext())
    var mathClass = new Class { Name = "Math" };
    mathClass.Students.Add(new Student { Name = "Alice" });
    mathClass.Students.Add(new Student { Name = "Bob" });


This will create an entry in the Class table, two entries in the Student table and two entries in the StudentClass table linking them together.

You basically do the same for updates. Just fetch the data, modify the graph by adding and removing objects from collections, call SaveChanges. Check this similar question for details.


According to your comment, you need to insert a new Class and add two existing Students to it:

using (var context = new YourContext())
    var mathClass= new Class { Name = "Math" };
    Student student1 = context.Students.FirstOrDefault(s => s.Name == "Alice");
    Student student2 = context.Students.FirstOrDefault(s => s.Name == "Bob");


Since both students are already in the database, they won't be inserted, but since they are now in the Students collection of the Class, two entries will be inserted into the StudentClass table.

git still shows files as modified after adding to .gitignore

The solutions offered here and in other places didn't work for me, so I'll add to the discussion for future readers. I admittedly don't fully understand the procedure yet, but have finally solved my (similar) problem and want to share.

I had accidentally cached some doc-directories with several hundred files when working with git in IntelliJ IDEA on Windows 10, and after adding them to .gitignore (and PROBABLY moving them around a bit) I couldn't get them removed from the Default Changelist.

I first commited the actual changes I had made, then went about solving this - took me far too long. I tried git rm -r --cached . but would always get path-spec ERRORS, with different variations of the path-spec as well as with the -f and -r flags.

git status would still show the filenames, so I tried using some of those verbatim with git rm -cached, but no luck. Stashing and unstashing the changes seemed to work, but they got queued again after a time (I'm a bity hazy on the exact timeframe). I have finally removed these entries for good using

git reset

I assume this is only a GOOD IDEA when you have no changes staged/cached that you actually want to commit.

<SELECT multiple> - how to allow only one item selected?

Late to answer but might help someone else, here is how to do it without removing the 'multiple' attribute.

    //Here you can change the value of the maximum allowed options
    max_selected_options: 1

Replace first occurrence of string in Python

string replace() function perfectly solves this problem:

string.replace(s, old, new[, maxreplace])

Return a copy of string s with all occurrences of substring old replaced by new. If the optional argument maxreplace is given, the first maxreplace occurrences are replaced.

>>> u'longlongTESTstringTEST'.replace('TEST', '?', 1)

node.js TypeError: path must be absolute or specify root to res.sendFile [failed to parse JSON]

I used the code below and tried to show the sitemap.xml file

router.get('/sitemap.xml', function (req, res) {
    res.sendFile('sitemap.xml', { root: '.' });

Can't build create-react-app project with custom PUBLIC_URL

Have a look at the documentation. You can have a .env file which picks up the PUBLIC_URL

Although you should remember that what its used for -

You may use this variable to force assets to be referenced verbatim to the url you provide (hostname included). This may be particularly useful when using a CDN to host your application.

Get user's current location

You may want to take a look at GeoIP Country Whois Locator found at PHPClasses.

Composer: how can I install another dependency without updating old ones?

In my case, I had a repo with:

  • requirements A,B,C,D in .json
  • but only A,B,C in the .lock

In the meantime, A,B,C had newer versions with respect when the lock was generated.

For some reason, I deleted the "vendors" and wanted to do a composer install and failed with the message:

Warning: The lock file is not up to date with the latest changes in composer.json.
You may be getting outdated dependencies. Run update to update them.
Your requirements could not be resolved to an installable set of packages.

I tried to run the solution from Seldaek issuing a composer update vendorD/libraryD but composer insisted to update more things, so .lock had too changes seen my my git tool.

The solution I used was:

  1. Delete all the vendors dir.
  2. Temporarily remove the requirement VendorD/LibraryD from the .json.
  3. run composer install.
  4. Then delete the file .json and checkout it again from the repo (equivalent to re-adding the file, but avoiding potential whitespace changes).
  5. Then run Seldaek's solution composer update vendorD/libraryD

It did install the library, but in addition, git diff showed me that in the .lock only the new things were added without editing the other ones.

(Thnx Seldaek for the pointer ;) )

printf format specifiers for uint32_t and size_t


#include <inttypes.h>

printf("i [ %zu ] k [ %"PRIu32" ]\n", i, k);

The z represents an integer of length same as size_t, and the PRIu32 macro, defined in the C99 header inttypes.h, represents an unsigned 32-bit integer.

how to iterate through dictionary in a dictionary in django template?

If you pass a variable data (dictionary type) as context to a template, then you code should be:

{% for key, value in data.items %}
    <p>{{ key }} : {{ value }}</p> 
{% endfor %}

Which method performs better: .Any() vs .Count() > 0?

EDIT: it was fixed in EF version 6.1.1. and this answer is no more actual

For SQL Server and EF4-6, Count() performs about two times faster than Any().

When you run Table.Any(), it will generate something like(alert: don't hurt the brain trying to understand it)

    1 AS [C1]
    FROM [Table] AS [Extent1]
)) THEN cast(1 as bit) WHEN ( NOT EXISTS (SELECT 
    1 AS [C1]
    FROM [Table] AS [Extent2]
)) THEN cast(0 as bit) END AS [C1]
FROM  ( SELECT 1 AS X ) AS [SingleRowTable1]

that requires 2 scans of rows with your condition.

I don't like to write Count() > 0 because it hides my intention. I prefer to use custom predicate for this:

public static class QueryExtensions
    public static bool Exists<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate)
        return source.Count(predicate) > 0;

Model backing a DB Context has changed; Consider Code First Migrations

Just go to Package Manage Console, type the following:


*If the error like this appears "Unable to update database to match the current model because there are pending changes and automatic migration is disabled. Either write the pending model changes to a code-based migration or enable automatic migration."

Do this >>> Add-Migration

*Visual studio will ask for a name, kindly input the name you want.


"message failed to fetch from registry" while trying to install any module

I had to execute the command below:

npm config set registry

However, that will make npm install packages over an insecure HTTP connection. If you can, you should stick with

npm config set registry

instead to install over HTTPS.

Is there a JavaScript strcmp()?

What about


Can't open file 'svn/repo/db/txn-current-lock': Permission denied

This is a common problem. You're almost certainly running into permissions issues. To solve it, make sure that the apache user has read/write access to your entire repository. To do that, chown -R apache:apache *, chmod -R 664 * for everything under your svn repository.

Also, see here and here if you're still stuck.

Update to answer OP's additional question in comments:

The "664" string is an octal (base 8) representation of the permissions. There are three digits here, representing permissions for the owner, group, and everyone else (sometimes called "world"), respectively, for that file or directory.

Notice that each base 8 digit can be represented with 3 bits (000 for '0' through 111 for '7'). Each bit means something:

  • first bit: read permissions
  • second bit: write permissions
  • third bit: execute permissions

For example, 764 on a file would mean that:

  • the owner (first digit) has read/write/execute (7) permission
  • the group (second digit) has read/write (6) permission
  • everyone else (third digit) has read (4) permission

Hope that clears things up!

Programmatically Creating UILabel

Does the following work ?

UIFont * customFont = [UIFont fontWithName:ProximaNovaSemibold size:12]; //custom font
NSString * text = [self fromSender];

CGSize labelSize = [text sizeWithFont:customFont constrainedToSize:CGSizeMake(380, 20) lineBreakMode:NSLineBreakByTruncatingTail];

UILabel *fromLabel = [[UILabel alloc]initWithFrame:CGRectMake(91, 15, labelSize.width, labelSize.height)];
fromLabel.text = text;
fromLabel.font = customFont;
fromLabel.numberOfLines = 1;
fromLabel.baselineAdjustment = UIBaselineAdjustmentAlignBaselines; // or UIBaselineAdjustmentAlignCenters, or UIBaselineAdjustmentNone
fromLabel.adjustsFontSizeToFitWidth = YES;
fromLabel.adjustsLetterSpacingToFitWidth = YES;
fromLabel.minimumScaleFactor = 10.0f/12.0f;
fromLabel.clipsToBounds = YES;
fromLabel.backgroundColor = [UIColor clearColor];
fromLabel.textColor = [UIColor blackColor];
fromLabel.textAlignment = NSTextAlignmentLeft;
[collapsedViewContainer addSubview:fromLabel];

edit : I believe you may encounter a problem using both adjustsFontSizeToFitWidth and minimumScaleFactor. The former states that you also needs to set a minimumFontWidth (otherwhise it may shrink to something quite unreadable according to my test), but this is deprecated and replaced by the later.

edit 2 : Nevermind, outdated documentation. adjustsFontSizeToFitWidth needs minimumScaleFactor, just be sure no to pass it 0 as a minimumScaleFactor (integer division, 10/12 return 0). Small change on the baselineAdjustment value too.

Intellij Idea: Importing Gradle project - getting JAVA_HOME not defined yet

Try starting IntelliJ from terminal. You can find application file under: /Applications/IntelliJ\ IDEA\

Unix tail equivalent command in Windows Powershell

There have been many valid answers, however, none of them has the same syntax as tail in linux. The following function can be stored in your $Home\Documents\PowerShell\Microsoft.PowerShell_profile.ps1 for persistency (see powershell profiles documentation for more details).

This allows you to call...

tail server.log
tail -n 5 server.log
tail -f server.log
tail -Follow -Lines 5 -Path server.log

which comes quite close to the linux syntax.

function tail {
        Get the last n lines of a text file.
    .PARAMETER Follow
        output appended data as the file grows
    .PARAMETER Lines
        output the last N lines (default: 10)
        path to the text file
        PS> tail c:\server.log
        PS> tail -f -n 20 c:\server.log

        [Int]$Lines = 10,

        [parameter(Mandatory=$true, Position=5)]
    if ($Follow)
        Get-Content -Path $Path -Tail $Lines -Wait
        Get-Content -Path $Path -Tail $Lines

Django Server Error: port is already in use

if you have face this problem in mac you just need to open activity monitor and force quite python then try again

enter image description here

How do I increase modal width in Angular UI Bootstrap?

You can specify custom width for .modal-lg class specifically for your popup for wider viewport resolution. Here is how to do it:


@media (min-width: 1400px){

   .my-modal-popup .modal-lg {
       width: 1308px;



var modal = ${
    animation: true,
    templateUrl: 'modalTemplate.html',
    controller: 'modalController',
    size: 'lg',
    windowClass: 'my-modal-popup'

How to stop PHP code execution?

Please see the following information from user Pekka ?

According to the manual, destructors are executed even if the script gets terminated using die() or exit():

The destructor will be called even if script execution is stopped using exit(). Calling exit() in a destructor will prevent the remaining shutdown routines from executing.
According to this PHP: destructor vs register_shutdown_function, the destructor does not get executed when PHP's execution time limit is reached (Confirmed on Apache 2, PHP 5.2 on Windows 7).

The destructor also does not get executed when the script terminates because the memory limit was reached. (Just tested)

The destructor does get executed on fatal errors (Just tested) Update: The OP can't confirm this - there seem to be fatal errors where things are different

It does not get executed on parse errors (because the whole script won't be interpreted)

The destructor will certainly not be executed if the server process crashes or some other exception out of PHP's control occurs.

Referenced in this question Are there any instances when the destructor in PHP is NOT called?

JDK was not found on the computer for NetBeans 6.5

From the commnand prompt execute the following two commands:

netbeans-6.5.1-windows.exe –extract //two dashes before extract

java -jar bundle.jar

The first one extracts the installer from the exe while the other executes the installer.

according to this link:

In Bootstrap open Enlarge image in modal


img.modal-img {
  cursor: pointer;
  transition: 0.3s;
img.modal-img:hover {
  opacity: 0.7;
.img-modal {
  display: none;
  position: fixed;
  z-index: 99999;
  padding-top: 100px;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgba(0,0,0,0.9);
.img-modal img {
  margin: auto;
  display: block;
  width: 80%;
  max-width: 700%;
.img-modal div {
  margin: auto;
  display: block;
  width: 80%;
  max-width: 700px;
  text-align: center;
  color: #ccc;
  padding: 10px 0;
  height: 150px;
.img-modal img, .img-modal div {
  animation: zoom 0.6s;
.img-modal span {
  position: absolute;
  top: 15px;
  right: 35px;
  color: #f1f1f1;
  font-size: 40px;
  font-weight: bold;
  transition: 0.3s;
  cursor: pointer;
@media only screen and (max-width: 700px) {
  .img-modal img {
    width: 100%;
@keyframes zoom {
  0% {
    transform: scale(0);
  100% {
    transform: scale(1);


$('img.modal-img').each(function() {_x000D_
    var modal = $('<div class="img-modal"><span>&times;</span><img /><div></div></div>');_x000D_
    modal.find('img').attr('src', $(this).attr('src'));_x000D_
    modal = $(this).next();_x000D_
    $(this).click(function(event) {_x000D_;_x000D_
    modal.find('span').click(function(event) {_x000D_
  $(document).keyup(function(event) {_x000D_
img.modal-img {_x000D_
  cursor: pointer;_x000D_
  transition: 0.3s;_x000D_
img.modal-img:hover {_x000D_
  opacity: 0.7;_x000D_
.img-modal {_x000D_
  display: none;_x000D_
  position: fixed;_x000D_
  z-index: 99999;_x000D_
  padding-top: 100px;_x000D_
  left: 0;_x000D_
  top: 0;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  overflow: auto;_x000D_
  background-color: rgba(0,0,0,0.9);_x000D_
.img-modal img {_x000D_
  margin: auto;_x000D_
  display: block;_x000D_
  width: 80%;_x000D_
  max-width: 700%;_x000D_
.img-modal div {_x000D_
  margin: auto;_x000D_
  display: block;_x000D_
  width: 80%;_x000D_
  max-width: 700px;_x000D_
  text-align: center;_x000D_
  color: #ccc;_x000D_
  padding: 10px 0;_x000D_
  height: 150px;_x000D_
.img-modal img, .img-modal div {_x000D_
  animation: zoom 0.6s;_x000D_
.img-modal span {_x000D_
  position: absolute;_x000D_
  top: 15px;_x000D_
  right: 35px;_x000D_
  color: #f1f1f1;_x000D_
  font-size: 40px;_x000D_
  font-weight: bold;_x000D_
  transition: 0.3s;_x000D_
  cursor: pointer;_x000D_
@media only screen and (max-width: 700px) {_x000D_
  .img-modal img {_x000D_
    width: 100%;_x000D_
@keyframes zoom {_x000D_
  0% {_x000D_
    transform: scale(0);_x000D_
  100% {_x000D_
    transform: scale(1);_x000D_
$('img.modal-img').each(function() {_x000D_
    var modal = $('<div class="img-modal"><span>&times;</span><img /><div></div></div>');_x000D_
    modal.find('img').attr('src', $(this).attr('src'));_x000D_
    modal = $(this).next();_x000D_
    $(this).click(function(event) {_x000D_;_x000D_
    modal.find('span').click(function(event) {_x000D_
  $(document).keyup(function(event) {_x000D_
<script src=""></script>_x000D_
<script src=""></script>_x000D_
<link href="" rel="stylesheet"/>_x000D_
<img src="" class="modal-img">

Can overridden methods differ in return type?

Overriding and Return Types, and Covariant Returns
the subclass must define a method that matches the inherited version exactly. Or, as of Java 5, you're allowed to change the return type in the

sample code

                                                                                                            class Alpha {
          Alpha doStuff(char c) {
                  return new Alpha();
             class Beta extends Alpha {
                    Beta doStuff(char c) { // legal override in Java 1.5
                    return new Beta();
             } } 
As of Java 5, this code will compile. If you were to attempt to compile this code with a 1.4 compiler will say attempting to use incompatible return type – sandeep1987 1 min ago

Is there a php echo/print equivalent in javascript

From w3school's page on JavaScript output,

JavaScript can "display" data in different ways:

Writing into an alert box, using window.alert().

Writing into the HTML output using document.write().

Writing into an HTML element, using innerHTML.

Writing into the browser console, using console.log().

Using JSON POST Request

An example using jQuery is below. Hope this helps

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<title>My jQuery JSON Web Page</title>
<script type="text/javascript" src=""></script>
<script type="text/javascript">

JSONTest = function() {

    var resultDiv = $("#resultDivContainer");

        url: "",
        type: "POST",
        data: { apiKey: "23462", method: "example", ip: "" },
        dataType: "json",
        success: function (result) {
            switch (result) {
                case true:
        error: function (xhr, ajaxOptions, thrownError) {


<h1>My jQuery JSON Web Page</h1>

<div id="resultDivContainer"></div>

<button type="button" onclick="JSONTest()">JSON</button>


Firebug debug process

Firebug XHR debug process

Format decimal for percentage values?

If you have a good reason to set aside culture-dependent formatting and get explicit control over whether or not there's a space between the value and the "%", and whether the "%" is leading or trailing, you can use NumberFormatInfo's PercentPositivePattern and PercentNegativePattern properties.

For example, to get a decimal value with a trailing "%" and no space between the value and the "%":

myValue.ToString("P2", new NumberFormatInfo { PercentPositivePattern = 1, PercentNegativePattern = 1 });

More complete example:

using System.Globalization; 


decimal myValue = -0.123m;
NumberFormatInfo percentageFormat = new NumberFormatInfo { PercentPositivePattern = 1, PercentNegativePattern = 1 };
string formattedValue = myValue.ToString("P2", percentageFormat); // "-12.30%" (in en-us)

How to get parameter value for date/time column from empty MaskedTextBox

You're storing the .Text properties of the textboxes directly into the database, this doesn't work. The .Text properties are Strings (i.e. simple text) and not typed as DateTime instances. Do the conversion first, then it will work.

Do this for each date parameter:

Dim bookIssueDate As DateTime = DateTime.ParseExact( txtBookDateIssue.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture ) cmd.Parameters.Add( New OleDbParameter("@Date_Issue", bookIssueDate ) ) 

Note that this code will crash/fail if a user enters an invalid date, e.g. "64/48/9999", I suggest using DateTime.TryParse or DateTime.TryParseExact, but implementing that is an exercise for the reader.

How to fill OpenCV image with one solid color?

Here's how to do with cv2 in Python:

# Create a blank 300x300 black image
image = np.zeros((300, 300, 3), np.uint8)
# Fill image with red color(set each pixel to red)
image[:] = (0, 0, 255)

Here's more complete example how to create new blank image filled with a certain RGB color

import cv2
import numpy as np

def create_blank(width, height, rgb_color=(0, 0, 0)):
    """Create new image(numpy array) filled with certain color in RGB"""
    # Create black blank image
    image = np.zeros((height, width, 3), np.uint8)

    # Since OpenCV uses BGR, convert the color first
    color = tuple(reversed(rgb_color))
    # Fill image with color
    image[:] = color

    return image

# Create new blank 300x300 red image
width, height = 300, 300

red = (255, 0, 0)
image = create_blank(width, height, rgb_color=red)
cv2.imwrite('red.jpg', image)

Server configuration is missing in Eclipse

This happens when Eclipse shuts down incorrectly - delete the server and then re-create it again.

Which programming languages can be used to develop in Android?

Java and C:

  • C used for low level functionalities and device connectivities
  • Java used for Framework and Application Level

You may find more information in Android developers site.

correct PHP headers for pdf file download

I had the same problem recently and this helped me:

    header('Content-Description: File Transfer'); 
    header('Content-Type: application/octet-stream'); 
    header('Content-Disposition: attachment; filename="FILENAME"'); 
    header('Content-Transfer-Encoding: binary'); 
    header('Expires: 0'); 
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); 
    header('Pragma: public'); 
    header('Content-Length: ' . filesize("PATH/TO/FILE")); 

I found this answer here

Dynamic Web Module 3.0 -- 3.1

I had the same problem and fixed this by editing org.eclipse.wst.common.project.facet.core.xml.

In this file, I was able to change the following line

<installed facet="jst.web" version="3.1"/>

back to

<installed facet="jst.web" version="3.0"/>

That seemed to fix the problem for me.