File put contents

Wednesday, March 17th, 2010

file_put_contents() is in php nowadays, but if you’re on an old server you may need your own.
This simply checks if the function’s there, and if not it makes the function.

  1. // Replacement for file_put_contents if it doesn't exist
  2. if(!function_exists('file_put_contents')){
  3.         function file_put_contents($file, $data){
  4.                 $fp = fopen($file, 'w');
  5.                 fwrite($fp, $data);
  6.                 fclose($fp);
  7.         }
  8. }

Display clean php code for copying

// Replacement for file_put_contents if it doesn't exist
if(!function_exists('file_put_contents')){
	function file_put_contents($file, $data){
		$fp = fopen($file, 'w');
		fwrite($fp, $data);
		fclose($fp);
	}
}

Check url

Wednesday, March 17th, 2010

This is a function that checks to see if a url exists.
Not mine btw, but for the life of me I can’t remember where I got it.

  1. // Check if a url exists
  2. function isValidUrl($url){
  3.                 $url = @parse_url($url);
  4.  
  5.                 if ( ! $url) {
  6.                         return false;
  7.                 }
  8.  
  9.                 $url = array_map('trim', $url);
  10.                 $url['port'] = (!isset($url['port'])) ? 80 : (int)$url['port'];
  11.                 $path = (isset($url['path'])) ? $url['path'] : '';
  12.  
  13.                 if ($path == '')
  14.                 {
  15.                         $path = '/';
  16.                 }
  17.  
  18.                 $path .= ( isset ( $url['query'] ) ) ? "?$url[query]" : '';
  19.  
  20.                 if ( isset ( $url['host'] ) AND $url['host'] != gethostbyname ( $url['host'] ) )
  21.                 {
  22.                         if ( PHP_VERSION >= 5 )
  23.                         {
  24.                                 $headers = get_headers("$url[scheme]://$url[host]:$url[port]$path");
  25.                         }
  26.                         else
  27.                         {
  28.                                 $fp = fsockopen($url['host'], $url['port'], $errno, $errstr, 30);
  29.  
  30.                                 if ( ! $fp )
  31.                                 {
  32.                                         return false;
  33.                                 }
  34.                                 fputs($fp, "HEAD $path HTTP/1.1\r\nHost: $url[host]\r\n\r\n");
  35.                                 $headers = fread ( $fp, 128 );
  36.                                 fclose ( $fp );
  37.                         }
  38.                         $headers = ( is_array ( $headers ) ) ? implode ( "\n", $headers ) : $headers;
  39.                         return ( bool ) preg_match ( '#^HTTP/.*\s+[(200|301|302)]+\s#i', $headers );
  40.                 }
  41.                 return false;
  42. }

Display clean php code for copying

// Check if a url exists
function isValidUrl($url){
		$url = @parse_url($url);

		if ( ! $url) {
			return false;
		}

		$url = array_map('trim', $url);
		$url['port'] = (!isset($url['port'])) ? 80 : (int)$url['port'];
		$path = (isset($url['path'])) ? $url['path'] : '';

		if ($path == '')
		{
			$path = '/';
		}

		$path .= ( isset ( $url['query'] ) ) ? "?$url[query]" : '';

		if ( isset ( $url['host'] ) AND $url['host'] != gethostbyname ( $url['host'] ) )
		{
			if ( PHP_VERSION >= 5 )
			{
				$headers = get_headers("$url[scheme]://$url[host]:$url[port]$path");
			}
			else
			{
				$fp = fsockopen($url['host'], $url['port'], $errno, $errstr, 30);

				if ( ! $fp )
				{
					return false;
				}
				fputs($fp, "HEAD $path HTTP/1.1\r\nHost: $url[host]\r\n\r\n");
				$headers = fread ( $fp, 128 );
				fclose ( $fp );
			}
			$headers = ( is_array ( $headers ) ) ? implode ( "\n", $headers ) : $headers;
			return ( bool ) preg_match ( '#^HTTP/.*\s+[(200|301|302)]+\s#i', $headers );
		}
		return false;
}

