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 20 total  RSS 

Output JavaScript variables from PHP

Class with useful static methods for outputting PHP values into JavaScript format.

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com

class JS{
	//generic and maybe not the desired results xD
	function value($o){
		if($o === null)
			return 'null';
		$t = strtolower(gettype($o));
		if($t == 'string' && is_numeric($o) && ($o[0] || strlen($o) == 1) || in_array($t, array('double', 'integer')))
			$t = 'number';
		elseif($t == 'string' && preg_match('@^\d{4}(?:-\d{1,2}){1,2}(?: (?:\d{1,2}:){2}\d{1,2})?$@', $o)) //strtotime works also with "strange" values strtotime('x')
			$t = 'date';
		elseif($t == 'array' && ($c = count($k = array_keys($o))) && $k !== range(0, $c - 1))
			$t = 'object';
		elseif(!in_array($t, array('boolean', 'string', 'array', 'object')))
			$t = 'string';
		$t = 'from' . $t;
		return self::$t($o);
	}
	function fromNumber($o){
		return +$o . '';
	}
	function fromObject($o){
		$r = array();
		foreach($o as $n => $v)
			$r[] = self::fromString($n) . ':' . self::value($v);
		return '{' . implode(',', $r) . '}';
	}
	function fromBoolean($o){
		return $o ? 'true' : 'false';
	}
	//$q = should quote? 
	//$c = char that will be used to quote
	function fromString($o, $q = true, $c = '"'){
		return ($p = $q ? $c : '') . preg_replace('/\r\n|\n\r|\r/', '\n', str_replace($c, '\\' . $c, str_replace('\\', '\\\\', $o))) . $p;
	}
	function fromArray($o){
		$s = '';
		foreach($o as $v)
			$s .= ($s ? ',' : '') . self::value($v);
		return '[' . $s . ']';
	}
	function fromDate($o){
		(is_numeric($o) && $o = +$o) || ($o = strtotime($o)) > 0 || ($o = mktime());
		$o = explode(',', date('Y,n,j,G,i,s', $o));
		foreach($o as $i => $v)
			$o[$i] = +$v;
		return 'new Date(' . implode(',', $o)  . ')';
	}
}


Example

$o = new stdClass;
$o->abc = 123;
echo implode("\n<br />", array(
	JS::value('1984-07-22 11:30:12'),
	JS::value('Test'),
	JS::value(1234),
	JS::value(true),
	JS::value(array(1,2,3)),
	JS::value(array('lala' => 'x')),
	JS::value($o)
));

Rails Date Formats

// cribbed from http://wiki.rubyonrails.org/rails/pages/HowToDefineYourOwnDateFormat

my_formats = {
  :my_format_1 => '%l %p, %b %d, %Y',
  :my_format_2  => '%l:%M %p, %B %d, %Y'
}

ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS.merge!(my_formats)
ActiveSupport::CoreExtensions::Date::Conversions::DATE_FORMATS.merge!(my_formats)

Calculate last day of current Month

'Determines what the next month is based on today and subtracts 1 day from first day of next month.

'VB.NET
Dim NextMonth As Integer
Dim RptYear As Integer
'Determine next month
NextMonth = DatePart(DateInterval.Month, DateAdd(DateInterval.Month, +1, today))
'Determine the year of the next month, in case you are going from Dec to Jan
RptYear = DatePart(DateInterval.Year, DateAdd(DateInterval.Month, +1, today))
'Subtract 1 day from the first day of next month to get this months last day
Return DateAdd(DateInterval.Day, -1, DateValue(NextMonth.ToString & "/1/" & RptYear.ToString))

Format Ruby code in HTML

This code uses the Ruby gem 'syntax' to create an XML file containing the HTML tags around the code, which is then transformed into an HTML file. The working example was first built using coding examples from Howto format ruby code for blogs [wolfman.com] and Formatting Ruby and HTML code for blog posting [blogspot.com]

#!/usr/bin/ruby

#file: ruby2html.rb 

require 'rubygems'
require 'syntax/convertors/html'
require 'projxslt' # <- this is my own class to do an XSLT transform 
require 'rexml/document'
include REXML

