Tag Archive for object

Store/retrieve object in session

//On Login page
User currentUser = <get the User entity here, including relations to UserRights>;
Session.Add("CurrentUser", currentUser);

//On another page
User restoredUser = Session["CurrentUser"] as User;
if (restoredUser != null)
{
	//use the User entity here to check user's rights
}

source

Object to array

function object_to_array($object){
	$new = NULL;
	if (is_object($object)) {
		$object = (array) $object;
	}
	if (is_array($object)) {
		$new = array();
		foreach ($object as $key => $val) {
			$key = preg_replace("/^(.*)/", "", $key);
			$new[$key] = $this->object_to_array($val);
		}
	} else {
		$new = $object;
	}
	return $new;
}

source

Timer Object

// Learning Processing // Daniel Shiffman // <a href="http://www.learningprocessing.com" >http://www.learningprocessing.com</a> // Example 10-5: Object-oriented timer class Timer { int savedTime; // When Timer started int totalTime; // How long Timer should last Timer(int tempTotalTime) { totalTime = tempTotalTime; } // Starting the timer void start() { // When the timer starts it stores the current time in milliseconds. savedTime = millis(); } // The function isFinished() returns true if 5,000 ms have passed. // The work of the timer is farmed out to this method. boolean isFinished() { // Check how much time has passed int passedTime = millis()- savedTime; if (passedTime > totalTime) { return true; } else { return false; } } }

source

XHTML válido para adicionar Flash

<object id="" type="application/x-shockwave-flash" data="file.swf" width="300" height="250">
<param name="movie" value="file.swf" />
<param name="wmode" value="transparent" />
</object>

source

Utilisation de mysqli (syntaxe objet)

<?php

/* how to create connexion (4th parameter = default database) */
$mysqli = new mysqli($host, $usr, $pass, $db);

