DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets

  • submit to reddit

Recent Snippets

                    #!/usr/bin/env ruby
# Author : Emad Elsaid (https://github.com/blazeeboy)
require 'koala' # gem install koala --no-document
# create a facebook app and get access token from here
# https://developers.facebook.com/tools/explorer
# select "user_status", "friends_status", "user_checkins" when authenticating
oauth_access_token = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
graph = Koala::Facebook::API.new(oauth_access_token)

places = []
page = graph.get_connections('me', 'checkins')
begin
	places += page.map {|p| p['place']}
end while page = page.next_page

places.each do |place|
	unless place['location'].is_a? String
		puts "#{place['name']} lat:#{place['location']['latitude']} long:#{place['location']['longitude']}"
	else
		puts "#{place['name']} location:#{place['location']}"
	end
end                
                    Steps to do the Contextual Logging

Configuring one time which is very efficient.

log4j.properties -- text highlighted in green specifies contextual information

1) log4j.appender.stdout.layout.ConversionPattern=%-5p %-23d{MM-dd-yyyy HH:mm:ss:S} [%t] %X{clientRequestIP} %X{timestamp} %X{session} %X{loggedinuserid} %X{loggedinusername} %X{httpmethod}  %X{requesturl} %c:%L %m%n


2) Code Snippet
Put this code in Filter class. This will be invoked once per request and attach unique timestamp which will be prepended for each controller, service, dao, adapter methods

		import org.apache.log4j.MDC;
	    	. . . . . .
		. . . . . .
		final long timestamp = (new Date()).getTime();
		MDC.put("timestamp", timestamp);
		MDC.put("httpmethod", httpmethod);
		MDC.put("session", sessionid);
		MDC.put("requesturl", requestUrl);
		MDC.put("loggedinusername", username);                
                    #!/usr/bin/env ruby
# Author : Emad Elsaid (https://github.com/blazeeboy)
FILENAME = 'db.txt'
OPEN, CLOSE = 1 , 0

file = File.open(FILENAME, 'a')
file.write "#{OPEN} : #{Time.new}\n"
file.flush

begin
	loop { sleep 60 } # sleep for an hour in an endless loop

rescue SystemExit, Interrupt # on exit
	file.write "#{CLOSE} : #{Time.new}\n"
	file.close
end                
                    #!/usr/bin/env ruby
# Author : Emad Elsaid (https://github.com/blazeeboy)
require 'json'
require 'open-uri'
require 'uri'
require 'net/http'

CODE_LIMIT = 10
$url = "https://eval.in/"
$languages = {
	'c' => 'c/gcc-4.7.2',					'c++' => 'c++/gcc-4.7.2',
	'fortran' => 'fortran/f95-4.4.3',		'haskell' => 'haskell/hugs98-sep-2006',
	'io' => 'io/io-20110912',				'javascript' => 'javascript/node-0.10.26',
	'lua' => 'lua/lua-5.2.1',				'ocaml' => 'ocaml/ocaml-4.00.1',
	'php' => 'php/php-5.5.1',				'perl' => 'perl/perl-5.16.1',
	'python' => 'python/cpython-3.2.3',		'ruby' => 'ruby/mri-2.1.0',
	'slash' => 'slash/slash-head',			'assembly' => 'assembly/nasm-2.07'
}

def evalin code, language

	return nil unless $languages.keys.include? language
	return nil if code.length < CODE_LIMIT

	params = {
		code: code,			lang: $languages[language],
		execute: 'on',		input: ''
	}

	postData = Net::HTTP.post_form(URI.parse($url), params)
	location = postData['location']
	if location
		evalin_data = JSON.parse open("#{location.gsub 'http://', 'https://'}.json").read
		return "#{evalin_data['output']}\n#{evalin_data['status']}\n#{location}"
	end
	return nil
end

puts evalin('10.times{ puts "done."}', 'ruby')                
                    #!/usr/bin/env ruby
# Author : Emad Elsaid (https://github.com/blazeeboy)
require "selenium-webdriver" # gem install selenium-webdriver
require "highline/import" # gem install highline

def coderwall github_email, github_password, title, content, tags

	driver = Selenium::WebDriver.for :firefox

	driver.navigate.to "https://coderwall.com/auth/github"
	
	driver.find_element(:css, '#login_field').send_keys github_email
	passwordf = driver.find_element(:css, '#password')
	passwordf.send_keys github_password
	passwordf.submit

	driver.navigate.to "https://coderwall.com/p/new"
	driver.find_element(:css, '#protip_title').send_keys title
	driver.find_element(:css, '#protip_body').send_keys content
	driver.find_element(:css, '#protip_tags').send_keys tags
	driver.find_element(:css, '.new_protip').submit

	driver.quit
end

email = ask 'What is your github email address ? '
password = ask('And github password? '){ |q| q.echo = '*' }
coderwall email, password, 'Title here', 'Content here', 'ruby, test'                
                    #!/usr/bin/env ruby
# Author : Emad Elsaid (https://github.com/blazeeboy)
require 'json'
require 'psych'
require 'commander/import' # gem install commander
program :version, '0.0.1'
program :description, 'Simple Key Value Storage Commandline Script'

FILENAME = 'storage.json'
storage = File.exists?(FILENAME) ? JSON.parse(File.read(FILENAME)) : {}