Normal smooth method

Wednesday, March 17th, 2010

On this post I’ll try to explain how the method for the Normal Smooth script works.


Concept

The idea is to reposition verticles so your mesh ends up nice and smooth. Of course there is already a function in Blender that does it, but that doesn’t take the actual “surface” of the mesh into account. So say you have a part of a perfect sphere selected, and you run the current internal function, it would flatten that selection, or even make it concave (hollow). That’s what we don’t want. In stead if you try to smooth a perfect sphere, it should not change anything. You can’t get smoother than a sphere!

See below here… that’s not nicely smoothed!


Smoothing the normal way

I’ll explain the concept in 2D. Lets say we want to smooth the position of vertex A and it’s connected to vertex B and C. Then we get the vertex normals for B and C. We then rotate those normal vectors 90 degrees towards A and make them half the length of the distance between that specific vert (B or C) and A. Once we have those, we find the points at the ends of those two vectors and place vert A at the midpoint between them.

But let me explain with a picture, which should help.


That’s just the basics

Of course there is a lot more that you can do with a script. Like looking further along the surface and using more normals. Also in 3d at times you have quads and you need to figure out what you want to do with the vert at the far end of the quad. Having non manifold meshes can be tricky too.

At least I hope this explains the idea a bit, and as ideas go…. it’s not too bad

Dolf

Mechanics math

Wednesday, March 17th, 2010

Here so I don’t have to search the internet to look for this stuff.

I’m working on some physics things for my swarm AI… tricky since I haven’t done any of this for ehm… 15 years or so.


Second law of Newton

F = m * a
a = F/m
m = F/a

F is force in newtons
m is mass in kilograms
a is acceleration in meters per second

Make a safe url

Wednesday, March 17th, 2010

This is a function that checks a string and makes it work nicely for friendly urls

  1. // Make sure a url string is nicely formatted
  2. function makeSafeUrl($myUrl, $allowSpace=0, $allowCase=0, $allowDot=0){
  3.         $sSafe = 'abcdefghijklmnopqrstuvwxyz1234567890-_';
  4.         $disallowed = array();
  5.         $disallowed['c'] = 'ç';
  6.         $disallowed['n'] = 'ñ';
  7.         $disallowed['y'] = 'ýÿ';
  8.         $disallowed['e'] = 'èéêë';
  9.         $disallowed['a'] = 'àáâãäå';
  10.         $disallowed['o'] = 'ðóòôõöø';
  11.         $disallowed['u'] = 'ùúûü';
  12.         $disallowed['i'] = 'ìíîï';
  13.  
  14.         if(!$allowSpace) $disallowed['-'] = ' ';
  15.         if($allowSpace) $sSafe .= ' ';
  16.  
  17.         if(!$allowDot) $disallowed['-'] = '.';
  18.         if($allowDot) $sSafe .= '.';
  19.  
  20.         if($allowCase){
  21.                 $sSafe .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  22.                 $disallowed['C'] = 'Ç';
  23.                 $disallowed['N'] = 'Ñ';
  24.                 $disallowed['Y'] = 'ÝŸ';
  25.                 $disallowed['E'] = 'ÈÉÊË';
  26.                 $disallowed['A'] = 'ÀÁÂÃÄÅ';
  27.                 $disallowed['O'] = 'ÐÓÒÔÕÖØ';
  28.                 $disallowed['U'] = 'ÙÚÛÜ';
  29.                 $disallowed['I'] = 'ÌÍÎÏ';
  30.         }else{
  31.                 $myUrl = strtolower($myUrl);
  32.         }
  33.  
  34.         $newString = array();
  35.  
  36.         for($i = 0; $i<strlen($myUrl); $i++){
  37.                 $thisChar = $myUrl[$i];
  38.                 if(stristr($sSafe, $thisChar)){
  39.                         $newString[$i] = $thisChar;
  40.                 }else{
  41.                         foreach($disallowed as $key => $var){
  42.                                 if(stristr($var, $thisChar)){
  43.                                         $newString[$i] = $key;
  44.                                 }
  45.                         }
  46.                 }
  47.         }
  48.         return implode('', $newString);
  49. }

