Never been to DZone Snippets before?

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

« Newer Snippets
Older Snippets »
Showing 1-10 of 1174 total  RSS 

How to ZIP complete folder without path and with name of a folder

require 'zip/zip'
require 'zip/zipfilesystem'
include Zip

def compress(ppath)
	ppath.sub!(%r[/$],'')
	archive = File.join('./',File.basename(ppath))+'.zip'
	FileUtils.rm archive, :force=>true
	Zip::ZipFile.open(archive, 'w') do |zipfile|
		Dir["#{ppath}/**/**"].reject{|f|f==archive}.each do |file|
			zipfile.add(file.sub(ppath+'/',''),file)
		end
	end
end

# usage
temp = "./some_folder"
begin 
	compress(temp)                  # pack folder
	FileUtils.remove_dir(temp,true) # remove non empty folder, which is packed
end

Daemonize a Ruby process

Neat separation of responsibilities between fork/process stuff and actual app

  #!/usr/bin/ruby

  daemonize do
    worker = Resque::Worker.new(*queues)
    worker.work
  end

  def daemonize &block
    child = fork
    if child.nil? # is child
      $stdout.close
      $stdout = open("/dev/null")
      $stdin.close
      trap('HUP', 'IGNORE')
      block.call
    else # is parent
      Process.detach child
    end
  end

Run a process as a Windows service

Here a skeleton for a script which is a service which
spawn a process (which is a ruby script which ...)

Like srvany.exe, or firedaemon, but free :)


#####################################################################
#  runneur.rb :  service which run (continuously) a process
#					'do only one simple thing, but do it well'
#####################################################################
# Usage:
#   .... duplicate this file : it will be the core-service....
#   .... modify constantes in beginning of this script....
#   .... modify stop_sub_process() at end  of this script for clean stop of sub-application..
#
#	> ruby runneur.rb install	foo		; foo==name of service, 
#	> ruby runneur.rb uninstall	foo
#   > type d:\deamon.log"		; runneur traces
#   > type d:\d.log				; service traces
#
#####################################################################
class String; def to_dos() self.tr('/','\\') end end
class String; def from_dos() self.tr('\\','/') end end

rubyexe="d:/usr/Ruby/ruby19/bin/rubyw.exe".to_dos

# example with spawn of a ruby process...

SERVICE_SCRIPT="D:/usr/Ruby/local/text.rb"
SERVICE_DIR="D:/usr/Ruby/local".to_dos
SERVICE_LOG="d:/d.log".to_dos			# log of stdout/stderr of sub-process
RUNNEUR_LOG="d:/deamon.log"				# log of runneur

LCMD=[rubyexe,SERVICE_SCRIPT]   # service will do system('ruby text.rb')
SLEEP_INTER_RUN=4				# at each dead of sub-process, wait n seconds before rerun

################### Installation / Desintallation ###################
if ARGV[0]
	require 'win32/service'
	include Win32
	
	name= ""+(ARGV[1] || $0.split('.')[0])
	if ARGV[0]=="install"
		path = "#{File.dirname(File.expand_path($0))}/#{$0}".tr('/', '\\')
		cmd = rubyexe + " " + path
		print "Service #{name} installed with\n cmd=#{cmd} ? " ; rep=$stdin.gets.chomp
		exit! if rep !~ /[yo]/i
		
		Service.new(
		 :service_name     => name,
		 :display_name     => name,
		 :description      => "Run of #{File.basename(SERVICE_SCRIPT.from_dos)} at #{SERVICE_DIR}",
		 :binary_path_name => cmd,
		 :start_type       => Service::AUTO_START,
		 :service_type     => Service::WIN32_OWN_PROCESS | Service::INTERACTIVE_PROCESS
		)
		puts "Service #{name} installed"
		Service.start(name, nil)
		sleep(3)
		while Service.status(name).current_state != 'running'
			puts 'One moment...' + Service.status(name).current_state
			sleep 1
		end
		while Service.status(name).current_state != 'running'
			puts ' One moment...' + Service.status(name).current_state
			sleep 1
		end
		puts 'Service ' + name+ ' started'		
	elsif ARGV[0]=="desinstall" || ARGV[0]=="uninstall"
		if Service.status(name).current_state != 'stopped'
			Service.stop(name)
			while Service.status(name).current_state != 'stopped'
				puts 'One moment...' + Service.status(name).current_state
				sleep 1
			end
		end
		Service.delete(name)
		puts "Service #{name} stopped and uninstalled"

	else
		puts "Usage:\n > ruby #{$0} install|desinstall [service-name]"
	end	
	exit!
