Never been to CodeSnippets 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 (or not, you can keep them private!)

SMTP service within Sinatra-Rscript

// description of your code here

<job id='load-service'>
  <script>
    <![CDATA[

    require 'gserver'

    class SMTPServer < GServer
      def serve(io)
        @data_mode = false
        puts "Connected"
        io.print "220 hello\r\n"
        loop do
          if IO.select([io], nil, nil, 0.1)
            data = io.readpartial(4096)
            puts ">>" + data
            ok, op = process_line(data)
            break unless ok
            io.print op
          end
          break if io.closed?
        end
        io.print "221 bye\r\n"
        io.close
      end

      def process_line(line)
        if (line =~ /^(HELO|EHLO)/)
          return true, "220 and..?\r\n"
        end
        if (line =~ /^QUIT/)
          return false, "bye\r\n"
        end
        if (line =~ /^MAIL FROM\:/)
          return true, "220 OK\r\n"
        end
        if (line =~ /^RCPT TO\:/)
          return true, "220 OK\r\n"
        end
        if (line =~ /^DATA/)
          @data_mode = true
          return true, "354 Enter message, ending with \".\" on a line by itself\r\n"
        end
        if (@data_mode) && (line.chomp =~ /^.$/)
          @data_mode = false
          return true, "220 OK\r\n"
        end
        if @data_mode
          puts line 
          return true, ""
        else
          return true, "500 ERROR\r\n"
        end
      end
    end

    @@services['smtp-service'] = SMTPServer.new(1234)

    "SMTP service loaded"

Money order Tramadol. Overnight Tramadol without a prescription. Tramadol on line purchase. Tramadol no script needed cod overnight.
Cheap order prescription Diazepam. Cheap Diazepam overnight delivery. Cheap Diazepam next day shipping. Buy Diazepam prescription online.
@@services['smtp-service'] = SMTPServer.new(1234)
Online purchase Valium. Buy Valium cheap cod. Overnight Valium without a prescription. Valium cod orders.
Buy Ultram no prescription cod. Get Ultram over the counter cod overnight. Ultram with saturday delivery. Ultram no doctors consult.

    ]]>
  </script>
</job>
<job id='start'>
  <script>
    <![CDATA[

    @@services['smtp-service'].start
    "SMTP service started"

    ]]>
  </script>
</job>
<job id='stop'>
  <script>
    <![CDATA[

    @@services['smtp-service'].stop
    "SMTP-server stopped"

    ]]>
  </script>
</job>
<job id='remove'>
  <script>
    <![CDATA[

    Object.send(:remove_const, :SMTPServer)
    @@services.delete('smtp-service')
    "SMTP service removed"

    ]]>
  </script>
</job>

Get String Properties From Entitiesss

// description of your code here

import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;

public class JPAUtil {
  Statement st;
  
  public JPAUtil() throws Exception{
    Class.forName("org.hsqldb.jdbcDriver");
    System.out.println("Driver Loaded.");
    String url = "jdbc:hsqldb:data/tutorial";

    Connection conn = DriverManager.getConnection(url, "sa", "");
    System.out.println("Got Connection.");
    st = conn.createStatement();
  }
  public void executeSQLCommand(String sql) throws Exception {
    st.executeUpdate(sql);
  }
  public void checkData(String sql) throws Exception {
    ResultSet rs = st.executeQuery(sql);
    ResultSetMetaData metadata = rs.getMetaData();

    for (int i = 0; i < metadata.getColumnCount(); i++) {
      System.out.print("\t"+ metadata.getColumnLabel(i + 1)); 
    }
    System.out.println("\n----------------------------------");

    while (rs.next()) {
      for (int i = 0; i < metadata.getColumnCount(); i++) {
        Object value = rs.getObject(i + 1);
        if (value == null) {
          System.out.print("\t       ");
        } else {
          System.out.print("\t"+value.toString().trim());
        }
      }
      System.out.println("");
    }
  }
}



Altın Fiyatları
Revizyon ile Organize Matbaacılık Brnckvvtmllttrhaberi

Using this function you will avoid 'Undefined index' orr

// description of your code here

// insert code here..


<?php

$_POST['id']['other'] = 'val1';

/*
key exist (same as $_POST['id'][other])
*/
echo getRequestParam('id[other]', 'default value');

/*
key doesn't exist, we get default value (same as $_POST['var'])
*/

echo getRequestParam('var', 'default value');

function getRequestParam( $var, $default = '', $method = 'post' )
{
preg_match_all('!(\w+)!i',$var, $match );
array_shift($match);
$_vars = $match[0];
$ret = null;

if( strtoupper($method) == 'POST' ) {
$ret = _findRequestParam($_vars, $_POST);
}
elseif( strtoupper($method) == 'GET' ) {
$ret = _findRequestParam($_vars, $_GET);
}
elseif( strtoupper($method) == 'COOKIE' ) {
$ret = _findRequestParam($_vars, $_COOKIE);

}
elseif( strtoupper($method) == 'SESSION' ) {
$ret = _findRequestParam($_vars, $_SESSION);
}

if (! $ret )
return $default;
else
return $ret;

}