Display clean php code for copying

 // Make sure a url string is nicely formatted
function makeSafeUrl($myUrl, $allowSpace=0, $allowCase=0, $allowDot=0){
	$sSafe = 'abcdefghijklmnopqrstuvwxyz1234567890-_';
	$disallowed = array();
	$disallowed['c'] = 'ç';
	$disallowed['n'] = 'ñ';
	$disallowed['y'] = 'ýÿ';
	$disallowed['e'] = 'èéêë';
	$disallowed['a'] = 'àáâãäå';
	$disallowed['o'] = 'ðóòôõöø';
	$disallowed['u'] = 'ùúûü';
	$disallowed['i'] = 'ìíîï';

	if(!$allowSpace) $disallowed['-'] = ' ';
	if($allowSpace) $sSafe .= ' ';

	if(!$allowDot) $disallowed['-'] = '.';
	if($allowDot) $sSafe .= '.';

	if($allowCase){
		$sSafe .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
		$disallowed['C'] = 'Ç';
		$disallowed['N'] = 'Ñ';
		$disallowed['Y'] = 'ÝŸ';
		$disallowed['E'] = 'ÈÉÊË';
		$disallowed['A'] = 'ÀÁÂÃÄÅ';
		$disallowed['O'] = 'ÐÓÒÔÕÖØ';
		$disallowed['U'] = 'ÙÚÛÜ';
		$disallowed['I'] = 'ÌÍÎÏ';
	}else{
		$myUrl = strtolower($myUrl);
	}

	$newString = array();

	for($i = 0; $i $var){
				if(stristr($var, $thisChar)){
					$newString[$i] = $key;
				}
			}
		}
	}
	return implode('', $newString);
}

List of all countries

Wednesday, March 17th, 2010

I found it helpfull to have this around from time to time.

Afghanistan, Albania, Algeria, American Samoa, Andorra, Angola, Anguilla, Antigua and Barbuda, Argentina, Armenia, Aruba, Australia, Austria, Azerbaijan, Bahamas, Bahrain, Bangladesh, Barbados, Belarus, Belgium, Belize, Benin, Bermuda, Bhutan, Bolivia, Bosnia, Botswana, Brazil, British Virgin Islands, Brunei, Bulgaria, Burkina Faso, Burundi, Cambodia, Cameroon, Canada, Cape Verde, Cayman Islands, Central African Republic, Chad, Chile, China, Colombia, Comoros, Costa Rica, Cote d’Ivoire, Croatia, Cuba, Cyprus, Cyprus, Czech Republic, Democratic Republic of the Congo, Denmark, Djibouti, Dominica, Dominican Republic, East Timor, Ecuador, Egypt, Egypt, El Salvador, Equatorial Guinea, Eritrea, Estonia, Ethiopia, Falkland Islands, Fiji, Finland, France, French Guiana, French Polynesia, Gabon, Gambia, Georgia, Germany, Ghana, Gibraltar, Greece, Greenland, Grenada, Guadeloupe, Guam, Guatemala, Guinea, Guinea-Bissau, Guyana, Haiti, Honduras, Hungary, Iceland, India, Indonesia, Iran, Iraq, Ireland, Israel, Italy, Jamaica, Japan, Jordan, Kazakhstan, Kenya, Kiribati, Kuwait, Kyrgyzstan, Laos, Latvia, Lebanon, Lesotho, Liberia, Libya, Liechtenstein, Lithuania, Luxembourg, Macau, Macedonia, Madagascar, Malawi, Malaysia, Maldives, Mali, Malta, Marshall Islands, Martinique, Mauritania, Mauritius, Mexico, Mexico, Micronesia, Moldova, Monaco, Mongolia, Montenegro, Montserrat, Morocco, Mozambique, Myanmar, Namibia, Nauru, Nepal, Netherlands, Netherlands Antilles, New Caledonia, New Zealand, Nicaragua, Niger, Nigeria, North Korea, Northern Mariana Islands, Norway, Oman, Pakistan, Palau, Palestine, Panama, Papua New Guinea, Paraguay, Peru, Philippines, Pitcairn Islands, Poland, Portugal, Puerto Rico, Qatar, Republic of the Congo, Romania, Russia, Rwanda, San Marino, Sao Tome and Principe, Saudi Arabia, Senegal, Serbia, Seychelles, Sierra Leone, Singapore, Slovakia, Slovenia, Solomon Islands, Somalia, South Africa, South Korea, Spain, Sri Lanka, St. Kitts and Nevis, St. Lucia, St. Vincent and the Grenadines, Sudan, Suriname, Swaziland, Sweden, Switzerland, Syria, Taiwan, Tajikistan, Tanzania, Thailand, Tibet, Togo, Tonga, Trinidad and Tobago, Tunisia, Turkey, Turkey, Turkey, Turkmenistan, Turks and Caicos Islands, Tuvalu, U.S. Virgin Islands, Uganda, Ukraine, United Arab Emirates, United Kingdom, United States, Uruguay, Uzbekistan, Vanuatu, Venezuela, Vietnam, Western Sahara, Western Samoa, Yemen, Zambia, Zimbabwe