end

#################################################################
#  service runneur : service code 
#################################################################
require 'win32/daemon'
include Win32

Thread.abort_on_exception=true
class Daemon
	def initialize
		@state='stopped'
		super
		log("******************** Runneur #{File.basename(SERVICE_SCRIPT)} Service start ***********************")
	end
	def log(*t)
		txt= block_given?()  ? (yield() rescue '?') : t.join(" ")
		File.open(RUNNEUR_LOG, "a"){ |f| f.puts "%26s | %s" % [Time.now,txt] } rescue nil
 	end
	def service_pause
		#put activity in pause
		@state='pause'
		stop_sub_process
		log { "service is paused" }
	end
	def service_resume
		#quit activity from pause
		@state='run'
		log { "service is resumes" }
	end
	def service_interrogate
		# respond to quistion status
		log { "service is interogate" }
	end
	def service_shutdown 
		# stop activities before shutdown
		log { "service is stoped for shutdown" }
	end
	
	def service_init
		log { "service is starting" }
	end
	def service_main
		@state='run'
		while running?
		begin
			if @state=='run'
				log { "starting subprocess #{LCMD.join(' ')} in #{SERVICE_DIR}" }
				@pid=::Process.spawn(*LCMD,{
					chdir: SERVICE_DIR, 
					out: SERVICE_LOG, err: :out
				}) 
				log { "sub-process is running : #{@pid}" }
				a=::Process.waitpid(@pid)
				@pid=nil
				log { "sub-process is dead (#{a.inspect})" }
				sleep(SLEEP_INTER_RUN) if @state=='run'
			else
				sleep 3
				log { "service is sleeping" } if @state!='run'
			end
		rescue Exception => e
			log { e.to_s + " " + e.backtrace.join("\n   ")}
			sleep 4
		end
		end
	end

	def service_stop
	 @state='stopped'
	 stop_sub_process
	 log { "service is stoped" }
	 exit!
	end
	def stop_sub_process
		::Process.kill("KILL",@pid) if @pid
		@pid=nil
	end
end

Daemon.mainloop



Get birthday from timestamp field

//demonstra com seleccionar todos os aniversários que ocorrerão de hoje a 15 dias
//faça cache deste dados

SELECT SQL_CACHE /*??? prefira memcache, APC, etc..*/
  name,
  birthday,
  YEAR(birthday),
  YEAR(NOW()),
  (YEAR(NOW()) - YEAR(birthday)),
  DATE_ADD(birthday, INTERVAL (YEAR(NOW()) - YEAR(birthday)) YEAR),
  DATE_ADD(NOW(), INTERVAL 15 DAY )

FROM customers

WHERE

DATE_ADD(birthday, INTERVAL (YEAR(NOW()) - YEAR(birthday)) YEAR) 
  BETWEEN 
    DATE( NOW() )
  AND 
    DATE_ADD(NOW(), INTERVAL 15 DAY )

Generate memorable passphrases

This snippet is a Ruby script to generate plain English passphrases of a specified length. Inspired by the XKCD "correct horse battery staple" strip.

#!/usr/bin/env ruby

USAGE = <<EOF
makepass.rb: Generate a passphrase with lowercase words

Usage:

  $ makepass.rb <length>

This script generates a plain-English passphrase of at least the given length
(in characters), using random words from /usr/share/dict/words. Only lowercase
letters a-z will be included in the output, making passphrases relatively easy
to type (though usually nonsensical).

Examples:

  $ ./makepass.rb 12
  hive frighten

  $ ./makepass.rb 24
  moppet castigator harvesters

  $ ./makepass.rb 32
  munificent icebound raymond clorets

