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

                    function prime($n){
 
      //all numbers that will be evaluated as prime       
     for($i=1;$i<=$n;$i++){     
               $counter = 0; 
              //all probability of divisible factors
              for($j=1;$j<=$i;$j++){                   
                    //$i is divisible by $j, increament the counter
                     if($i % $j==0){                       
                          $counter++;
                    }
              }          
           /*how many greens? they have to be 2 
            ( each prime number has exactly 2 (two) divisors)*/
             if($counter==2){
                 print $i." is Prime <br/>";
             }
      }
} 


prime(20);  //find the Prime for 1-20 range                
                    #!/usr/bin/env ruby
# Author : Emad Elsaid (https://github.com/blazeeboy)
require 'linkedin' # gem install linkedin
require 'json'

# create an appliation then
# get your api keys at https://www.linkedin.com/secure/developer
config = {
	your_consumer_key: 		'xxxxxxxxxxxxxxxx',
	your_consumer_secret: 	'xxxxxxxxxxxxxxxx',
	oauth_user_token: 		'xxxxxxxxxxxxxxxx',
	oauth_user_secret: 		'xxxxxxxxxxxxxxxx'
}
client = LinkedIn::Client.new(
						config[:your_consumer_key], 
						config[:your_consumer_secret] 
					)

client.authorize_from_access(
		config[:oauth_user_token],
		config[:oauth_user_secret]
	)

client.add_share(
	comment: 'Good Morning', 
	content: {'submitted-url' => 'http://www.github.com/blazeeboy' }
)                
                    //The programming sample below shows how to DXF Drawings to PDF file using default settings.

 [C# Code Sample]

using Aspose.Imaging.FileFormats.Cad;
using Aspose.Imaging.ImageOptions;

namespace DxfExamples
{
    /// <summary>
    /// Represents test examples for DXF -> PDF export
    /// </summary>
    public class DxfExamples
    {
        /// <summary>
        /// Default export.
        /// </summary>
        public void DefaultExport()
        {
            // Name of the file
            string filename = "Drawing1.dxf";

            // Load an image
            using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(filename))
            {
                // Create options
                PdfOptions pdfOptions = new PdfOptions();

                // Set output file size
                pdfOptions.PageWidth = 800;
                pdfOptions.PageHeight = 600;

                // Export
                image.Save(filename + ".pdf", pdfOptions);
            }
        }
    }
}

//[VB.NET Code Sample]

Imports Aspose.Imaging.FileFormats.Cad
Imports Aspose.Imaging.ImageOptions

Namespace DxfExamples
        ''' <summary>
        ''' Represents test examples for DXF -> PDF export
        ''' </summary>
        Public Class DxfExamples
            ''' <summary>
            ''' Default export.
            ''' </summary>
            Public Sub DefaultExport()
                ' Name of the file
                Dim filename As String = "Drawing1.dxf"

                ' Load an image
                Using image As Aspose.Imaging.Image = Aspose.Imaging.Image.Load(filename)
                    ' Create options
                    Dim pdfOptions As New PdfOptions()

                    ' Set output file size
                    pdfOptions.PageWidth = 800
                    pdfOptions.PageHeight = 600

                    ' Export
                    image.Save(filename & Convert.ToString(".pdf"), pdfOptions)
                End Using
            End Sub
        End Class
    End Namespace

//Setting the Image Size

//[C# Code Sample]

//The code sample below shows the auto-scaling option in use.
using Aspose.Imaging.FileFormats.Cad;
using Aspose.Imaging.ImageOptions;

namespace DxfExamples
{
    /// <summary>
    /// Represents test examples for DXF -> PDF export
    /// </summary>
    public class DxfExamples
    {
/// <summary>
        /// Export with automatical up-scaling.
        /// </summary>
        public void ExportAutoUpScale()
        {
            // Name of the file
            string filename = "Drawing2.dxf";

            // Load an image
            using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(filename))
            {
                // Create options
                PdfOptions pdfOptions = new PdfOptions();

                // Set output file size
                pdfOptions.PageWidth = 850;
                pdfOptions.PageHeight = 600;

                // Allow upscaling
                pdfOptions.ScaleMethod = ScaleType.GrowToFit;

                // Export
                image.Save(filename + "_UpScale.pdf", pdfOptions);
            }
        }
    }
}

//[VB.NET Code Sample]

Imports Aspose.Imaging.FileFormats.Cad
Imports Aspose.Imaging.ImageOptions

Namespace DxfExamples
	''' <summary>
	''' Represents test examples for DXF -> PDF export
	''' </summary>
	Public Class DxfExamples
		''' <summary>
		''' Export with automatical up-scaling.
		''' </summary>
		Public Sub ExportAutoUpScale()
			' Name of the file
			Dim filename As String = "Drawing2.dxf"

			' Load an image
			Using image As Aspose.Imaging.Image = Aspose.Imaging.Image.Load(filename)
				' Create options
				Dim pdfOptions As New PdfOptions()

				' Set output file size
				pdfOptions.PageWidth = 850
				pdfOptions.PageHeight = 600

				' Allow upscaling
				pdfOptions.ScaleMethod = ScaleType.GrowToFit

				' Export
				image.Save(filename & Convert.ToString("_UpScale.pdf"), pdfOptions)
			End Using
		End Sub
	End Class
End Namespace

                
                    #!/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