PHP Humaniser l'affichagededuréesécoulées

/**Function when($ts) takes timestamp on input and returns
  * human readable time difference. Example output:
  * I am running my script in 20 minute intervals to clear the
  * database and remove overhead.
**/

function kiedy($ts) {
   $ts=time()-$ts;
   if ($ts<60)
       // <1 minute
       return $ts; //." seconds ago";
     elseif ($ts<60*60)
       // <1 hour
       return floor($ts/60); //." minutes ago";
   elseif ($ts<60*60*2)
       // <2 hour
       return "60"; //"1 hour ago";
     elseif ($ts<60*60*24)
       // <24 hours = 1 day
       return floor($ts/60*60); //." hours ago";
     elseif ($ts<60*60*24*2)
       // <2 days
       return "1 day ago";
     elseif ($ts<60*60*24*7)
       // <7 days = 1 week
         return floor($ts/60*60*24); //." days ago";
   elseif ($ts<60*60*24*30.5)
       // <30.5 days ~  1 month
       return floor($ts/60*60*24*7); //." weeks ago";
     elseif ($ts<60*60*24*365)
       // <365 days = 1 year
       return floor($ts/60*60*24*30.5); //." months ago";
   else
       // more than 1 year
       return floor($ts/60*60*24*365); //." years ago";
};

$link = mysql_connect("localhost", "database", "pwd");
mysql_select_db("database");
$res = mysql_query("SELECT timestamp from chattable ORDER by timestamp DESC");
while ($line = mysql_fetch_array($res, MYSQL_ASSOC)) {
    $ts = $line['timestamp'];
    $result=kiedy($ts);
    if ($result > 20 ) {  // ADJUST THIS TO CLEAR X MINUTES
        $SQL = "DELETE from chattable WHERE timestamp = '$ts'";
        $resultD = mysql_query($SQL);
    }
}

$SQL = 'OPTIMIZE TABLE chattable';
$resultO = mysql_query($SQL);

Ruby Verificar o meus jogos na mega-sena e lotomaniaquefaçoutilizandoteimosinha

#! /usr/bin/env ruby

require 'rubygems'
require 'open-uri'
require 'hpricot'

megasena_jogos = 897..898
megasena_apostas = [[1, 2, 3, 4, 5, 6], [1, 11, 12, 21, 22, 23]]

lotomania_jogos = 753..754
lotomania_apostas = [[1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 16, 18, 20, 22, 25, 26, 28, 29, 30, 31, 33, 34, 35, 38, 50, 51, 53, 61, 62, 63, 65, 68, 72, 76, 77, 79, 80, 81, 82, 85, 87, 90, 91, 92, 93, 94, 96, 99]]

puts '======= Lotomania ===================================================='
lotomania_jogos.each do |jogo|
  doc = open("http://www1.caixa.gov.br/loterias/loterias/lotomania/_lotomania_pesquisa.asp?submeteu=sim&opcao=concurso&txtConcurso=#{jogo}").string
  numeros_sorteados = doc.gsub(/.*<\/a>\|/, '').gsub(/,.*/m, '').split('|')[0, 20].collect{|n| n.to_i}
  break if numeros_sorteados.size < 20
  lotomania_apostas.each_with_index do |aposta, i|
    acertos = aposta & numeros_sorteados
    puts "No jogo #{jogo} aposta #{i + 1}a voce acertou #{acertos.size} numero(s): #{acertos.inspect}"
    
    acertos = ((0..99).to_a - aposta) & numeros_sorteados
    puts "No jogo #{jogo} aposta #{i + 1}b voce acertou #{acertos.size} numero(s): #{acertos.inspect}"
  end
end