class Ruby2Html
  def initialize(rubyfile, htmlfile)
    code = File.read(rubyfile)
    convertor = Syntax::Convertors::HTML.for_syntax "ruby"
    code_html = convertor.convert(code)
    
    tempfile = '../temp/ruby2html.xml'
    xslfile = '../ruby2html/ruby2html.xsl'
    save_file(tempfile, code_html)
    
    px = Projxslt.new(tempfile, xslfile)
    buffer = px.transform()
    save_file(htmlfile, buffer)
    
  end
  
  def save_file(filename, buffer)
    file = File.new(filename, 'w')
    file.puts buffer
    file.close
  end
end

if __FILE__ == $0
  r2h = Ruby2Html.new('ruby2html.rb', '../temp/ruby2html.html')
  puts 'completed'
end

file: ruby2html.xsl
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns="http://www.w3.org/1999/xhtml"
                version="1.0">

  <xsl:output method="html" doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN"
          doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
          encoding="ISO-8859-1"/> 

	<xsl:template match="/">
	<xsl:element name="html">

        <head>
          <title>Sample code</title>
          <link rel="stylesheet" type="text/css" href="ruby2html.css" />
	</head>

	<body>
          <div id="wrap">
          <xsl:apply-templates />
          </div>
	</body> 

	</xsl:element>
	</xsl:template>

	<xsl:template match="pre">
	  <xsl:copy-of select="."/>
	</xsl:template>

</xsl:stylesheet>

Here's the output from the formatted Ruby HTML code [twitxr.com]

Referemce: Syntax Manual [rubyforge.org]

Formatting a date in XSLT

This template formats a date ie 060208171320 -> 06-Feb-08T17:13:20

  <xsl:template name="FormatDate">
    <xsl:param name="DateTime" />
    <!-- new date format 2006-01-14T08:55:22 -->
    <xsl:variable name="mo">
      <xsl:value-of select="substring($DateTime,3,2)" />
    </xsl:variable>
    <xsl:variable name="day">
      <xsl:value-of select="substring($DateTime,5,2)" />
    </xsl:variable>
    <xsl:variable name="year">
      <xsl:value-of select="substring($DateTime,1,2)" />
    </xsl:variable>
    <xsl:variable name="hh">
      <xsl:value-of select="substring($DateTime,7,2)" />
    </xsl:variable>
    <xsl:variable name="mm">
      <xsl:value-of select="substring($DateTime,9,2)" />
    </xsl:variable>
    <xsl:variable name="ss">
      <xsl:value-of select="substring($DateTime,11,2)" />
    </xsl:variable>
    <xsl:if test="(string-length($day) &lt; 2)">
      <xsl:value-of select="0"/>
    </xsl:if>
    <xsl:value-of select="$day"/>
    <xsl:value-of select="'-'"/>
    <xsl:choose>
      <xsl:when test="$mo = '01'">Jan</xsl:when>
      <xsl:when test="$mo = '02'">Feb</xsl:when>
      <xsl:when test="$mo = '03'">Mar</xsl:when>
      <xsl:when test="$mo = '04'">Apr</xsl:when>
      <xsl:when test="$mo = '05'">May</xsl:when>
      <xsl:when test="$mo = '06'">Jun</xsl:when>
      <xsl:when test="$mo = '07'">Jul</xsl:when>
      <xsl:when test="$mo = '08'">Aug</xsl:when>
      <xsl:when test="$mo = '09'">Sep</xsl:when>
      <xsl:when test="$mo = '10'">Oct</xsl:when>
      <xsl:when test="$mo = '11'">Nov</xsl:when>
      <xsl:when test="$mo = '12'">Dec</xsl:when>
    </xsl:choose>
    <xsl:value-of select="'-'"/>

    <xsl:value-of select="$year"/>
    <xsl:value-of select="'T'"/>
    <xsl:value-of select="$hh"/>
    <xsl:value-of select="':'"/>
    <xsl:value-of select="$mm"/>
    <xsl:value-of select="':'"/>
    <xsl:value-of select="$ss"/>
  </xsl:template>


copied from http://snipr.com/1z833 [geekswithblogs.net] and modified to suit the date input format I used.

Pretty Print XML using Ruby