JQuery geshi

Wednesday, March 17th, 2010

Code highlighting using ajax with jquery and geshi

  1. $(document).ready(function(){
  2.  
  3.         // Initialise highlighting
  4.         if($('pre').length){
  5.                 $('pre').each(function(){
  6.                         highLight($(this));
  7.                 });
  8.         }
  9.  
  10. });
  11.  
  12. // Highlight item
  13. function highLight(thisItem){
  14.         snippet  = thisItem.html();
  15.         snippet = snippet.replace(/&amp;amp;/ig, escape('&'));
  16.         snippet = snippet.replace(/&lt;/ig, '<');
  17.         snippet = snippet.replace(/&gt;/ig, '>');
  18.         language = thisItem.attr('class');
  19.         $.ajax({
  20.                 type: "POST",
  21.                 url: '/scripts/highlight.php',
  22.                 data: 'language='+language+'&snippet='+snippet,
  23.                 dataType: "html",
  24.                 success: function(msg){
  25.                         if (msg){
  26.                                 msg = msg.replace('&amp;', '&');
  27.                                 thisItem.after(msg);
  28.                                 thisItem.hide();
  29.                         }
  30.                 }
  31.         });
  32. }

Display clean javascript code for copying

$(document).ready(function(){

	// Initialise highlighting
	if($('pre').length){
		$('pre').each(function(){
			highLight($(this));
		});
	}

});

// Highlight item
function highLight(thisItem){
	snippet  = thisItem.html();
	snippet = snippet.replace(/&amp;amp;/ig, escape('&'));
	snippet = snippet.replace(/&lt;/ig, '<');
	snippet = snippet.replace(/&gt;/ig, '>');
	language = thisItem.attr('class');
	$.ajax({
		type: "POST",
		url: '/scripts/highlight.php',
		data: 'language='+language+'&snippet='+snippet,
		dataType: "html",
		success: function(msg){
			if (msg){
				msg = msg.replace('&amp;', '&');
				thisItem.after(msg);
				thisItem.hide();
			}
		}
	});
}

Make a safe url

Wednesday, March 17th, 2010