puts '======= Mega Sena ===================================================='
megasena_jogos.each do |jogo|
  doc = Hpricot(open("http://www1.caixa.gov.br/loterias/loterias/megasena/megasena_pesquisa_new.asp?submeteu=sim&opcao=concurso&txtConcurso=#{jogo}"))
  numeros_sorteados = doc.search("//span[@id='num_sorteio']/ul/li/").collect{|n| n.to_s.to_i}.uniq.sort
  break if numeros_sorteados.empty?
  megasena_apostas.each_with_index do |aposta, i|
    acertos = aposta & numeros_sorteados
    puts "No jogo #{jogo} aposta #{i + 1} voce acertou #{acertos.size} numero(s): #{acertos.inspect}"
    puts "VOCÊ GANHOU!!!!!!!!!!!!!!!!!!!!!!!!!!!!" if acertos.size == 6
  end
end

PHP 函数打包到SpeedUp Web表单创建过程。 V.0.2Beta

<?php
   class forms implements iforms{
   	
   		var $_inited=false;
		var $_form=array();
   		var $_elems=array();
					/**_elems: array(
						array('id'=>'','name'=>'login','value'=>'','validate'=>true,'params'=>'','on'=>array('click'=>'event'))
					);**/
					/**
					_fields: array('id'=>'','label'=>"Enter your login:","value"=>"el:21551","type"=>"pair","style"=>"");
					**/
		var $_fields=array();
		var $_patterns=array();
		var $_css=array();
		var $_js=array();
		var $_data='';
	
	
		/**
		 * Constructor. Make new instance of the form container.
		 * @return 
		 * @param $method Object
		 * @param $action Object
		 * @param $encoding Object
		 * @param $params Object[optional]
		 */
		
		public function init($method,$action,$encoding='',$name='',$id='',$params=array())
		{
				$id=($id)?'f_'.md5($time.$name.$action).'_'.mt_rand(10,99):'';
				if($this->correctMethod($method) && !$this->_inited){
					$this->_data='';
					$this->_form['method']=$method;
					$this->_form['action']=$action;
					$this->_form['encoding']=$encoding;
					$this->_form['params']=$params;
					$this->_form['id']=$id;
					$this->_form['name']=$name;
					$this->initOthers();
					$this->initPatterns();
					$this->_inited=true;
				}else{
					return IFORM_WRONG_METHOD;	
				}
		}
		
		protected function initOthers(){
			//CSS
			$this->css['pairFieldLabelClass']='label';
			$this->css['singleFieldLabelClass']='label label1 center';
			$this->css['sinleFieldLabelStyle']='width:100%;clear:both;';
			$this->css['formLegendClass']='legend';
			$this->css['pairFieldValueClass']='value value1';
			$this->css['pairFieldLabelClass']='label';
			$this->css['rowClass']='row';
			$this->css['formMainClass']='form';
			$this->css['submit']='submit center';
			
			//JS
			$this->js['validateFunct']='Invis.tools.checkValue(this.id);';
		}
		
		public function addLegend($text){
			$this->_form['legend']=sprintf($this->_patterns['formLegend'],$text);
		}
		protected function correctMethod($method)
		{
			switch($method){
				case 'GET':
				case 'POST':
				case 'PUT':
				return true;
			}
			return false;
		}
		
		/**
		 * Append eventHandler to added to form input element
		 * @return integer
		 * @param $name String 
		 * @param $event String
		 * @param $handler String
		 */
		public function addEventHandler($name,$event,$handler){
			if(trim($name)!='' && trim($event)!='' && trim($handler)!=''){
				for($i=0;$i<count($this->_elems);$i++){
					if($this->_elems['name']==$name){
						$this->_elems[$i]['on'][]=array($event=>$handler);
						break;
					}
				}
			}else{
				return IFORM_WRONG_PARAMS;
			}
			return 1;
		}
		
		/**
		 * Add submit control to the form
		 * @return void
		 * @param $name Object
		 * @param $value Object
		 * @param $style Object[optional]
		 */
		public function addSubmit($name,$value,$params=array())
		{
			if(trim($name)!=''){
				$this->_submit=sprintf($this->_patterns['submit'],$name,$value,$this->_prepareParams($params));
			}else{
				return IFROM_WRONG_PARAMS;
			}
		}
		
		/**
		 * Check that element with value of type $type equals $value
		 * @return integer
		 * @param $type String
		 * @param $value String
		 */
		protected function elemExists($type,$value)
		{
			for($i=0;$i<count($this->_elems);$i++){
				switch($type)
				{
					case 'name':
						if($this->_elems[$i]['name']==$value)return 1;
					break;
					case 'id':
						if($this->_elems[$i]['id']==$value)return 1;
					break;		
				}
			}
			return 0;
		}
		
		/**
		 * Set "important" parameter to the $id - input element
		 * @return integer
		 * @param $name String
		 */
		public function validateElement($id)
		{
			if(trim($name)==''){
				return IFORM_WRONG_PARAMS;
			}else{
				if(!$this->elemExists("id",$id)){
					return IFORM_WRONG_ELEM;
				}else{
					//FIX ERROR
					$this->_elems[array_search($name,$this->_elems)]['validate']=true;
				}
			}
			return 1;
		}
		
		/**
		 * Add input element to the current form
		 * @return String 
		 * @param $type String
		 * @param $name String
		 * @param $parent String
		 * @param $id String[optional]
		 * @param $value String[optional]
		 * @param $validate Boolean[optional]
		 * @param $params String[optional]
		 */
		public function addInput($type,$name,$parent,$id='',$value='',$validate=false,$params='')
		{
			if(trim($type)!='' && trim($name)!='' && trim($parent)!=''){
				$id=(!$id)?'i'.md5($name).'_'.count($this->_elems):$id;
				$this->_elems[]=array(
									'id'=>$id,
									'type'=>$type,
									'parent'=>$parent,
									'name'=>$name,
									'value'=>$value,
									'validate'=>$validate,
									'on'=>array(),
									'params'=>$params									
									);
			}else{
				return IFROM_WRONG_PARAMS;
			}
			return $id;
		}
		
		/**
		 * Add field to the form
		 * @return String 
		 * @param $label String
		 * @param $type String[optional]
		 * @param $el String[optional]
		 * @param $id String[optional]
		 * @param $params String[optional]
		 */
		public function addField($label,$type="pair",$value="",$id='',$params="")
		{
			$id=(!$id)?'f'.md5($label).'_'.count($this->_fields):$id;
			$this->_fields[]=array("id"=>$id,"label"=>$label,"type"=>$type,"value"=>$value,"type"=>$type,"style"=>$params);
			return $id;
		}
		
		
		/**
		 * Initialize system patterns
		 * @return void 
		 */
		protected function initPatterns()
		{
			$this->_patterns['form']='<form action="%s" method="%s" encoding="%s" %s>';
			$this->_patterns['inputI']='<input type="%s" name="%s" id="%s" %s %s %s/>';
			$this->_patterns['inputD']='<%s name="%s" id="%s" %s %s %s>%s</%s>';
			$this->_patterns['fieldsingle']='<div class="%s" style="width:100%;clear:both;" id="%s" %s%s</div>';
			$this->_patterns['fieldpair']='<div class="%s" %s id="%s"><span class="%s" style="%s">%s</span><span style="%s">%s</span></div>';
			$this->_patterns['formLegend']='<div class="'.$this->css['formLegendClass'].'">%s</div>';
			$this->_patterns['mainContainer']='<div class="'.$this->css['formMainClass'].'">';
			$this->_patterns['endContainer']='</div></form>';
			$this->_patterns['submit']='<div class="row"><span class=" '.$this->css['submitClass'].'" style="clear:both;"><input type="submit" name="%s" value="%s" %s/></span></div>';
		}
		
		
		/**
		 * Get inputs which referers to $parent-field
		 * @return String
		 * @param $parent Object
		 */
		protected function _getChildsInputs($parent)
		{
			$res='';
			for($i=0;$i<count($this->_elems);$i++)
			{
				if($this->_elems[$i]['parent']==$parent){
					switch($this->_elems[$i]['type']){
						case 'password':
						case 'checkbox':
						case 'text':
							$res.=sprintf(
								$this->_patterns['inputI'],
								$this->_elems[$i]['type'],
								$this->_elems[$i]['name'],
								$this->_elems[$i]['id'],
								($this->_elems[$i]['validate'])?'onclick="'.$this->js['validateFunct'].'"':'',
								$this->_getEvents($i),
								$this->_prepareParams($this->_elems[$i]['params'])
								);		
								break;		
						case 'select':
							$res.=sprintf(
								$this->_patterns['inputI'],
								$this->_elems[$i]['type'],
								$this->_elems[$i]['name'],
								$this->_elems[$i]['id'],
								($this->_elems[$i]['validate'])?'onclick="'.$this->js['validateFunct'].'"':'',
								$this->_getEvents($i),
								$this->_prepareParams($this->_elems[$i]['params'])
								);
								break;
						default:
							$res=IFORM_WRONG_TYPE;
					}
				}
			}
			return $res;
		}
		
		
		/**
		 * 
		 * @return String
		 * @param $elId Integer
		 */
		protected function _getEvents($elId){
			$result=null;
			if(array_search($elId,$this->_elems)!=-1){
				foreach($this->_elems[$elId]['on'] as $k=>$v)
				{
					$result.=' on'.$k.'="return '.$v.'();" ';
				}
			}else{
				$result=IFORM_NOT_EXISTS;
			}
			return $result;
		}
		
		private function _prepareParams($data)
		{
			$res=null;
			if(is_array($data)){
				foreach($data as $k=>$v)
				{
					$res.=$k."=\"".$data."\"";
				}	
			}
			return $res;
		}
		
		/**
		 * 
		 * @return String
		 */
		public function render($output=true)
		{//<form action="%s" method="%s" encoding="%s" style="%s" %s>
		#print_rbr($this->_elems);
		#die_br($this->_fields);
			$this->_data=sprintf($this->_patterns['form'],$this->_form['action'],$this->_form['method'],$this->_form['encoding'],$this->_prepareParams($this->_form['params']));
			$this->_data.=sprintf($this->_patterns['mainContainer']);
			$this->_data.=($this->_form['legend'])?$this->_form['legend']:'';
			#die($this->_data);
			$this->_data.='<input type="hidden" name="genericDATA" id="fX'.md5(time()).'" value="'.time().'"/>';
			for($i=0;$i<count($this->_fields);$i++)
			{#die_r($this->_fields[$i]);
				switch($this->_fields[$i]['type'])
				{
					
					case 'pair':
					//<div class="%s" id="%s"><span class="%s" style="%s">%s</span><span style="%s">%s(value)</span></div>'
						$this->_data.=sprintf(
											$this->_patterns['fieldpair'],
											$this->css['rowClass'],
											$this->_fields[$i]['params'],
											$this->_fields[$i]['id'],
											$this->css['pairFieldLabelClass'],
											$this->css['pairFieldLabelStyle'],
											$this->_fields[$i]['label'],
											$this->css['pairFieldValueClass'],
											($this->_fields[$i]['value']=='')?$this->_getChildsInputs($this->_fields[$i]['id']):$this->_fields[$i]['value']
											);
						
						break;
					case 'single':
						break;
				}
			}
			$this->_data.=$this->_submit;
			$this->_data.=sprintf($this->_patterns['endContainer']);
			return ($output)?$this->_data:'';
		}
		
		function getData()
		{
			return $this->_data;	
		}
		
   }