command :c do |c|
  c.syntax = 'storage c key value'
  c.description = 'create new key with a value in our storage'
  c.example 'store myname key with my name as a value', 'ruby storage c myname emad elsaid hamed'
  c.action do |args, options|
    storage[args[0]] = args[1..-1].join(' ')
    File.write FILENAME, storage.to_json
  end
end

command :r do |c|
  c.syntax = 'storage r key'
  c.description = 'read a key value or all values from storage'
  c.example 'read my name', 'ruby storage r myname'
  c.action do |args, options|
    puts( args[0] ? storage[args[0]] : storage.to_yaml )
  end
end

command :d do |c|
  c.syntax = 'storage d key'
  c.description = 'delete a key from storage'
  c.example 'remove my name from storage', 'ruby storage d myname'
  c.action do |args, options|
    storage.delete args[0]
    File.write FILENAME, storage.to_json
  end
end

                
                    #!/usr/bin/env ruby
# Author : Emad Elsaid (https://github.com/blazeeboy)
require 'gosu'
include Gosu
DIMENSION, SPLITS, COLOR = 200, 50, Color::GREEN
# credits to: http://en.wikipedia.org/wiki/Maze_generation_algorithm
class GameWindow < Window
  def initialize
    super DIMENSION, DIMENSION, false, 1000
    self.caption = "Maze"
  end
  def draw
    complexity, density = 0.75, 0.75
    shape = [(SPLITS / 2) * 2 , (SPLITS / 2) * 2 ] # Only odd shapes
    # Adjust complexity and density relative to maze size
    complexity = (complexity * (5 * (shape[0] + shape[1])))
    density    = (density * (shape[0] / 2 * shape[1] / 2))
    z = Array.new(shape[0]){ Array.new(shape[1], 0) } # Build actual maze
    # Fill borders
    z[0] = z[-1].fill 1
    z.each { |l| l[0] = l[-1] = 1 }
    for i in 0...density # Make isles
        x, y = rand(shape[1] / 2) * 2, rand(shape[0] / 2) * 2
        z[y][x] = 1
        for j in 0...complexity
            neighbours = []
            neighbours << [y, x - 2] if x > 1
            neighbours << [y, x + 2] if x < shape[1] - 2
            neighbours << [y - 2, x] if y > 1
            neighbours << [y + 2, x] if y < shape[0] - 2
            unless neighbours.empty?
                y_,x_ = neighbours[rand(neighbours.size - 1)]
                if z[y_][x_] == 0
                    z[y_ + (y - y_) / 2][x_ + (x - x_) / 2] = z[y_][x_] = 1
                    x, y = x_, y_
                end
            end
        end
    end
    size = DIMENSION/SPLITS
  	z.each_with_index do |row, x|
        row.each_with_index do |value, y|
            draw_quad x*size, y*size, COLOR,
                      x*size+size, y*size, COLOR,
                      x*size+size, y*size+size, COLOR,
                      x*size, y*size+size, COLOR if value==1
        end
    end
  end
end
GameWindow.new.show                
                    #!/usr/bin/env ruby
# Author : Emad Elsaid (https://github.com/blazeeboy)
require 'gosu'
include Gosu

$dimension = 200
$line_limit = 70

class GameWindow < Window

  def initialize
    super $dimension, $dimension, false
    self.caption = "Drawing board"
  	@points = []
  end

  def update
    @points << [ mouse_x, mouse_y ]
    @points.shift if @points.size > $line_limit
  end

  def draw
  	return if @points.empty?
	@points.inject(@points[0]) do |last, point|
		draw_line	last[0],last[1], Color::GREEN,
					point[0],point[1], Color::GREEN
		point
	end
  end
  
end
GameWindow.new.show
                
                    #!/usr/bin/env ruby
# Author : Emad Elsaid (https://github.com/blazeeboy)
# Idea of : Thibault (@EyeWriteCode)
require 'Twitter' #gem install twitter
begin
	# Create a read application from : 
	# https://apps.twitter.com
	# authenticate it for your account
	# fill in the following
	config = {
		consumer_key:        '',
		consumer_secret:     '',
		access_token:        '',
		access_token_secret: ''
	}
	sClient = Twitter::Streaming::Client.new(config)
	rClient = Twitter::REST::Client.new(config)
	following = rClient.friend_ids.to_a
	topics = ['#NP', '#NW', '#nowplaying', '#now_playing']

	sClient.filter(track: topics.join(',')) do |tweet|
		if tweet.is_a?(Twitter::Tweet)
		  text = tweet.text
		  			.gsub(/[#@]\S+/,'')
		  			.gsub(/\n+/,' ')
		  			.gsub(/\s{2,}/,'')
		  			.strip
		  user = tweet.user
		  puts "#{user.screen_name} : #{text}" if following.include? user.id
		end
	end
rescue
	puts 'error occurred, waiting for 5 seconds'
	sleep 5
	retry
end                
                    #!/usr/bin/env ruby
# Author : Emad Elsaid (https://github.com/blazeeboy)
require 'sinatra'

set :port, 3000
set :environment, :production

get '/' do
	<<-EOT
<html><head>
	</head><body style="padding:0px;margin:0px;">
	<form action="/upload" method="post" enctype="multipart/form-data" >
		Choose files <input type="file" name="files[]" multiple>
		<input type="submit" value="Upload" />
	</form>
</body></html>
EOT
end

post '/upload' do
	params['files'].each do |f|
		tempfile = f[:tempfile]
		filename = f[:filename]
		FileUtils.copy(tempfile.path, "./#{filename}")
	end
	redirect '/'
end