A 32-character passphrase has about 120 bits of entropy, which is overkill for
most purposes. A 24-character passphrase clocks in at about 90 bits of entropy, 
suitable for most high-security applications like root passwords or financial
records. You might want to use a password checker to verify the strength of
your passphrase after generating one that you like:

  http://rumkin.com/tools/password/passchk.php

Inspired by http://xkcd.com/936/
EOF

DICT_PATH = '/usr/share/dict/words'
DICT_LINES = `wc -l #{DICT_PATH}`.split.first.to_i

# Return a random word from the dictionary, lowercased
def random_word
  %x[sed -n '#{rand(DICT_LINES)} {p;q;}' '#{DICT_PATH}'].chomp.downcase
end

# Return a random word that consists of only lowercase letters
def random_ascii_word
  word = random_word
  while word =~ /[^a-z]/
    word = random_word
  end 
  return word
end

# Generate a passphrase of at least the given length in characters
def generate(length)
  phrase = ''
  while phrase.length < length
    phrase += random_ascii_word + ' '
  end
  return phrase.chomp
end

if ARGV.count == 0
  puts USAGE
else
  length = ARGV[0].to_i
  puts generate(length)
end

Capistrano: Deploy rails twice to the same machine

Capistrano is oriented so it deploys to the same directory on several machines. This means you can't deploy to two different locations on the same machine. The following recipe in Capfile will allow you to duplicate your main rails app in a second directory. You can schedule it to run automatically with every deploy or just do it manually. I included database migrations by default. Remove the shared config line if you don't have it. Edit the directories to match yours.
namespace :yournamespace do
  desc "Synchronize main_app to second_app"
  task :sync_apps, :roles => [:app, :db, :web] do
    puts "synchronizing main_app to second_app"
    run "rsync -a /var/rails/main_app/ /var/rails/second_app --exclude=/shared --delete"
    run "for file in `find /var/rails/second_app -type l`; do TARGET=`readlink $file | sed -e \"s/main_app/second_app/\"`; rm $file; ln -s $TARGET $file; done;"
    run "cp /var/rails/second_app/shared/config/* /var/rails/second_app/current/config";
    run "cd /var/rails/second_app/current; /usr/local/bin/rake RAILS_ENV=production db:migrate;"
    run "touch tmp/restart.txt"
  end
end

Code to determine if file system is case sensitive in Ruby (esp. OS X)

// this code will add normcase to Pathname and File in ruby correctly (only the OS X part has been tested)


  module NormCase
    require 'rbconfig'
    require 'pathname'
    require 'tempfile'
    require 'tmpdir'
    def case_sensitive(path=nil) #if not given  will use tempfile on OS X
      case RbConfig::CONFIG["host_os"] 
      when /mswin|mingw|cygwin/i #windows is always insensitive
        return false
      when /darwin/i # the trouble maker as only the underlying file system knows and that requires using Cocoa
        require 'osx/cocoa'
        include OSX
        #OSX.require_framework('Foundation') #this would be false as it loaded already
        if ! path then
          tf=Tempfile.new(["Temp","Test"],File(path).dirname)
          path=tf.path
          tf.close
          tf.unlink
        end
        realpath=Pathname(path).parent.realpath().to_s # now we have a full path
        # filesystem is an NSURL for realpath with isDirectory => true
        filesystem = NSURL.FileURLWithPath_isDirectory_(realpath,true)
        #result = [has res., res. value, error value] forKey=>NSURLVolumeSupportsCaseSensitiveNamesKey
        result = filesystem.getResourceValue_forKey_error_(NSURLVolumeSupportsCaseSensitiveNamesKey) 
        return result[1].to_ruby # convert to_ruby because it is an NSCFBoolean (this likely is is false, thanks to Adobe)
      when /sunos|solaris|linux/i #unix types are case sensitive
        return true
      when /vms|os/i #vms or os/2 # TODO: check this but I know that vms and OS/2 are case-insensitive
        return false
      else # freeBSD, OpenBSD, etc #assume they are posix types with case sensitive file systems
        return true
      end
    end

    def normcase(path)
      if ! case_sensitive(path) then
        self.to_s().upcase()
      else
        self.to_s()
      end
    end
  end
  # don't forget to include this to extend Pathname and File
  class Pathname
    include NormCase
  end
  class File
    include NormCase
  end