?>

Ruby 使用ruby播放文件

require 'rubygems'

class Player
  @@sound_path = ''
  @@sound_app = 'mpg321'
  @@process_devnull = '> /dev/null 2>&1'
  @@process_bg = '&'
  
  def self.sound_path=(value)
    @@sound_path = value
  end

  def self.sound_app=(value)
    @@sound_app = value
  end
                                  
  def self.process_devnull=(value)
    @@process_devnull = value
  end

  def self.process_bg=(value)
    @@process_bg = value
  end
  
  def self.play(file)
    cmd = "#{@@sound_app} #{@@sound_path + file} #{@@process_devnull} #{@@process_bg}"
    system cmd
  end
end

files = Dir.glob(File.join("/home/buildmaster/Desktop/sounds/error", "*.mp3"))
Player.play(files[rand(files.size)])

JavaScript 滚动到顶部 - JavaScript

<script language='javascript'>

function move_up() {
scroll_clipper.scrollTop = 0;
}

</script>

<a href='javascript:move_up()'>Move UP</a>

<p>

<div id='scroll_clipper'
style='position:absolute; width:150px; height: 150px; overflow:auto'>
<div id='scroll_text' style='background-color:yellow'>
Here is some content that can be scrolled.
<p>It uses two divs:<ul>
<li>scroll_clipper, and
<li>scroll_text
</ul>