/**
@access private
*/

function _findRequestParam($vars, $find_in , $curr_key = 0)
{
static $ret;

if( array_key_exists($vars[$curr_key], $find_in) ) {
if( count( $vars)-1 == $curr_key ) {
$ret = $find_in[$vars[$curr_key]];
}
elseif( $curr_key < count( $vars)-1 ) {
_findRequestParam( $vars, $find_in[$vars[$curr_key]], $curr_key+1 );
}
}

return $ret;

}

?>


Windows Live

6144 users tagging and storing useful source code snippets

// description of your code here

// insert code here..


<?php

$_POST['id']['other'] = 'val1';

/*
key exist (same as $_POST['id'][other])
*/
echo getRequestParam('id[other]', 'default value');

/*
key doesn't exist, we get default value (same as $_POST['var'])
*/

echo getRequestParam('var', 'default value');

function getRequestParam( $var, $default = '', $method = 'post' )
{
preg_match_all('!(\w+)!i',$var, $match );
array_shift($match);
$_vars = $match[0];
$ret = null;

if( strtoupper($method) == 'POST' ) {
$ret = _findRequestParam($_vars, $_POST);
}
elseif( strtoupper($method) == 'GET' ) {
$ret = _findRequestParam($_vars, $_GET);
}
elseif( strtoupper($method) == 'COOKIE' ) {
$ret = _findRequestParam($_vars, $_COOKIE);

}
elseif( strtoupper($method) == 'SESSION' ) {
$ret = _findRequestParam($_vars, $_SESSION);
}

if (! $ret )
return $default;
else
return $ret;

}

/**
@access private
*/

function _findRequestParam($vars, $find_in , $curr_key = 0)
{
static $ret;

if( array_key_exists($vars[$curr_key], $find_in) ) {
if( count( $vars)-1 == $curr_key ) {
$ret = $find_in[$vars[$curr_key]];
}
elseif( $curr_key < count( $vars)-1 ) {
_findRequestParam( $vars, $find_in[$vars[$curr_key]], $curr_key+1 );
}
}

return $ret;

}

?>
Altın Fiyatları
Revizyon ile Organize Matbaacılık Brnckvvtmllttrhaberi

Subscribe to a RSS feed of your posts

// description of your code here

// insert code here..


<?php

$_POST['id']['other'] = 'val1';

/*
key exist (same as $_POST['id'][other])
*/
echo getRequestParam('id[other]', 'default value');

/*
key doesn't exist, we get default value (same as $_POST['var'])
*/

echo getRequestParam('var', 'default value');

function getRequestParam( $var, $default = '', $method = 'post' )
{
preg_match_all('!(\w+)!i',$var, $match );
array_shift($match);
$_vars = $match[0];
$ret = null;

if( strtoupper($method) == 'POST' ) {
$ret = _findRequestParam($_vars, $_POST);
}
elseif( strtoupper($method) == 'GET' ) {
$ret = _findRequestParam($_vars, $_GET);
}
elseif( strtoupper($method) == 'COOKIE' ) {
$ret = _findRequestParam($_vars, $_COOKIE);

}
elseif( strtoupper($method) == 'SESSION' ) {
$ret = _findRequestParam($_vars, $_SESSION);
}

if (! $ret )
return $default;
else
return $ret;

}

/**
@access private
*/

function _findRequestParam($vars, $find_in , $curr_key = 0)
{
static $ret;

if( array_key_exists($vars[$curr_key], $find_in) ) {
if( count( $vars)-1 == $curr_key ) {
$ret = $find_in[$vars[$curr_key]];
}
elseif( $curr_key < count( $vars)-1 ) {
_findRequestParam( $vars, $find_in[$vars[$curr_key]], $curr_key+1 );
}
}

return $ret;

}

?>
Altın Fiyatları
Revizyon ile Organize Matbaacılık Brnckvvtmllttrhaberi

Inline Mp3player for HTML

// Adds a neat Flash player for evry Mp3 file in a Website.