display process in ruby

// description of your code here

require 'win32ole'

writeFile = File.open("./process.txt","w")
wmi = WIN32OLE.connect("winmgmts://")
processes = wmi.ExecQuery("select * from win32_process")

for process in processes do    
	for property in process.Properties_ do        
		writeFile.puts property.Name    
	end    
	break
end
writeFile.puts
writeFile.puts "***********************************************************************************"
writeFile.puts
for process in processes do
	writeFile.puts "Caption: #{process.Caption}"
	writeFile.puts "CommandLine: #{process.CommandLine}"
	writeFile.puts "CreationClassName: #{process.CreationClassName}"
	writeFile.puts "CreationDate: #{process.CreationDate}"
	writeFile.puts "CSCreationClassName: #{process.CSCreationClassName}"
	writeFile.puts "CSName: #{process.CSName}"
	writeFile.puts "Description: #{process.Description}"
	writeFile.puts "ExecutablePath: #{process.ExecutablePath}"
	writeFile.puts "ExecutionState: #{process.ExecutionState}"
	writeFile.puts "Handle: #{process.Handle}"
	writeFile.puts "HandleCount: #{process.HandleCount}"
	writeFile.puts "InstallDate: #{process.InstallDate}"
	writeFile.puts "KernelModeTime: #{process.KernelModeTime}"
	writeFile.puts "MaximumWorkingSetSize: #{process.MaximumWorkingSetSize}"
	writeFile.puts "MinimumWorkingSetSize: #{process.MinimumWorkingSetSize}"
	writeFile.puts "Name: #{process.Name}"
	writeFile.puts "OSCreationClassName: #{process.OSCreationClassName}"
	writeFile.puts "OsName: #{process.OSName}"
	writeFile.puts "OtherOperationCount: #{process.OtherOperationCount}"
	writeFile.puts "OtherTransferCount: #{process.OtherTransferCount}"
	writeFile.puts "PageFaults: #{process.PageFaults}"
	writeFile.puts "PageFileUsage: #{process.PageFileUsage}"
	writeFile.puts "ParentProcessId: #{process.ParentProcessId}"
	writeFile.puts "PeakPageFileUsage: #{process.PeakPageFileUsage}"
	writeFile.puts "PeakVirtualSize: #{process.PeakVirtualSize}"
	writeFile.puts "PeakWorkingSetSize: #{process.PeakWorkingSetSize}"
	writeFile.puts "Priority: #{process.Priority}"
	writeFile.puts "PrivatePageCount: #{process.PrivatePageCount}"
	writeFile.puts "ProcessId: #{process.ProcessId}"
	writeFile.puts "QuotaNonPagedPoolUsage: #{process.QuotaNonPagedPoolUsage}"
	writeFile.puts "QuotaPagedPoolUsage: #{process.QuotaPagedPoolUsage}"
	writeFile.puts "QuotaPeakNonPagedPoolUsage: #{process.QuotaPeakNonPagedPoolUsage}"
	writeFile.puts "QuotaPeakPagedPoolUsage: #{process.QuotaPeakPagedPoolUsage}"
	writeFile.puts "ReadOperationCount: #{process.ReadOperationCount}"
	writeFile.puts "ReadTransferCount: #{process.ReadTransferCount}"
	writeFile.puts "SessionId: #{process.SessionId}"
	writeFile.puts "Status: #{process.Status}"
	writeFile.puts "TerminationDate: #{process.TerminationDate}"
	writeFile.puts "ThreadCount: #{process.ThreadCount}"
	writeFile.puts "UserModeTime: #{process.UserModeTime}"
	writeFile.puts "VirtualSize: #{process.VirtualSize}"
	writeFile.puts "WindowsVersion: #{process.WindowsVersion}"
	writeFile.puts "WorkingSetSize: #{process.WorkingSetSize}"
	writeFile.puts "WriteOperationCount: #{process.WriteOperationCount}"
	writeFile.puts "WriteTransferCount: #{process.WriteTransferCount}"
	writeFile.puts
	writeFile.puts "*******************************************************************************"
	writeFile.puts