This is a function that makes a string url safe.
Nice for creating friendly urls that are actually friendly.

  1. // Function for making sure text only uses url safe symbols
  2. function makeSafe(thisText, allowSpace){
  3.         var w = "!@#$%^&*()+=[]\\\';,./{}|\":<>?";
  4.         var s = 'abcdefghijklmnopqrstuvwxyz0123456789-_';
  5.         var x = new Array('àáâãäå', 'ç', 'èéêë', 'ìíîï', 'ñ', 'ðóòôõöø', 'ùúûü', 'ýÿ');
  6.         var r = new Array('a', 'c', 'e', 'i', 'n', 'o', 'u', 'y');
  7.  
  8.         if(allowSpace){
  9.                 s = s + ' ';
  10.         }
  11.  
  12.         thisText = thisText.toLowerCase();
  13.         var newText = new Array();
  14.  
  15.         for (i = 0; i < thisText.length; i++){
  16.                 thisChar = thisText.charAt(i);
  17.                 if(w.indexOf(thisChar) == -1){
  18.                         if(s.match(''+thisChar+'')){
  19.                                 newText[i] = thisChar;
  20.                         }else{
  21.                                 for (j = 0; j < x.length; j++){
  22.                                         if(x[j].match(thisChar)){
  23.                                                 newText[i] = r[j];
  24.                                         }
  25.                                 }
  26.                         }
  27.                 }
  28.         }
  29.  
  30.         return newText.join('');
  31. }

Display clean javascript code for copying

// Function for making sure text only uses url safe symbols
function makeSafe(thisText, allowSpace){
	var w = "!@#$%^&*()+=[]\\\';,./{}|\":<>?";
	var s = 'abcdefghijklmnopqrstuvwxyz0123456789-_';
	var x = new Array('àáâãäå', 'ç', 'èéêë', 'ìíîï', 'ñ', 'ðóòôõöø', 'ùúûü', 'ýÿ');
	var r = new Array('a', 'c', 'e', 'i', 'n', 'o', 'u', 'y');

	if(allowSpace){
		s = s + ' ';
	}

	thisText = thisText.toLowerCase();
	var newText = new Array();

	for (i = 0; i < thisText.length; i++){
		thisChar = thisText.charAt(i);
		if(w.indexOf(thisChar) == -1){
			if(s.match(''+thisChar+'')){
				newText[i] = thisChar;
			}else{
				for (j = 0; j < x.length; j++){
					if(x[j].match(thisChar)){
						newText[i] = r[j];
					}
				}
			}
		}
	}

	return newText.join('');
}

Find root folder

Wednesday, March 17th, 2010

I use this tiny snippet that uses jquery to find the root folder of my website.
It assumes jquery.js is included in the page.
It’s usefull for finding out where to post ajax stuff to (so you have a complete root).

For this website it would look in the header of the html for:
<script type="text/javascript" src="http://www.macouno.com/js/jquery.js"></script>

  1. // Get the source directory of this script
  2. root = $('script[@src$=jquery.js]').attr('src').replace('js/jquery.js', '');
  3. if(!location.href.match('www')){
  4.         root = root.replace('www.', '');
  5. }

Display clean javascript code for copying

// Get the source directory of this script
root = $('script[@src$=jquery.js]').attr('src').replace('js/jquery.js', '');
if(!location.href.match('www')){
	root = root.replace('www.', '');
}

Add to tinymce

Wednesday, March 17th, 2010

Because I will forget unless I save a copy here.
This is a very basic function for adding a string to tinymce (I use it to add images that are listed elsewhere on a page).

  1. // Adding content to the end of the tinymce editor
  2. function addToTiny(newContent){
  3.         var inst = tinyMCE;
  4.         inst.execCommand('mceFocus',false,'content');
  5.         inst.execCommand('mceInsertContent', true, newContent);
  6. }

Display clean javascript code for copying

// Adding content to the end of the tinymce editor
function addToTiny(newContent){
	var inst = tinyMCE;
	inst.execCommand('mceFocus',false,'content');
	inst.execCommand('mceInsertContent', true, newContent);
}
click here to close

Help keep these files free,
and support further development!