DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Latest Articles - DZone

article thumbnail
Active Record YAML Backup Solution - Drop In Rake Task And Config File To Backup Db And Directorys Of Your Choice (user Uploaded Files)
EZ drop in backup rake task for your rails projects - works well - 5 - 10 min set up, one rake file and one config file backs up db and any directory's to any number of servers with rsync BSD License or whatever, but it would be cool if you told me your using it 2007 ISS http://industrialstrengthinc.com this is a sample config file and a rake task you can drop into any rails project to do backups, easy to automate. Backs up your specified environment db to activerecord yml files (one per table) and zips them up in a human readable timestamped file syncs that and any other set of arbitrary directory's to any number of arbitrary servers with rsync be sure to set ssh key based logins to run: rake backup also: rake backup:db, rake backup:restoredb (promts for a file created by backup:db), rake backup:push (to push out what u got) note: this uses something like 30 lines of code from some blog site I got it from that I cant recall, yay for that guy, thanks ## example crontab entry: 3 * * * * cd /rails_deployment_dir/current && nice rake backup RAILS_ENV=production >> /rails_deployment_dir/production_backup_system.log ## config file - goes in config/backup.yml production: dirs: - db/backups - public/uploaded_images servers: - name: backup server number 1 host: gridserver.com port: 22 user: [email protected] dir: /home/blah/backups - name: backup server two host: kradradio.com port: 22 user: kraduser dir: /home/kraduser/backups_from_my_rails_proj development: dirs: - db/backups - public/uploaded_images servers: - name: local self host: localhost port: 5222 user: oneman dir: /home/oneman/Documents/development_backup ## rake file lib/tasks/backup.rake desc "Backup Everything Specified in config/backup.yml" task :backup => [ "backup:db", "backup:push"] namespace :backup do RAILS_APPDIR = RAILS_ROOT.sub("/config/..","") def interesting_tables ActiveRecord::Base.connection.tables.sort.reject! do |tbl| ['schema_info', 'sessions', 'public_exceptions'].include?(tbl) end end desc "Push backup to remote server" task :push => [:environment] do FileUtils.chdir(RAILS_APPDIR) backup_config = YAML::load( File.open( 'config/backup.yml' ) )[RAILS_ENV] for server in backup_config["servers"] puts "Backing up #{RAILS_ENV} directorys #{backup_config['dirs'].join(', ')} to #{server['name']}" puts "Time is " + Time.now.rfc2822 + "\n\n" for dir in backup_config["dirs"] local_dir = RAILS_APPDIR + "/" + dir + "/" remote_dir = server['dir'] + "/" + dir.split("/").last + "/" puts "Syncing #{local_dir} to #{server['host']}#{remote_dir}" sh "/usr/bin/rsync -avz -e 'ssh -p#{server['port']} ' #{local_dir} #{server['user']}@#{server['host']}:#{remote_dir}" end puts "Completed backup to #{server['name']}\n\n" end end task :storedb => :environment do backupdir = RAILS_APPDIR + '/db/backup' FileUtils.mkdir_p(backupdir) FileUtils.chdir(backupdir) puts "Dumping database to activerecord yaml files in #{backupdir}" interesting_tables.each do |tbl| klass = tbl.classify.constantize puts "Writing #{tbl}..." File.open("#{tbl}.yml", 'w+') { |f| YAML.dump klass.find(:all).collect(&:attributes), f } end puts "Database Dumped.\n\n" end desc "Dump Current Environment Db to file" task :db => [:environment, :storedb ] do backupdir = RAILS_APPDIR + '/db/backup' archivedir = RAILS_APPDIR + '/db/backups' backup_filename = "#{RAILS_ENV}_db_backup_#{Time.now.strftime("%B.%d.%Y_at_%I.%M.%S%p_%Z")}.tar.bz2" FileUtils.mkdir_p(archivedir) puts "Archiving #{backupdir} yaml files to #{backup_filename}\n\n" `tar -C #{backupdir} -cjf #{backup_filename} *` `mv #{backup_filename} #{archivedir}` end desc "Restore Current Environment Db from a file" task :restoredb => [:environment] do backupdir = RAILS_APPDIR + '/db/backup' archivedir = RAILS_APPDIR + '/db/backups' print "Input a file to load into the db: #{archivedir}/" backup_filename = STDIN.gets.chomp puts "Loading backup file: #{backup_filename}" FileUtils.chdir(archivedir) `tar -xjf #{backup_filename}` `mv *.yml #{backupdir}` FileUtils.mkdir_p(backupdir) FileUtils.chdir(backupdir) interesting_tables.each do |tbl| puts "Clearing #{tbl} table.." ActiveRecord::Base.connection.execute "TRUNCATE #{tbl}" puts "Loading #{tbl} backup file..." table = YAML.load_file("#{tbl}.yml") if table.length > 0 && table.first.key?("id") highestid = 0 table.each do |fixture| if fixture["id"] > highestid highestid = fixture["id"] end end ActiveRecord::Base.connection.execute "SELECT setval('#{tbl}_id_seq',#{highestid})" puts "Setting #{tbl}_id sequence to #{highestid}" end #klass = tbl.classify.constantize ActiveRecord::Base.transaction do puts "Inserting #{table.length} values into #{tbl}" table.each do |fixture| ActiveRecord::Base.connection.execute "INSERT INTO #{tbl} (#{fixture.keys.join(",")}) VALUES (#{fixture.values.collect { |value| ActiveRecord::Base.connection.quote(value) }.join(",")})", 'Fixture Insert' end puts "#{tbl} table restored.\n\n" end end end end
November 16, 2007
by Snippets Manager
· 2,360 Views
article thumbnail
Convert Ruby Array To Ranges
# Array#to_ranges # Converts an array of values (which must respond to #succ) to an array of ranges. For example, # [3,4,5,1,6,9,8].to_ranges => [1,3..6,8..9] class Array def to_ranges array = self.compact.uniq.sort ranges = [] if !array.empty? # Initialize the left and right endpoints of the range left, right = self.first, nil array.each do |obj| # If the right endpoint is set and obj is not equal to right's successor # then we need to create a range. if right && obj != right.succ ranges << Range.new(left,right) left = obj end right = obj end ranges << Range.new(left,right) end ranges end end
October 19, 2007
by Bill Siggelkow
· 8,302 Views
article thumbnail
Include Text Files In C Source
This includes the contents of myfile.txt into the char array text. Note: This only works if ALL lines in the file are enclosed in "s. Wrong myfile.txt: Hello world Goodbye world Right myfile.txt: "Hello world" "Goodbyle world" "" char text[] = { #include "myfile.txt" }
October 1, 2007
by Snippets Manager
· 4,339 Views
article thumbnail
Ruby Random Numbers Of A Specific Length
// generate random numbers of a specific number of digits rand.to_s[2..10] #=> 8 digit long random number rand.to_s[2..6] #=> 4 digit long random number
September 21, 2007
by Snippets Manager
· 11,209 Views
article thumbnail
Javascript Sprintf
September 19, 2007
by Snippets Manager
· 535 Views
article thumbnail
DOM Mouse-Over Element Selection And Isolation
DOM ISO.v.0.3.0.7.bookmarklet.js bookmarklet for selecting and isolating an element on a page. two sections: section 1: Mouseover DOM, setup and handle mouse events and show information about element in informational div. Click to select, Any key to cancel. section 2: Element Isolation with help of XPath. prompt user for XPath expression e.g., //DIV[@id='post-body']. then use XPath to select all elements not(ancestor or descendant or self), then delete those elements. also ignore self-or-descendants of head and title. tools: Ruderman's javascript development environment: https://www.squarefree.com/bookmarklets/webdevel.html#jsenv Mielczarek's js to bookmarklet generator: http://ted.mielczarek.org/code/mozilla/bookmarklet.html (function() { //GLOBALS //globals for classMausWork var gSelectedElement; //currently only one selection var gHoverElement; //whatever element the mouse is over var gHovering=false; //mouse is over something var gObjArrMW=[]; //global array of classMausWork objects. for removing event listeners when done selecting. //extended var infoDiv; //currently just container for InfoDivHover, might add more here var infoDivHover; //container for hoverText text node. var hoverText; //show information about current element that the mouse is over //const EXPERIMENTAL_NEW_CODE=true; //debugging. new features. //START SetupDOMSelection(); //(Section 1) Element Selection function SetupDOMSelection() { { //setup event listeners //var pathx="//div | //span | //table | //td | //tr | //ul | //ol | //li | //p"; var pathx="//div | //span | //table | //th | //td | //tr | //ul | //ol | //li | //p | //iframe"; var selection=$XPathSelect(pathx); for(var element, i=0;element=selection(i);i++) { if(element.tagName.match(/^(div|span|table|td|tr|ul|ol|li|p)$/i)) //redundant check. { var m = new classMausWork(element); gObjArrMW.push(m); attachMouseEventListeners(m); } } document.body.addEventListener('mousedown',MiscEvent,false); document.body.addEventListener('mouseover',MiscEvent,false); document.body.addEventListener('mouseout',MiscEvent,false); document.addEventListener('keypress',MiscEvent,false); } { //setup informational div to show which element the mouse is over. infoDiv=document.createElement('div'); var s=infoDiv.style; s.position='fixed'; s.top='0'; s.right='0'; s.display='block'; s.width='auto'; s.padding='0px'; document.body.appendChild(infoDiv); infoDivHover=document.createElement('div'); s=infoDivHover.style; s.fontWeight='bold'; s.padding='3px'; s.Opacity='0.8'; s.borderWidth='thin'; s.borderStyle='solid'; s.borderColor='white'; s.backgroundColor='black'; s.color='white'; infoDiv.appendChild(infoDivHover); hoverText=document.createTextNode('selecting'); infoDivHover.appendChild(hoverText); } } function CleanupDOMSelection() { for(var m; m=gObjArrMW.pop(); ) { detachMouseEventListeners(m); } ElementRemove(infoDiv); document.body.removeEventListener('mousedown',MiscEvent,false); document.body.removeEventListener('mouseover',MiscEvent,false); document.body.removeEventListener('mouseout',MiscEvent,false); document.removeEventListener('keypress',MiscEvent,false); } function attachMouseEventListeners(c) { //c is object of class classMausWork c.element.addEventListener("mouseover",c.mouse_over,false); c.element.addEventListener("mouseout",c.mouse_out,false); c.element.addEventListener("mousedown",c.mouse_click,false); } function detachMouseEventListeners(c) { //c is object of class classMausWork c.resetElementStyle(); c.element.removeEventListener("mouseover",c.mouse_over,false); c.element.removeEventListener("mouseout",c.mouse_out,false); c.element.removeEventListener("mousedown",c.mouse_click,false); } //mouse event handling class for element, el. function classMausWork(element) { //store information about the element this object is assigned to handle. element, original style, etc. this.element=element; var elementStyle=element.getAttribute('style'); var target; this.mouse_over=function(ev) { if(gHovering)return; var e=element; var s=e.style; s.backgroundColor='yellow'; s.borderWidth='thin'; s.borderColor='lime'; s.borderStyle='solid'; InfoMSG(ElementInfo(e),'yellow','blue','yellow'); gHoverElement=e; gHovering=true; target=ev.target; ev.stopPropagation(); }; this.mouse_out=function(ev) { if(!gHovering)return; if(gHoverElement!=element ||ev.target!=target)return; var e=element; e.setAttribute('style',elementStyle); InfoMSG('-','white','black','white'); gHoverElement=null; gHovering=false; target=null; //ev.stopPropagation(); }; this.mouse_click=function(ev) { if(!gHovering)return; if(gHoverElement!=element ||ev.target!=target)return; var e=element; e.setAttribute('style',elementStyle); ev.stopPropagation(); CleanupDOMSelection(); gHoverElement=null; gHovering=false; target=null; if(ev.button==0) { gSelectedElement=e; ElementSelected(e); //finished selecting, cleanup then move to next part (section 2), element isolation. } }; this.resetElementStyle=function() { element.setAttribute('style',elementStyle); }; } function MiscEvent(ev) //keypress, and mouseover/mouseout/mousedown event on body. cancel selecting. { if(ev.type=='mouseout' && !gHovering) { InfoMSG('-','white','black','white'); } else if(ev.type=='mouseover' && !gHovering) { InfoMSG('cancel','yellow','red','yellow'); } else //keypress on document or mousedown on body, cancel ops. { CleanupDOMSelection(); } } function InfoMSG(text,color,bgcolor,border) { var s=infoDivHover.style; if(color)s.color=color; if(bgcolor)s.backgroundColor=bgcolor; if(border)s.borderColor=border; if(text)hoverText.data=text; } //(Section 2) Element Isolation function ElementSelected(element) //finished selecting element. setup string to prompt user. { PromptUserXpath(ElementInfo(element)); } function PromptUserXpath(defaultpath) //prompt user, isolate element. { var userpath = prompt("XPath of elements to isolate : ", defaultpath); if(userpath && userpath.length>0) { var addPredicate = "[count(./ancestor-or-self::head)=0][count(./ancestor-or-self::title)=0]"; //exclude head & title elements from selection so they aren't removed var addPath = "//script | //form | //object | //embed"; //include these elements in selection for removal var pathx=TransformXPath_NoAncestorDescendentSelf(userpath, addPredicate, addPath); //the xpath selection of all elements to be removed/deleted. try { var element; var elements=$XPathSelect(pathx); for(var i=0;element=elements(i);i++) { if(!element.nodeName.match(/^(head|title)$/i)) //redundant check. { ElementRemove(element); } } } catch(err) { alert("wtf: "+err); } } } //support function $XPathSelect(p, context) { if (!context) context = document; var i, arr = [], xpr = document.evaluate(p, context, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null); return function(x) { return xpr.snapshotItem(x); }; //closure. wooot! returns function-type array of elements (usually elements, or something else depending on the xpath expression). } function ElementRemove(e) { if(e)e.parentNode.removeChild(e); } function ElementInfo(element) { var txt=''; if(element) { txt=element.tagName.toLowerCase(); //txt=element.tagName; txt=attrib(txt,element,'id'); txt=attrib(txt,element,'class'); txt='//'+txt; } return txt; function attrib(t,e,a) { if(e.hasAttribute(a)) { t+="[@"+a+"='"+e.getAttribute(a)+"']"; } return t; } } //function to 'invert' the XPath by selecting all elements that are not ancestor and not descendent and not self. function TransformXPath_NoAncestorDescendentSelf(u, includePredicates, includePaths) { //sample input (u): //div[@class='sortbox'] //sample output //*[ not(./descendant-or-self::*=//div[@class='sortbox'])][ not(./ancestor-or-self::*=//div[@class='sortbox'])] //sample output with additional conditions: //*[ not(./descendant-or-self::*=//div[@class='sortbox'])][ not(./ancestor-or-self::*=//div[@class='sortbox'])][count(./ancestor-or-self::head)=0][count(./ancestor-or-self::title)=0] //obsolete method. much faster but can only be used for limited types of (simple) xpath expressions -- unlike the current version, which should be able to convert any xpath. //input: table[@id='topbar'] //output: //*[not(./descendant-or-self::table[@id='topbar']) and not(./ancestor-or-self::table[@id='topbar'])] //output (alternative): //*[count(./descendant-or-self::table[@id='topbar'])=0 and count(./ancestor-or-self::table[@id='topbar'])=0] var o1= './descendant-or-self::*='+gr(u); o1= 'not' + gr(o1); o1= nt(o1); var o2= './ancestor-or-self::*='+gr(u); o2= 'not' + gr(o2); o2= nt(o2); var o= '//*'+o1+o2; if(includePredicates && includePredicates.length>0) o += includePredicates; if(includePaths && includePaths.length>0) o += ' | ' + includePaths; return o; function nt(term){return wrap(term,'[]');} //node test; predicate - enclose with bracket. function gr(term){return wrap(term,'()');} //group - parenthesize. function wrap(term, enclosure){return enclosure.charAt(0)+term+enclosure.charAt(1);} } })();
September 9, 2007
by Jon C
· 2,341 Views
article thumbnail
Display The Number Of Characters In The Name Of Each Month
months = %w(January February March April May June July August September October November December) months.each { |m| print m, " (", m.length, ")\n" }
August 8, 2007
by Logan Koester
· 5,140 Views
article thumbnail
Java: RegEx: Splitting A Space-, Comma-, And Semi-colon Separated List
// Greedy RegEx quantifier used // X+ = X, one or more times // [\\s,;]+ = one or more times of either \s , or ; String test_data = "hello world, this is a test, ;again"; _logger.debug("Source: " + test_data); for (String tag : test_data.split("[\\s,;]+")) { _logger.debug("Received tag: [" + tag + "]"); }
August 5, 2007
by Snippets Manager
· 38,235 Views · 1 Like
article thumbnail
C#: Resize An Image While Maintaining Aspect Ratio And Maximum Height
public void ResizeImage(string OriginalFile, string NewFile, int NewWidth, int MaxHeight, bool OnlyResizeIfWider) { System.Drawing.Image FullsizeImage = System.Drawing.Image.FromFile(OriginalFile); // Prevent using images internal thumbnail FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone); FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone); if (OnlyResizeIfWider) { if (FullsizeImage.Width MaxHeight) { // Resize with height instead NewWidth = FullsizeImage.Width * MaxHeight / FullsizeImage.Height; NewHeight = MaxHeight; } System.Drawing.Image NewImage = FullsizeImage.GetThumbnailImage(NewWidth, NewHeight, null, IntPtr.Zero); // Clear handle to original file so that we can overwrite it if necessary FullsizeImage.Dispose(); // Save resized picture NewImage.Save(NewFile); }
July 19, 2007
by Arthur Chaparyan
· 22,559 Views · 1 Like
article thumbnail
Class PHP XMLHttpRequest Emulator Using Curl.
// XMLHttpRequest emulator using curl. * @version 0.5 2007/07/16 23:00:13 * @link http://www.myopera.com/moises-l Comments & suggestions * @link http://files.myopera.com/moises-l/files/class.XMLHttpRequest.php Available at * @copyright GPL © 2007, Moises Lima * @license http://creativecommons.org/licenses/by-nc-sa/2.5/ Released under a Creative Commons License */ class XMLHttpRequest{ /** * String version of data returned from server process. * @link http://www.w3.org/TR/XMLHttpRequest/#dfn-responsetext * @access public * @var string * @name $responseText */ var $responseText; /** * DOM-compatible document object of data returned from server process. * which can be examined and parsed using W3C DOM node tree methods and properties * @link http://www.w3.org/TR/XMLHttpRequest/#dfn-responsexml * @access public * @var object * @name $responseXML */ var $responseXML; /** * The http status code returned by server as a number (e.g. 404 for "Not Found" or 200 for "OK"). * @link http://www.w3.org/TR/XMLHttpRequest/#dfn-status * @access public * @var number * @name $status */ var $status; /** * The http status code returned by server as a string (e.g. "Not Found" or "OK") * @link http://www.w3.org/TR/XMLHttpRequest/#dfn-statustext * @access public * @var string * @name $statusText */ var $statusText; /** * The state of the object * 0 = uninitialized * 1 = loading * 2 = loaded * 3 = interactive * 4 = complete * @link http://www.w3.org/TR/XMLHttpRequest/#dfn-readystate * @access public * @var number * @name $readyState */ var $readyState; /** * The error string * @link http://www.w3.org/TR/XMLHttpRequest/#notcovered * @access public * @var string * @name $error */ var $error; /** * An event handler for an event that fires at every state change * @link http://www.w3.org/TR/XMLHttpRequest/#dfn-onreadystatechange * @access public * @name $onreadystatechange */ var $onreadystatechange; /** * An event handler for an event that fires at finished requisition * @link http://www.w3.org/TR/XMLHttpRequest/#notcovered * @access public * @name $onload */ var $onload; /** * An event handler for an event that fires at errors * @link http://www.w3.org/TR/XMLHttpRequest/#notcovered * @access public * @name $onerror */ var $onerror; // http://www.w3.org/TR/XMLHttpRequest/#notcovered /** * cURL handle * @access private * @name $curl */ var $curl; /** * responseHeaders process * @access private * @name $responseHeaders */ var $responseHeaders; /** * cURL headers * @access private * @name $headers */ var $headers=array("Connection: Keep-Alive","Keep-Alive: 300"); /** * Curl info * @access public * @name $curl_version * @var Array */ var $curl_version; /** * TRUE to follow any "Location: " header that the server sends as part of the HTTP header. * @access public * @name $followLocation * @var Bolean */ var $followLocation; /** * Class constructor (compatibility with PHP 4). */ function XMLHttpRequest(){ $this->open="function open() { [native code] }"; $this->setRequestHeader="function setRequestHeader() { [native code] }"; $this->getAllResponseHeaders="function getAllResponseHeaders() { [native code] }"; $this->getResponseHeader="function getResponseHeader() { [native code] }"; $this->send="function send() { [native code] }"; $this->readyState = 0; $this->curl = curl_init(); $this->curl_version = curl_version(); $this->followLocation=false; curl_setopt($this->curl, CURLOPT_HEADER, true); if(isset($_SERVER['HTTP_USER_AGENT'])){ curl_setopt($this->curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT'] ); }else{ curl_setopt($this->curl, CURLOPT_USERAGENT, "XMLHttpRequest/0.2"); } curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($this->curl, CURLOPT_TIMEOUT, 1000); curl_setopt($this->curl, CURLOPT_CONNECTTIMEOUT, 300); } /** * @access private */ function __toString(){ return "[object XMLHttpRequest]"; } /** * Specifies the method, URL, and other optional attributes of a request. * @access public * @link http://www.w3.org/TR/XMLHttpRequest/#dfn-open * @param String $method HTTP Methods defined in section 5.1.1 of RFC 2616 http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html * @param String $url Specifies either the absolute or a relative URL of the data on the Web service. * @param Bolean $async FakeSauro Erectus. * @param String $user specifies the name of the user for HTTP authentication. * @param String $password specifies the password of the user for HTTP authentication. * @return void */ function open($method, $url, $async=true, $user="", $password=""){ $this->readyState = 1; if(!empty($method) && !empty($url)){ $method=strtoupper(trim($method)); /* if(!ereg("^(GET|POST|HEAD|PUT|DELETE|OPTIONS)$",$method)){ throw new Exception("Unknown HTTP request method [$method]"); } */ if(isset($_SERVER['HTTP_REFERER']) && empty($this->url) ){ curl_setopt($this->curl, CURLOPT_REFERER, $_SERVER['HTTP_REFERER']); }elseif(isset($this->url)){ curl_setopt($this->curl, CURLOPT_REFERER, $this->url); } $this->url = $url; curl_setopt($this->curl, CURLOPT_URL, $this->url); if($method=="POST"){ curl_setopt($this->curl, CURLOPT_POST, 1); }elseif($method=="GET"){ curl_setopt($this->curl, CURLOPT_POST, 0); }else{ curl_setopt($this->curl, CURLOPT_POST, 0); curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, $method); } } if(ereg("^(https)",$url)){ curl_setopt($this->curl,CURLOPT_SSL_VERIFYPEER,false); } if(!empty($user) && !empty($password)){ curl_setopt($this->curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY); curl_setopt($this->curl,CURLOPT_USERPWD,$user.":". $password); } } /** * Assigns a label/value pair to the header to be sent with a request. * @access public * @link http://www.w3.org/TR/XMLHttpRequest/#dfn-setrequestheader * @param String $label Specifies the header label. * @param String $value Specifies the header value. * @return void */ function setRequestHeader($label, $value){ $this->headers[] = "$label: $value"; curl_setopt($this->curl, CURLOPT_HTTPHEADER, $this->headers); } /** * Returns complete set of headers (labels and values) as a string. * @access public * @link http://www.w3.org/TR/XMLHttpRequest/#dfn-getallresponseheaders * @return string Complete set of headers (labels and values) as a string */ function getAllResponseHeaders(){ return $this->responseHeaders; } /** * Returns the value of the specified http header. * @access public * @link http://www.w3.org/TR/XMLHttpRequest/#dfn-getresponseheader. * @param String $label * @return String|null The string value of a single header label. */ function getResponseHeader($label){ $value=array(); preg_match_all('/(?s)'.$label.': (.*?)\s\n/i', $this->responseHeaders , $value); if(count($value ) > 0){ return implode(', ' , $value[1]); } return null; } function getResponseHeader2($label){ $value=array(); preg_match('/(?s)'.$label.': (.*?)\s\n/i', $this->responseHeaders , $value); if(count($value ) > 0){ return $value[1]; } return null; } /** * Transmits the request, optionally with postable string or DOM object data. * @access public * @link http://www.w3.org/TR/XMLHttpRequest/#dfn-getresponseheader * @param String $data * @return void */ function send($data=null){ $sT=array(); if(isset($this->onreadystatechange))eval($this->onreadystatechange); if($data){ curl_setopt($this->curl, CURLOPT_POSTFIELDS, $data); } $this->response= curl_exec($this->curl); $header_size = curl_getinfo($this->curl, CURLINFO_HEADER_SIZE); $this->responseHeaders = substr($this->response, 0, $header_size - 4); if($this->followLocation){ $location=array(); while(preg_match('/Location:(.*?)\n/', $this->responseHeaders, $location)){ curl_setopt($this->curl, CURLOPT_REFERER, $this->url); $url = @parse_url(trim(array_pop($location))); if (!$url){ break; } $last_url = parse_url(curl_getinfo($this->curl, CURLINFO_EFFECTIVE_URL)); if (!isset($url['scheme']))$url['scheme'] = $last_url['scheme']; if (!isset($url['host']))$url['host'] = $last_url['host']; if (!isset($url['path']))$url['path'] = $last_url['path']; $this->url = $url['scheme'] . '://' . $url['host'] . $url['path'] . (isset($url['query'])?'?'.$url['query']:''); curl_setopt($this->curl, CURLOPT_POST, 0); //curl_setopt($this->curl, CURLOPT_POSTFIELDS,0); curl_setopt($this->curl, CURLOPT_URL, $this->url); $this->response= curl_exec($this->curl); $header_size = curl_getinfo($this->curl, CURLINFO_HEADER_SIZE); $this->responseHeaders = substr($this->response, 0, $header_size - 4); } } $this->error = curl_error($this->curl); if ($this->error) { if(isset($this->onerror))eval($this->onerror); } $this->readyState = 2; if(isset($this->onreadystatechange))eval($this->onreadystatechange); $this->responseText = substr($this->response, $header_size); preg_match('/^HTTP\/\d\.\d\s+(\d{3}) (.*)\s\n/i', $this->responseHeaders , $sT); if(count($sT ) > 2){ $this->responseHeaders = ereg_replace ($sT[0], "", $this->responseHeaders); $this->status = $sT[1]; $this->statusText = $sT[2]; } if(version_compare(PHP_VERSION , "5", ">=")){ if (preg_match('/(application|text)\/[\w+\+]?xml/i', $this->getResponseHeader("Content-Type"))){ libxml_use_internal_errors(true); $this->responseXML = new DOMDocument(); $this->responseXML->loadXML($this->responseText); $errors = libxml_get_errors(); if (!empty($errors)){ $this->responseXML=null; $error=$errors[0]; $this->error= trim($error->message) ." in $this->url on line $error->line column: $error->column "; if(isset($this->onerror))eval($this->onerror); } libxml_clear_errors(); } } $this->readyState = 3; if(isset($this->onreadystatechange))eval($this->onreadystatechange); $this->headers=Array(); $this->readyState = 4; if(isset($this->onreadystatechange))eval($this->onreadystatechange); if(isset($this->onload))eval($this->onload); } /** * Closes a cURL session and frees all resources. * @name close * @access public * @return void */ function close(){ curl_close($this->curl); } } ?>
July 18, 2007
by Snippets Manager
· 3,573 Views
article thumbnail
Reverse TinyURL
PHP // Resolves a TinyURL.com encoded URL to its source. // Example: reverse_tinyurl('http://tinyurl.com/2ocfun') => "http://logankoester.com" function reverse_tinyurl($url) { $url = explode('.com/', $url); $url = 'http://preview.tinyurl.com/' . $url[1]; $preview = file_get_contents($url); preg_match('/redirecturl" href="(.*)">/', $preview, $matches); return $matches[1]; }
July 2, 2007
by Logan Koester
· 8,578 Views
article thumbnail
Save To Bookmarks/Favorites
// Cross-browser code for IE/Mozilla var bookmarkurl="Add full URI here" var bookmarktitle="Add your title here" function addbookmark(){ if (document.all) window.external.AddFavorite(bookmarkurl,bookmarktitle)//IE window.sidebar.addPanel( bookmarktitle, bookmarkurl, '' );//Moz } //add javascript:addbookmark(); to the HTML to call the function
June 30, 2007
by Snippets Manager
· 2,462 Views
article thumbnail
Compress/decompress Byte Array
using System; using System.Collections.Generic; using System.IO.Compression; using System.IO; using System.Collections; namespace Utilities { class Compression { public static byte[] Compress(byte[] data) { MemoryStream ms = new MemoryStream(); DeflateStream ds = new DeflateStream(ms, CompressionMode.Compress); ds.Write(data, 0, data.Length); ds.Flush(); ds.Close(); return ms.ToArray(); } public static byte[] Decompress(byte[] data) { const int BUFFER_SIZE = 256; byte[] tempArray = new byte[BUFFER_SIZE]; List tempList = new List(); int count = 0, length = 0; MemoryStream ms = new MemoryStream(data); DeflateStream ds = new DeflateStream(ms, CompressionMode.Decompress); while ((count = ds.Read(tempArray, 0, BUFFER_SIZE)) > 0) { if (count == BUFFER_SIZE) { tempList.Add(tempArray); tempArray = new byte[BUFFER_SIZE]; } else { byte[] temp = new byte[count]; Array.Copy(tempArray, 0, temp, 0, count); tempList.Add(temp); } length += count; } byte[] retVal = new byte[length]; count = 0; foreach (byte[] temp in tempList) { Array.Copy(temp, 0, retVal, count, temp.Length); count += temp.Length; } return retVal; } } }
June 10, 2007
by Snippets Manager
· 8,737 Views
article thumbnail
Display DateTime Up To Milliseconds
Format string "ffff" is responsible for displaying milliseconds. string myTime = DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss:ffff"); Console.WriteLine(myTime);
May 25, 2007
by Snippets Manager
· 26,183 Views · 20 Likes
article thumbnail
PHP - Change Active Directory Password
You are changing the password for ". $info[$i]["givenname"][0] .", " . $info[$i]["sn"][0] ." (" . $info[$i]["samaccountname"][0] .") to " . $_POST['user_pass'] ." \n"; $passwd1 = $_POST['user_pass']; $userDn = $info[$i]["distinguishedname"][0]; $newPassword = $passwd1; $newPassword = "\"" . $newPassword . "\""; $len = strlen($newPassword); for ($i = 0; $i < $len; $i++){ $newPassw .= "{$newPassword{$i}\000";} $newPassword = $newPassw; $userdata["unicodePwd"] = $newPassword; $result = ldap_mod_replace($ldap, $userDn , $userdata); if ($result) echo "Your password has been changed!" ; else echo "There was a problem changing your password, please call IT for help"; } } @ldap_close($ldap); ?>
May 23, 2007
by Snippets Manager
· 4,662 Views
article thumbnail
Remove Empty XML Nodes
Remove nodes like (without attributes & without children) public static void RemoveEmptyNodes(XmlDocument doc) { XmlNodeList nodes = doc.SelectNodes("//node()"); foreach (XmlNode node in nodes) if ((node.Attributes.Count == 0) && (node.ChildNodes.Count == 0)) node.ParentNode.RemoveChild(node); }
May 15, 2007
by Snippets Manager
· 8,549 Views
article thumbnail
Java: Lucene: Simple In-Memory Search Example
// Adapted from http://javatechniques.com/blog/lucene-in-memory-text-search-example // Works with present APIs in Lucene 2.1.0 /** * A simple example of an in-memory search using Lucene. */ import java.io.IOException; import java.io.StringReader; import org.apache.lucene.search.Hits; import org.apache.lucene.search.Query; import org.apache.lucene.document.Field; import org.apache.lucene.search.Searcher; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.document.Document; import org.apache.lucene.store.RAMDirectory; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.queryParser.QueryParser; import org.apache.lucene.queryParser.ParseException; import org.apache.lucene.analysis.standard.StandardAnalyzer; public class InMemoryExample { public static void main(String[] args) { // Construct a RAMDirectory to hold the in-memory representation // of the index. RAMDirectory idx = new RAMDirectory(); try { // Make an writer to create the index IndexWriter writer = new IndexWriter(idx, new StandardAnalyzer(), true); // Add some Document objects containing quotes writer.addDocument(createDocument("Theodore Roosevelt", "It behooves every man to remember that the work of the " + "critic, is of altogether secondary importance, and that, " + "in the end, progress is accomplished by the man who does " + "things.")); writer.addDocument(createDocument("Friedrich Hayek", "The case for individual freedom rests largely on the " + "recognition of the inevitable and universal ignorance " + "of all of us concerning a great many of the factors on " + "which the achievements of our ends and welfare depend.")); writer.addDocument(createDocument("Ayn Rand", "There is nothing to take a man’s freedom away from " + "him, save other men. To be free, a man must be free " + "of his brothers.")); writer.addDocument(createDocument("Mohandas Gandhi", "Freedom is not worth having if it does not connote " + "freedom to err.")); // Optimize and close the writer to finish building the index writer.optimize(); writer.close(); // Build an IndexSearcher using the in-memory index Searcher searcher = new IndexSearcher(idx); // Run some queries search(searcher, "freedom"); search(searcher, "free"); search(searcher, "progress or achievements"); searcher.close(); } catch (IOException ioe) { // In this example we aren’t really doing an I/O, so this // exception should never actually be thrown. ioe.printStackTrace(); } catch (ParseException pe) { pe.printStackTrace(); } } /** * Make a Document object with an un-indexed title field and an indexed * content field. */ private static Document createDocument(String title, String content) { Document doc = new Document(); // Add the title as an unindexed field… doc.add(new Field("title", title, Field.Store.YES, Field.Index.NO)); // …and the content as an indexed field. Note that indexed // Text fields are constructed using a Reader. Lucene can read // and index very large chunks of text, without storing the // entire content verbatim in the index. In this example we // can just wrap the content string in a StringReader. doc.add(new Field("content", new StringReader(content))); return doc; } /** * Searches for the given string in the "content" field */ private static void search(Searcher searcher, String queryString) throws ParseException, IOException { // Build a Query object QueryParser parser = new QueryParser("content", new StandardAnalyzer()); Query query = parser.parse(queryString); // Search for the query Hits hits = searcher.search(query); // Examine the Hits object to see if there were any matches int hitCount = hits.length(); if (hitCount == 0) { System.out.println("No matches were found for \"" + queryString + "\""); } else { System.out.println("Hits for \"" + queryString + "\" were found in quotes by:"); // Iterate over the Documents in the Hits object for (int i = 0; i < hitCount; i++) { Document doc = hits.doc(i); // Print the value that we stored in the "title" field. Note // that this Field was not indexed, but (unlike the // "contents" field) was stored verbatim and can be // retrieved. System.out.println(" " + (i + 1) + ". " + doc.get("title")); } } System.out.println(); } }
May 15, 2007
by Snippets Manager
· 6,230 Views
article thumbnail
Java DOM : Creating An XML Document From XML File
// description of your code here try { // // Create the XML Document // DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = dbfac.newDocumentBuilder(); Document doc = docBuilder.parse(filePath); // ... } catch (Exception e) { // ... }
May 14, 2007
by Snippets Manager
· 19,270 Views
article thumbnail
How To Convert A String With A Date To A Calendar
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); Date date = sdf.parse(strDate); Calendar cal = Calendar.getInstance(); cal.setTime(date);
May 8, 2007
by Snippets Manager
· 160,542 Views · 3 Likes
article thumbnail
Hash Code Generator
Simple hash code generator which allows hash codes for primitives and Java objects to be combined for a single object hash code with: new HashCode().hash(value1) .hash(value2) .hash(value3) .getHashCode(); This also supports hashing of arrays by recursively hashing all elements in the array. Thanks to Item 8 in Joshua Bloch's "Effective Java" for the hash code theory: public class HashCode { static final int DEFAULT_SEED = 23; static final int fODD_PRIME_NUMBER = 37; int hash; // ------------------------------------------------- Constructors /** * Constructor - creates a hash code object initialized with * the given seed value. */ public HashCode(int seed) { this.hash = seed; } /** * Constructor - creates a hash code object initialized with * a default seed value. */ public HashCode() { this(DEFAULT_SEED); } // ---------------------------------------------------- Accessors /** * Returns the hash code stored in the object */ public int getHashCode() { return this.hash; } public String toString() { return String.valueOf(this.hash); } // ----------------------------------------------- Implementation /** * Adds the given value to the stored hash. This is done by * multiplying the current hash by fODD_PRIME_NUMBER and then * adding the new value to it. */ private void add(int value){ this.hash = fODD_PRIME_NUMBER * this.hash + value; } //basic number types: public HashCode hash(int value) { add(value); return this; } public HashCode hash(long value) { add((int)( value ^ (value >>> 32) )); return this; } public HashCode hash(short value) { add((int)value); return this; } public HashCode hash(byte value) { add((int)value); return this; } public HashCode hash(float value ) { add(Float.floatToIntBits(value) ); return this; } public HashCode hash(double value) { return hash(Double.doubleToLongBits(value)); } //other primitives: public HashCode hash(boolean value) { add(value ? 1 : 0); return this; } public HashCode hash(char value) { add((int)value); return this; } //objects: /** * Hashes an object. If this is null it will hash a value * of zero. If it is an array it will recursively hash all * of the elements in the array. For other objects it will * simply invoke their own hashCode() method. */ public HashCode hash(Object obj) { if (obj == null) add(0); else if (!isArray(obj) ) add(obj.hashCode()); else { //recursively hash all elements in the array int length = Array.getLength(obj); for (int i = 0; i < length; i++) { Object item = Array.get(obj, i); hash(item); } } return this; } // ----------------------------------------------- Static Methods /** * Returns true if the object is an array */ private static boolean isArray(Object obj){ return obj.getClass().isArray(); } /** * Returns a hash code for the given object. This is offered * as a simplified method for: * * new HashCode().hash(obj).getHashCode() * * Most notably, it allows for the quick and easy caching of * arrays. It is not intended for hashing any arbitrary object * though. For hashes beyond a single object property it is * better to instantiate the HashCode object and hash all * of the pertinent properties. */ public static int hashArray(Object obj) { return new HashCode().hash(obj).getHashCode(); } // ------------------------------------------------------ Testing public static void main(String [] args) { double [] a1 = new double [] {1,2,3,4,5,6}; double [] a2 = new double [] {1,2,3,4,5,6}; System.out.println(a1.hashCode()); System.out.println(a2.hashCode()); System.out.println(new HashCode().hash(a1)); System.out.println(new HashCode().hash(a2)); } }
May 4, 2007
by Snippets Manager
· 8,366 Views
  • Previous
  • ...
  • 1640
  • 1641
  • 1642
  • 1643
  • 1644
  • 1645
  • 1646
  • 1647
  • Next
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook
×