/* how to verify connexion */
if (mysqli_connect_errno()) {
    printf("Echec de la connexion : %s
", mysqli_connect_error());
}

/* how to set the default charset to use */
if (!$mysqli->set_charset("utf8")) {
   printf("Erreur lors du chargement du jeu de caractères utf8 : %s
", $mysqli->error);
}

/* how to use real_escape_string on string */
$nom = $mysqli->real_escape_string($nom);
$mail = $mysqli->real_escape_string($mail);
$tel = $mysqli->real_escape_string($tel);


/*how to get data in a table with a while */
$query = "SELECT nom, mail, tel FROM ufr_jury ORDER by nom;";
$ressource = $mysqli->query($query);
while($result = $ressource->fetch_assoc()){
						
	echo "<tr>";
							
	echo "<td>".$result['nom']."</td>";
	echo "<td>".$result['mail']."</td>";
	echo "<td>".$result['tel']."</td>";
							
	echo "</tr>";

}

/* how to free result ressource */
$ressource->close();
						
/* how to close connection */
$mysqli->close();

?>

source

SimpleSelector, Javascript DOM selector

/*!
 * $imple$elector
 *
 * Selector by id, className or tagName, f.e.:
 * $$( '#wrap' ) or $$( '.special' ) or $$( 'p' )
 *
 * Mulitple selectors seperated by comma, f.e.:
 * $$( '#id, .cls' )
 *
 * Give context as second param, f.e.:
 * $$( 'a', '#wrap' ) or $$( 'a', wrapNode ) or $$( 'a', [node1, node2] )
 *
 * @version   0.2
 * @author    Victor Villaverde Laan
 * @link      <a href="http://www.freelancephp.net/simpleselector-javascript-dom-selector/" >http://www.freelancephp.net/simpleselector-javascript-dom-selector/</a>
 * @license   MIT license
 */
var SimpleSelector = {

	/**
	 * Find elements with the given selector within the context
	 * @param selector [string]
	 * @param context  [string | DOM node | array of DOM nodes]
	 * @return [DOM node | array of DOM nodes | empty array]
	 */
	find: function ( selector, context ) {
		var selectors = selector.split( ',' ),
			elements = [],
			wrappers = [];

		// set wrappers
		if ( typeof context == 'string' ) {
			var wraps = SimpleSelector.find( context );
			// set array to wrappers
			wrappers = ( wraps.constructor == Array ) ? wraps : [ wraps ];
		} else if ( context && context.constructor == Array ) {
			wrappers = context;
		} else {
			// document is default context
			wrappers.push( context || document );
		}

		// find matching elements within the wrappers (context)
		for ( var a = 0, b = wrappers.length; a < b; a++ ) {
			for ( var x = 0, y = selectors.length; x < y; x++ ) {
				// selector: trim spaces
				var s = selectors[x].replace( / /g, '' ),
					// get operator
					operator = s.substr( 0, 1 ),
					// get key
					key = s.substr( 1 ),
					els = [];

				// get matching elements
				if ( operator == '#' ) {
					// get element by id
					els[0] = document.getElementById( key );
					// check if element is part of context
					if ( els[0] && SimpleSelector.isDescendant( els[0], wrappers[ a ] ) )
						elements.push( els[0] );
				} else if ( operator == '.' ) {
					// get element by className
					els = SimpleSelector.getByClass( key, wrappers[ a ] );
					// convert type to array
					els = [].slice.call( els, 0 );
					// add to elements collection
					elements = elements.concat( els );
				} else {
					// get element by tagName
					els = wrappers[ a ].getElementsByTagName( s );
					// add to elements collection
					// in this case [].slice.call( els, 0 ) does not work
					// in IE, says constructor is undefined??
					for ( var i = 0, j = els.length; i < j; i++ )
						elements.push( els[ i ] );
				}
			}
		}

		// return single element or array of elements
		return ( elements.length == 1 ) ? elements[0] : elements;
	},

	/**
	 * Check wether an element is a descendant of the given ancestor
	 * @param descendant [DOM node]
	 * @param ancestor   [DOM node]
	 * @return [boolean]
	 */
	isDescendant: function ( descendant, ancestor ) {
		return ( ( descendant.parentNode == ancestor )
					|| ( descendant.parentNode != document )
				&& arguments.callee( descendant.parentNode, ancestor ) );
	},

	/**
	 * Cross browser function for getting elements by className
	 * @param className [string]
	 * @param context   [DOM node]
	 * @return [array of DOM nodes]
	 */
	getByClass: function ( className, context ) {
		var elements = [],
			expr = new RegExp('b' + className + 'b'),
			wrapper = context || document,
			allElements = wrapper.getElementsByTagName( '*' );

		// filter all elements that contain the given className
		for ( var x = 0, y = allElements.length; x < y; x++ ) {
			if ( expr.test( allElements[ x ].className ) )
				elements.push( allElements[ x ] );
		}

		return elements;
	}

};

// if global $$ is not set
if ( ! window.$$ )
	window.$$ = SimpleSelector.find;

source

if(property in object)

var x = ("foo" in myObject)? myObject[foo] : false;

for(keyName in myObject){}

source

Creating an array of objects to store atom rss data

<?php
error_reporting(E_ALL); // shows all errors, remove this on live sites

$feedURL = '<a href="http://mydomain.com/rss/example.xml';" >http://mydomain.com/rss/example.xml';</a>
$getFILE = get_content($feedURL) or die("feed not loading");
$xml = simplexml_load_string($getFILE, NULL, LIBXML_NOCDATA); // Set CDATA as text nodes
$xml->registerXPathNamespace('atom', '<a href="http://www.w3.org/2005/Atom');" >http://www.w3.org/2005/Atom');</a> // define namespace atom

    class oEntry
    {
        public $url;
        public $author;
        public $date;
        public $text;
        
        function oEntry($url, $author, $date, $text) {
        	$this->url = $url;
        	$this->author = $author;
        	$this->date = $date;
        	$this->text = $text;
        }
    } 

	foreach($xml->xpath('atom:entry') as $entry) {
		// array of objects
		$e[] = new oEntry($xml->link['href'], $entry->author->name, $entry->published, $entry->content); 	
	} // end foreach

?>

SAMPLE XML INPUT (you need to fill out the tags):
<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="<a href="http://www.w3.org/2005/Atom"" >http://www.w3.org/2005/Atom"</a> xmlns:thr="<a href="http://purl.org/syndication/thread/1.0">" >http://purl.org/syndication/thread/1.0"></a>
  <link rel="alternate" type="text/html" href="" />
  <id></id>
  <updated></updated>
  <title></title>
  
  <entry>
    <id></id>
    <thr:in-reply-to ref="" type="text/html" href=""/>
    <link rel="alternate" type="text/html" href="" />
    <title></title>
    <author>
        <name></name>
        <uri></uri>
    </author>
    <content type="html" xml:lang="en-us" xml:base="">
        <![CDATA[<p>html text goes here</p>]]>
    </content>
    <published>February 20, 2010  2:23 AM</published>
  </entry>

</feed>

source

Convert Array to Object

// Converts an array to an object
function array2obj($data) 
{
    return is_array($data) ? (object) array_map(__FUNCTION__,$data) : $data;
}

source

From JSON/Object/Array to STRING

$.json = function(a1){
	t=[];
	if(typeof a1=='string') return a1;
	if(typeof a1=='object') for(var x in a1)t.push(x+"="+encodeURI(a1[x]));
	if(a1.constructor==Object) for(var i=0;i<a1.length;i++) t.push(a1[i].name+"="+encodeURIComponent(a1[i].value));
	if(a1.constructor==Array) for(var i=0;i<a1.length;i++) t.push(a1[i].name+"="+encodeURIComponent(a1[i].value));
	
	return t.join("&");
};

source