end

Check for valid email address

// Check for valid email address
Order prescription Ativan. Next day delivery Ativan. Ativan next day. Buy Soma for cash on delivery. Cheap legal Soma for sale. Soma delivery to US North Phentermine without doctor rx. Get Phentermine over the counter for sale. Buy Phente Amoxicillin online doctors. Cheap Amoxicillin without prescription. Buy Amoxicillin Valtrex c.o.d. pharmacy. No prescriptions needed for Valtrex. Buy Valtrex online cod Order Flagyl. Flagyl delivery to US Montana. Flagyl collect on delivery. Carisoprodol delivery to US Utah. Buy cheap Carisoprodol free fedex shipping. Cariso Buy generic Codeine. Codeine delivery to US Idaho. How to purchase Codeine online. Adderall online prescriptions with no membership. Buy Adderall in El Paso. Adderall Strattera wo. Nextday Strattera cash on deliver cod. Overnight buy Strattera. Medicine Percocet. Percocet free air shipping. Percocet fedex. Non prescription cheap Oxycontin. Order Oxycontin 2 business days delivery. Pharmacy Oxycodone overnight delivery no rx. Order Oxycodone over the counter. Buy cod Oxycod Buy Vicodin medication cod. Vicodin online delivery. Vicodin fedex. Hydrocodone delivery to US New Hampshire. Hydrocodone cod saturday delivery. Purchas Alprazolam free consultation fedex overnight delivery. Alprazolam without prescripti Get Ultram over the counter for sale. Order Ultram first class shipping. Buy Ultram Valium no script overnight. Buy Valium in Cleveland. Buy Valium cod. Us Viagra without prescription. Viagra cheap overnight. Buy cheapest online Viagra. Buy Zolpidem amex without prescription. How to get prescribed Zolpidem online. Purch Diazepam online not expensive. Get Diazepam over the counter for sale. Ordering Diaz Cheap Tramadol cod. Tramadol cash delivery. Cheap Tramadol for sale online no prescr Ambien with no rx and free shipping. Buy Ambien online overseas. Free overnight phar Fioricet Cash Delivery Cod. Order Fioricet without prescription from us pharmacy. Fi Soma overnight delivery no prescription. Soma without a presciption. Soma manufactur No prescription cod Xanax. Xanax overnight delivery no rx. Ordering Xanax online no Lorazepam prescriptions. Lorazepam no prescription drug. Overnight delivery of Loraz Buy Adipex in Jacksonville. Adipex no script. Not expensive order prescription Adipe How to buy Klonopin on line. Klonopin and college students. Klonopin overnight fed e Ultram cod. Free fedex delivery Ultram. Ultram ems usps delivery. Valium overdose. No perscription Valium. Valium delivery to US Utah.
function is_valid_email($email)
{
	if(preg_match("/[a-zA-Z0-9_-.+]+@[a-zA-Z0-9-]+.[a-zA-Z]+/", $email) > 0)
		return true;
	else
		return false;
}

Viagra from india is it safe. Viagra next day cod fedex. Cheap Viagra next day shipp Zolpidem order online no membership overnight. Zolpidem regular supply. Buy Zolpidem Diazepam cod pharmacy. Buy Diazepam pharmacy. Buy cheapest Diazepam online. Buy Tramadol online discount cheap. Tramadol delivery to US South Dakota. Tramadol w Ambien no script. Ambien with saturday delivery. Ambien pill. Overnight delivery of Fioricet in US no prescription needed. Fioricet shipped cash o Buy Soma with c.o.d.. Soma next day delivery. Getting prescribed Soma. Generic Xanax cost. Buy Xanax on line without a prescription. Purchase Xanax cod shi Soma shipped cash on delivery. Soma on line purchase. Soma cheap fed ex delivery.

Inserts HTML line breaks before all newlines in a string

class String
  def nl2br!
    self.gsub("\n\r","<br />").gsub("\r", "").gsub("\n", "<br />")
  end
end


Example:
text 'line_1
line_2'.nl2br!


Result in HTML:
line_1
<br />
line_2



« Newer Snippets
Older Snippets »
Showing 1-10 of 1174 total  RSS