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
require 'open-uri'
require 'json'

print 'Github Username: '
username = gets.chomp

# get gists
puts 'Downloading gists list'
gists_str = open("https://api.github.com/users/#{username}/gists").read
gists = JSON.parse gists_str

gists.each_with_index do |gist, index|

	puts "#{index+1}/#{gists.length} Downloading #{gist['url']}"
	gist_str = open(gist['url']).read
	gist = JSON.parse gist_str

	dir = gist["id"]
	Dir.mkdir dir unless Dir.exist? dir

	gist["files"].each do |file_name, file_value|
		File.open("#{dir}/#{file_name}", 'w') { |f| f.write file_value['content']}
	end

end
                
                    #!/usr/bin/env ruby
require 'pygmentize' # gem install pygmentize
require 'selenium-webdriver' # gem install selenium-webdriver

exit unless code_path = ARGV.shift

file_path = File.absolute_path 'code.html'
image_path = File.absolute_path 'code_image.png'
code = Pygmentize.process File.read(code_path), :ruby
html = <<-EOT
<html>
<style>
body { padding:0px; margin:0px; } .highlight { padding: 20px; font-size: 13px; }div.highlight, div.highlight code, div.highlight pre  { background: #29281e; }div.highlight code { padding: 0; }div.highlight .c { color: #75715e }div.highlight .err { color: #960050; background-color: #1e0010 }div.highlight .k { color: #66d9ef }div.highlight .l { color: #ae81ff }div.highlight .n { color: #f8f8f2 }div.highlight .o { color: #f92672 }div.highlight .p { color: #f8f8f2 }div.highlight .cm { color: #75715e }div.highlight .cp { color: #75715e }div.highlight .c1 { color: #75715e }div.highlight .cs { color: #75715e }div.highlight .ge { font-style: italic }div.highlight .gs { font-weight: bold }div.highlight .kc { color: #66d9ef }div.highlight .kd { color: #66d9ef }div.highlight .kn { color: #f92672 }div.highlight .kp { color: #66d9ef }div.highlight .kr { color: #66d9ef }div.highlight .kt { color: #66d9ef }div.highlight .ld { color: #e6db74 }div.highlight .m { color: #ae81ff }div.highlight .s { color: #e6db74 }div.highlight .na { color: #a6e22e }div.highlight .nb { color: #f8f8f2 }div.highlight .nc { color: #a6e22e }div.highlight .no { color: #66d9ef }div.highlight .nd { color: #a6e22e }div.highlight .ni { color: #f8f8f2 }div.highlight .ne { color: #a6e22e }div.highlight .nf { color: #a6e22e }div.highlight .nl { color: #f8f8f2 }div.highlight .nn { color: #f8f8f2 }div.highlight .nx { color: #a6e22e }div.highlight .py { color: #f8f8f2 }div.highlight .nt { color: #f92672 }div.highlight .nv { color: #f8f8f2 }div.highlight .ow { color: #f92672 }div.highlight .w { color: #f8f8f2 }div.highlight .mf { color: #ae81ff }div.highlight .mh { color: #ae81ff }div.highlight .mi { color: #ae81ff }div.highlight .mo { color: #ae81ff }div.highlight .sb { color: #e6db74 }div.highlight .sc { color: #e6db74 }div.highlight .sd { color: #e6db74 }div.highlight .s2 { color: #e6db74 }div.highlight .se { color: #ae81ff }div.highlight .sh { color: #e6db74 }div.highlight .si { color: #e6db74 }div.highlight .sx { color: #e6db74 }div.highlight .sr { color: #e6db74 }div.highlight .s1 { color: #e6db74 }div.highlight .ss { color: #e6db74 }div.highlight .bp { color: #f8f8f2 }div.highlight .vc { color: #f8f8f2 }div.highlight .vg { color: #f8f8f2 }div.highlight .vi { color: #f8f8f2 }div.highlight .il { color: #ae81ff }</style>
</style>
<body>#{code}</body>
</html>
EOT

File.open( file_path, 'w' ) do |file|
	file.write html
end

driver = Selenium::WebDriver.for :firefox
driver.navigate.to "file://#{file_path}"
driver.save_screenshot(image_path)
driver.close

File.delete file_path

# usage imagize.rb /path/to/code/file.rb
#result is similar to :
# http://imgur.com/HYknU7c                
                    Simple fuzzy search algorithm similar to sublimeText

this is a simple algorithm to give a similar result
as SublimeText search feature, if you don't use sublimeText
i think you should just give it a shot from here :
http://www.sublimetext.com

to know more about fuzzy search you should check this wiki page:
http://en.wikipedia.org/wiki/Fuzzy_string_searching

the idea is simple, when you search for a text and you can't remember
only part of it or you miss some characters while typing the search should
be smart enough to show you what you're searching for, so your algorithm
should search for the query characters and allow any character to 
be followed by any other character sequence.

after you get strings that contain your query the fuzzy why,
you should rank them, i choose the simple one, if you found your
exact query your matching pattern will be the least of them in length
and if another patter has query plus one character you missed it
will be the second in search, and so on.

so i sorted ascending order by the matching pattern length.

a smarter algorithm should check if there are 2 matching and get the best one
also should check if you wrote a wrong character, and if you switched two characters
and so on of the operations mentioned in wikipedia.                
                    require 'gosu'
$width, $height = 200, 200
$number_of_particles = 200

class Quad
  def initialize
    @pos = {x:rand($width), y:rand($width)}
    @vel = { x:(rand(5)+1)*[1,-1].sample, y:(rand(5)+1)*[1,-1].sample }
    @size = rand(4)*[1,-1].sample
    @color = [  Gosu::Color::GRAY, Gosu::Color::WHITE,
                Gosu::Color::AQUA, Gosu::Color::RED,
                Gosu::Color::GREEN, Gosu::Color::BLUE,
                Gosu::Color::YELLOW, Gosu::Color::FUCHSIA,
                Gosu::Color::CYAN ].sample
  end
  def update
    @vel[:x] = @vel[:x] * -1 if @pos[:x] <= 0 or @pos[:x] >= $width
    @vel[:y] = @vel[:y] * -1 if @pos[:y] <= 0 or @pos[:y] >= $height
    @pos[:x] += @vel[:x]
    @pos[:y] += @vel[:y] 
  end
  def draw win
    win.draw_quad @pos[:x]-@size, @pos[:y]-@size, @color,
                  @pos[:x]+@size, @pos[:y]-@size, @color,
                  @pos[:x]+@size, @pos[:y]+@size, @color,
                  @pos[:x]-@size, @pos[:y]+@size, @color
  end
end

class GameWindow < Gosu::Window
  def initialize
    super $width, $height, false
    self.caption = "Quads"
    @quads = []
    $number_of_particles.times { @quads << Quad.new }
  end
  def update
    @quads.each {|q| q.update }
  end
  def draw
    color = Gosu::Color::WHITE
    draw_quad 0, 0, color, $width, 0, color, $width, $height, color, 0, $height, color
  	@quads.each { |q| q.draw self }
  end
end

window = GameWindow.new
window.show                
                    // Java code for for Managing TextFragment in FloatingBox

// Instantiate Document object
Document doc = new Document();
// Add page to PDF document
Page page = doc.getPages().add();
// Create FloatingBox object
FloatingBox aBox = new FloatingBox(40, 60);
// Set left position for FloatingBox
aBox.setLeft(40);
// Set Top position for FloatingBox
aBox.setTop(80);
// Set the vertical alignment for FloatingBox
aBox.setVerticalAlignment(com.aspose.pdf.VerticalAlignment.Bottom);
// Set Horizontal alignment for FloatingBox
aBox.setHorizontalAlignment(com.aspose.pdf.HorizontalAlignment.Center);
// Add text fragment to paragraphs collection of FloatingBox
aBox.getParagraphs().add(new TextFragment("main text"));
// Set border for FloatingBox
aBox.setBorder(new BorderInfo(15 /*BorderSide.Box*/));
// Set background color for FloatingBox
aBox.setBackgroundColor(com.aspose.pdf.Color.getYellow());
// Add FloatingBox to paragraphs collection of page object
page.getParagraphs().add(aBox);
// Set background of PDF page
page.setBackground(com.aspose.java.awt.Color.LIGHT_GRAY);
// Save the PDF document
doc.save(Environment.getExternalStorageDirectory().getAbsolutePath()+"/FloatingBox.pdf");

// Java code for Adding Table inside FloatingBox

// Instantiate Document object
Document doc = new Document();
// Add page to PDF document
Page page = doc.getPages().add();
// Create FloatingBox object
FloatingBox aBox = new FloatingBox(200, 100);
// Trim the contents exceeding FloatingBox dimensions
aBox.isExtraContentClip(true);
// Specify if you need to repeat the FloatingBox
aBox.isNeedRepeating(false);
// Set left position for FloatingBox
aBox.setLeft(40);
// Set top position for FloatingBox
aBox.setTop(80);
// Set the vertical alignment for FloatingBox
aBox.setVerticalAlignment(com.aspose.pdf.VerticalAlignment.Bottom);
// Set horizontal alignment for FloatingBox
aBox.setHorizontalAlignment(com.aspose.pdf.HorizontalAlignment.Center);
// Set border for FloatingBox
aBox.setBorder(new BorderInfo(15 /*BorderSide.Box*/, com.aspose.pdf.Color.getBlack()));
// Set background color for FloatingBox
aBox.setBackgroundColor(com.aspose.pdf.Color.getYellow());
// Add FloatingBox to paragraphs collection of page object
page.getParagraphs().add(aBox);

// Instantiate Table object
com.aspose.pdf.Table table = new com.aspose.pdf.Table();
// Set width of table columns
table.setColumnWidths("100 100");

// Create a loop object
for (int i = 1; i <= 20; i++)
{
    // Create a new row object and add it to table object
    Row row = table.getRows().add();
    // Add cell to cells collection of newly added row object
    row.getCells().add("Columns 1, line " + i);
    // Add another cell object
    row.getCells().add("Columns 2, line " + i);
}
// Add table to paragraphs collection of FloatingBox
aBox.getParagraphs().add(table);
// Save the PDF document
doc.save(Environment.getExternalStorageDirectory().getAbsolutePath()+"/FloatingBox.pdf");
                
                    #!/usr/bin/env ruby
# gem install sinatra --no-document
# gem install github-markdown --no-document
require 'sinatra'
require 'github/markdown' 
set :port, 3000

get '/' do
<<-EOT
	<!DOCTYPE html>
	<html>
	<head>
		<meta charset="utf-8">
		<title>Markdown tester</title>
	</head>
	<body>
		<textarea id="markdown" style="width:100%;height:300px;"></textarea>
		<div id="preview" ></div>
		<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
		<script type="text/javascript">
		$('#markdown').keyup(function(){
			$.post('/preview', {md:$('#markdown').val()}, function(response){
				$('#preview').html(response);
			});
		});
		</script>
	</body>
	</html>
EOT
end

post '/preview' do
	GitHub::Markdown.render_gfm params['md']
end
                
                    #!/usr/bin/env ruby
# generate a single sentence from a canonical form
# canonical sentence is a multi sentences combined in one
# form, generator will generate a sentence from it randomly
# based on the form, for example:
# "Hello [Emad|Elsaid]" , may generate "Hello Emad" or
# "Hello Elsaid" the result is random.
# also you could nest [] inside each other to gain a multi level
# canonical sentence example:
# "[[Hi|Hello] [Emad|elsaid] | good [morning|night] sir]"
def generate(result)
	while result.include? '[' 
		s_start = result.index '['
		s_end = s_start+1
		while s_end<result.length and result[s_end]!=']'
			s_start = s_end if result[s_end] == '['
			s_end += 1
		end
		sentence = result[(s_start+1)...s_end]
		sentence = sentence.split '|'
		result = result[0...s_start] + sentence.sample + result[s_end+1...result.length]
	end
	result
end

10.times do
	puts generate '[Hello|Hi] my [friend|dear], how [are you [today|these days]|is your brother]?'
end

# Hello my friend, how is your brother?
# Hi my dear, how is your brother?
# Hello my dear, how is your brother?
# Hello my dear, how is your brother?
# Hi my friend, how is your brother?
# Hi my friend, how is your brother?
# Hello my friend, how are you these days?
# Hello my friend, how is your brother?
# Hello my friend, how are you these days?
# Hi my friend, how is your brother?                
                    #!/usr/bin/env ruby
require 'digest/md5'
require "addressable/uri"

# this is based on gravatar image API
# https://en.gravatar.com/site/implement/images/
# options :
# size : <integer> size of image
# default: <string> url of image if email not found or:
#  * 404
#  * mm
#  * identicon
#  * monsterid
#  * wavatar
#  * retro
#  * blank
# forcedefault: "y" force default image to load
# rating: <string> one of the values : g, pg, r, x
def gravatar email, *options
	email_md5 = Digest::MD5.hexdigest email
	unless options.empty?
		params = Addressable::URI.new
		params.query_values = options.first
		params_query = "?#{params.query}"
	end
	"http://www.gravatar.com/avatar/#{email_md5}#{params_query}"
end


puts gravatar('blazeeboy@gmail.com')
puts gravatar(
	'blazeeboy@gmail.com', 
	size: 200, 
	default: 'https://pbs.twimg.com/media/BheUcQMIAAA0Gns.jpg:large'
	)
                
                    #!/usr/bin/env ruby
require 'mail' # gem install mail --no-document

# Credit to : 
# http://stackoverflow.com/questions/12884711/how-to-send-email-via-smtp-with-rubys-mail-gem

def ask question
  print "#{question} ? : "
  $stdin.gets.chomp!
end

# get it from : 
# https://www.tumblr.com/settings/blog/yourBlogName
# in the Post by Email section
tumblr_email = 'xxxxxxx@tumblr.com'

email = ask('what is your gmail address')

$options = { 
	:address              => "smtp.gmail.com",
  :port                 => 587,
  :domain               => email,
  :user_name            => email,
  :password             => ask('what is your password'),
  :authentication       => 'plain',
  :enable_starttls_auto => true  
}

Mail.defaults do
  delivery_method :smtp, $options
end


Mail.deliver do
  from     $options[:user_name]
  to       tumblr_email
  body     ask('write any message associated with the image')
  ARGV.each do |file|
    add_file file
  end
end

puts 'Posting to tumblr succeeded :)'
                
                    #!/usr/bin/env ruby

# Credits to :
# http://stackoverflow.com/questions/16365553/creating-gist-from-a-ruby-script
# i modified the script alittle bit to read files from params
require 'net/http'
require 'json'


uri = URI("https://api.github.com/gists")

files = {}
ARGV.each do |f|
	files[f] = {
		content: File.read(f)
	}
end

payload = {
  'public' => true,
  'files' => files
}

req = Net::HTTP::Post.new(uri.path)
req.body = payload.to_json

puts req.inspect
puts req.body.inspect

# GitHub API is strictly via HTTPS, so SSL is mandatory
res = Net::HTTP.start(uri.hostname, uri.port, :use_ssl => true) do |http|
  http.request(req)
end

response = JSON.parse res.body
puts response['html_url']