This code makes the XML output look pretty. I tried using the documentation from the REXML website to apply the method example doc.write($stdout,0), but I gave up, and instead wrote my own XML pretty-print method.

require 'rexml/document'
include REXML

  def pretty_print(parent_node, itab)
    buffer = ''

    parent_node.elements.each do |node|

      buffer += ' ' * itab + "<#{node.name}#{get_att_list(node)}"
  
      if node.to_a.length > 0
        buffer += ">"
        if node.text.nil?
          buffer += "\n"
          buffer += pretty_print(node,itab+2) 
          buffer += ' ' * itab + "</#{node.name}>\n"
        else
          node_text = node.text.strip
          if node_text != ''
            buffer += node_text 
            buffer += "</#{node.name}>\n"        
          else
            buffer += "\n" + pretty_print(node,itab+2) 
            buffer += ' ' * itab + "</#{node.name}>\n"        
          end
        end
      else
        buffer += "/>\n"
      end
      
    end
    buffer
  end

  def get_att_list(node)
    att_list = ''
    node.attributes.each { |attribute, val| att_list += " #{attribute}='#{val}'" }
    att_list
  end
  
  def pretty_xml(doc)
    buffer = ''
    xml_declaration = doc.to_s.match('<\?.*\?>').to_s
    buffer += "#{xml_declaration}\n" if not xml_declaration.nil?
    xml_doctype = doc.to_s.match('<\!.*\">').to_s
    buffer += "#{xml_doctype}\n" if not xml_doctype.nil?
    buffer += "<#{doc.root.name}#{get_att_list(doc.root)}"
    if doc.root.to_a.length > 0
      buffer +=">\n#{pretty_print(doc.root,2)}</#{doc.root.name}>"
    else
      buffer += "/>\n"
    end
  end

xml_data = "<hi id='124'><yo><a id='1'/><b/><c/></yo><sushi><love>Ruby</love></sushi></hi>"
doc = Document.new(xml_data)
pretty_xml(doc)


output
<hi id='124'>
  <yo>
    <a id='1'/>
    <b/>
    <c/>
  </yo>
  <sushi>
    <love>Ruby</love>
  </sushi>
</hi>


*Update 7-Jan-08 1:51AM *
Although I haven't tried running the following XSL code, this might actually have been a better solution to my problem. source: http://www.printk.net/~bds/indent.html

*Pretty Print XML using XSLT*
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" encoding="ISO-8859-1"/>
  <xsl:param name="indent-increment" select="'   '"/>
  
  <xsl:template name="newline">
    <xsl:text disable-output-escaping="yes">
</xsl:text>
  </xsl:template>
  
  <xsl:template match="comment() | processing-instruction()">
    <xsl:param name="indent" select="''"/>
    <xsl:call-template name="newline"/>    
    <xsl:value-of select="$indent"/>
    <xsl:copy />
  </xsl:template>
  
  <xsl:template match="text()">
    <xsl:param name="indent" select="''"/>
    <xsl:call-template name="newline"/>    
    <xsl:value-of select="$indent"/>
    <xsl:value-of select="normalize-space(.)"/>
  </xsl:template>
    
  <xsl:template match="text()[normalize-space(.)='']"/>
  
  <xsl:template match="*">
    <xsl:param name="indent" select="''"/>
    <xsl:call-template name="newline"/>    
    <xsl:value-of select="$indent"/>
      <xsl:choose>
       <xsl:when test="count(child::*) > 0">
        <xsl:copy>
         <xsl:copy-of select="@*"/>
         <xsl:apply-templates select="*|text()">
           <xsl:with-param name="indent" select="concat ($indent, $indent-increment)"/>
         </xsl:apply-templates>
         <xsl:call-template name="newline"/>
         <xsl:value-of select="$indent"/>
        </xsl:copy>
       </xsl:when>       
       <xsl:otherwise>
        <xsl:copy-of select="."/>
       </xsl:otherwise>
     </xsl:choose>
  </xsl:template>    
</xsl:stylesheet>

Simple output of date in perl