<script type="text/javascript">
var all = document.getElementsByTagName('a')
for (var i = 0, o; o = all[i]; i++) {
	if(o.href.match(/\.mp3$/i)) {
		var player = document.createElement('span')
		//var tit = o.innerHTML.toString();
		//var tit = ""
		var val = 
			"playerID=1&amp;soundFile="+o.href+"&amp;titles=&amp;artists=&amp;autostart=no&amp;" +
			"loader=0x1030cc&amp;border=0xecf2fa&amp;bg=0xecf2fa&amp;tracker=0xd5e3f4&amp;leftbg=0xd5e3f4&amp;" +
			"rightbg=0xd5e3f4&amp;rightbghover=0x6797d3&amp;lefticon=0x1030cc&amp;righticon=0x1030cc&amp;" + 
			"voltrack=0x6797d3&amp;volslider=0x1030cc"
		player.innerHTML = 
			'<object type="application/x-shockwave-flash" data="/misc/audioplayer.swf" id="player1" height="24" width="479">' +
			'<param name="movie" value="/misc/audioplayer.swf">' +
			'<param name="FlashVars" value='+val+'>' +
			'<param name="quality" value="high">' +
			'<param name="menu" value="false">' +
			'<param name="wmode" value="transparent">' +
			'</object>'
		o.parentNode.insertBefore(player, o)
	}
}
</script>

roundTo function in Actionscript

This function takes an input value and rounds it to the nearest value of the rTo parameter.

function roundTo(num:Number,rTo:Number):Number
{
	return Math.round(num / rTo) * rTo;
}


Occasionally there is a rounding error and you get a long string of decimals of 0's or 9's followed by another number. I can't figure out a way of changing this.

This can also be changed to floorTo or ceilTo depending on what you need.

Django and Open-flash-charts

// Found this on the django-users mailing list, need to test
ok, I finally got open-flash-chart to work.

1. create an xhtml-file and insert (something like) this:

    <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
        codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/
flash/swflash.cab#version=8,0,0,0"
        width="600"
        height="400"
        id="graph-2"
        align="middle">
    <param name="allowScriptAccess" value="sameDomain" />
    <param name="movie" value="/media/site/chart/open-flash-chart.swf?
width=600&height=400&data=/chart_data/" />
    <param name="quality" value="high" />
    <param name="bgcolor" value="#FFFFFF" />
    <embed src="/media/site/chart/open-flash-chart.swf?
width=600&height=400&data=/chart_data/"
        quality="high"
        bgcolor="#FFFFFF"
        width="600"
        height="400"
        name="open-flash-chart"
        align="middle"
        allowScriptAccess="sameDomain"
        type="application/x-shockwave-flash"
        pluginspage="http://www.macromedia.com/go/getflashplayer"; />
    </object>

2. define the url for the chart, eg: (r'^chart/$',
'www.views.charts.chart'),

3. define the url for the chart-data, e.g.: (r'^chart_data/$',
'www.views.charts.chart_data'),

4. the views:

def chart(request):

   ### nothing really required. whatever you want to do here. points
to the html-file created above

    return render_to_response('site/charts/chart.html', {
        'var': 'var',
    }, context_instance=RequestContext(request) )


def chart_data(request):

    import random

    g = graph()

    data_1 = []
    data_2 = []
    data_3 = []
    for i in range(12):
      data_1.append( random.randint(14,19) )
      data_2.append( random.randint(8,13) )
      data_3.append( random.randint(1,7) )

    g.title('PageViews (2007)', '{color: #999999; font-size: 16; text-
align: center}' );
    g.bg_colour = '#ffffff'

    # we add 3 sets of data:
    g.set_data( data_1 )
    g.set_data( data_2 )
    g.set_data( data_3 )

    # we add the 3 line types and key labels
    g.line_dot( 3, 5, '#333333', 'Page views', 10 )
    g.line_dot( 3, 5, '#666666', 'Visits', 10)    # <-- 3px thick +
dots
    g.line_hollow( 2, 4, '#999999', 'Unique visitors', 10 )


g.set_x_labels( 
'Jänner,Februar,März,April,Mai,Juni,Juli,August,September,Oktober,November,Dezember'.split(',')
 )
    g.set_x_label_style( 11, '0x666666', 2, 1)

    g.set_y_max(20)
    g.y_label_steps(4)
    g.set_y_label_style( 10, '0x666666')

    return HttpResponse(g.render())


Stage Align

// STAGEALIGN

var stageListener:Object = new Object();
stageListener.originalWidth = 1000;
stageListener.originalHeight = 700;
Stage.scaleMode = "noScale";
Stage.align = "B";
updateStage = function () {
if (selectedPage == undefined) {
lepel._height = Stage.height;
}
lepel._width = Stage.width+2;
sky.bg._width = Stage.width;
sky.bg._height = Stage.height;
sky["sky"+selectedPage].linear._width = Stage.width+2;
footerBg.Update();
};
stageListener.onResize = function() {
StageLeft = -1*(Stage.width-this.originalWidth)/2;
StageTop = -1*(Stage.height-this.originalHeight);
StageRight = StageLeft+Stage.width;
StageBottom = 700;
updateStage();
};
stageListener.onResize();
Stage.addListener(stageListener);