scroll_clipper defines the scroll area while scroll_text
defines the text to be scrolled.

</div>
</div>

ActionScript 替换文字

function replaceText( field:TextField, toSearch:String, toReplace:String)
{
	return field.split(toSearch).join(toReplace);
};

trace(replaceText(display_txt.text, "a", "b"));

PHP 替代Print_r()

function dump($var){
	 echo '<pre>'.highlight_string("<?php\n".print_r( $var, true)."\n?>", true).'</pre><br />';
}
	
//example
$myvar = array('1','2');
dump($myvar);

ActionScript 3 Flash CS3:comunicazione con un Web Server

var variables:URLVariables = new URLVariables();
variables.miavariabile = "Ciao";
var request:URLRequest = new URLRequest();
request.url = "http://www.miodominio.com/miapagina.php";
request.method = URLRequestMethod.POST;
request.data = variables;
var loader:URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.TEXT;
loader.addEventListener(Event.COMPLETE, completeHandler);
try {
	loader.load(request);
} catch (error:Error) {
	trace("Errore nel caricamento dell' URL");
}
function completeHandler(event:Event):void {
	var x_xml:XML = XML(event.target.data);
	trace(x_xml);
}

PHP 正确偏差转换数字(俄语)

/**
 * Выбор нужного падежа числа
 *
 * Пригодится для локализации любых скриптов. Лучше подключать через
 * <code>
 * if ( ! function_exists ( "NumToRu" ) )
 * {
 * 
 * }
 * </code>
 * @param int $number Число, требующее падежа
 * @param str $one Форма для mod 10 == 1 и != 11
 * @param str $little Форма для mod 10 == 2, 3, 4 и != 12, 13, 14
 * @param str $many Форма для остальных случаев
 * @return string Нужная форма падежа
 */