// Simple output of current date in perl

  my @day_name = ("Sun.","Mon.","Tue.","Wed.","Thu.","Fri.","Sat.");
  my ($sec,$min,$hour,$mday,$mon,$year,$wday); 
  ($sec,$min,$hour,$mday,$mon,$year,$wday,undef,undef)=localtime(time()); $year+=1900;$mon++;
  $report_date=sprintf("%s %04d.%02d.%02d %02d:%02d",$day_name[$wday],$year,$mon,$mday,$hour,$min);

RecordSet to tab-separated values

Function TSV(rs)
	Dim field
	For Each field In rs.Fields
		TSV = TSV & field.Name & VBTab
	Next
	TSV = Left(TSV, Len(TSV) - 1) & vbCr & rs.GetString()
End Function


The rows are separated by vbCr ("\r" in most languages).
The first row is the field names.

Actionscript _Text Class

Useful functions for adding dynamic text fields. Don't forget, you have to add the font of choice into the main movie Library for this to work (Library Panel Menu > New Font). The name you give the font is the string that you pass to the getTextFormat function for the "font" parameter. Setup your font styles with getTextFormat, setup your dynamic text box with getTextField, and then add text to the text box with appendTextField.

dynamic class _Text {
	static function getTextFormat(font:String,size:Number,color:Number,leading:Number,url:String,target:String){
		var fmt:TextFormat = new TextFormat();
		fmt.font = font;
		fmt.kerning = true;
		fmt.leading = (leading != undefined && leading != null) ? leading : 0;
		fmt.bold = false;
		fmt.size = (size != undefined && size != null) ? size : 11;
		fmt.color = (color != undefined && color != null) ? color : 0x000000;

		if (url != undefined && url != null) {
			fmt.url = url;
			fmt.target = (target != undefined && target != null) ? target : "_self";
		}
		return (fmt);
	}
	
	static function getTextField(targetMC,targetDepth,txtFieldName,x,y,w,h,txtObj){
		var targetDepth = (targetDepth != undefined && targetDepth != null) ? targetDepth : targetMC.getNextHighestDepth();
		var txtfld = targetMC.createTextField(txtFieldName, targetDepth, x, y, w, h);
		txtfld.antiAliasType = (txtObj.antiAliasType) ? txtObj.antiAliasType : "advanced";
		txtfld.sharpness = (txtObj.sharpness) ? txtObj.sharpness : -60;
		txtfld.thickness = (txtObj.thickness) ? txtObj.thickness : -100;
		txtfld.embedFonts = (txtObj.embedFonts) ? txtObj.embedFonts : true;
		txtfld.selectable = (txtObj.selectable) ? txtObj.selectable : false;
		txtfld.html = (txtObj.html) ? txtObj.html : true;
		txtfld.multiline = (txtObj.multiline) ? txtObj.multiline : true;
		txtfld.autoSize = (txtObj.autoSize) ? txtObj.autoSize : "left";
		
		if (txtObj.htmlText) txtfld.htmlText = txtObj.htmlText;
		if (txtObj.txtFormat) txtfld.setTextFormat(txtObj.txtFormat);
		
		if (txtObj.wordWrap == undefined || txtObj.wordWrap == null) txtfld._width = txtfld.textWidth + 10;
		else txtfld.wordWrap = txtObj.wordWrap;
		return txtfld;
	}
	
	static function appendTextField(txtfld,txtfrmt,txt){
		var beginIndex:Number = txtfld.htmlText.length;
		txtfld.setNewTextFormat(txtfrmt);
		txtfld.replaceText(beginIndex,beginIndex,txt);
	}
}

Objective-C and Cocoa: Human-readable file size from number of bytes

// Returns a human-readable string showing the file size from the number of bytes

- (NSString *)stringFromFileSize:(int)theSize
{
	float floatSize = theSize;
	if (theSize<1023)
		return([NSString stringWithFormat:@"%i bytes",theSize]);
	floatSize = floatSize / 1024;
	if (floatSize<1023)
		return([NSString stringWithFormat:@"%1.1f KB",floatSize]);
	floatSize = floatSize / 1024;
	if (floatSize<1023)
		return([NSString stringWithFormat:@"%1.1f MB",floatSize]);
	floatSize = floatSize / 1024;

	// Add as many as you like

	return([NSString stringWithFormat:@"%1.1f GB",floatSize]);
}
« Newer Snippets
Older Snippets »
Showing 1-10 of 20 total  RSS