function NumToRu ( $number, $one, $little, $many )
{
	if ( $number % 100 > 10 &&  $number % 100 < 15 )
	{
		return $many;
	}
	if ( $number % 10 == 1 )
	{
		return $one;
	}
	if ( $number % 10 > 1 && $number %10 < 5 )
	{
		return $little;
	}
	return $many;
}

Perl 备份您自己的snipplr.com片段

#!/usr/bin/perl
use strict;
use LWP::UserAgent;
my $silent = 0; # set to 1 for no output on stdout
my $logindata = {
    'username' => 'fill in your username',
    'password' => 'fill in your password',
                };
my $loginurl = 'http://snipplr.com/login/';
my $backupurl = 'http://snipplr.com/zipbackup.php';
my $backupdir = '.';

my $ua = LWP::UserAgent->new;
$ua->cookie_jar({ file => "cookies.txt" });

print qq{get cookie from frontpage...} unless $silent;
my $devnull = $ua->get('http://snipplr.com/'); #get cookie
print qq{done.\n} unless $silent;

print qq{login as $$logindata{'username'}...} unless $silent;
my $loginresponse = $ua->post($loginurl, $logindata);
print qq{done.\n} unless $silent;

print qq{exporting snipplr_backup.zip...} unless $silent;
my $backupfile = $ua->get($backupurl);
open (KI, ">$backupdir/snipplr_backup.zip");
binmode KI;
print KI $backupfile->content;
close (KI);
print qq{done.\n} unless $silent;