1. Home
  2. Blog
  3. Forum
  4. Sountrack to my Life



ARCHIVE
2011-11-24
November Twenty-Four Two Thousand Eleven

Thanksgiving & Codes & Grover!

Happy Thanksgiving Interwebs! Happy Birthday Grover!

I'm thankful that programming makes sense to me!

I've got a couple snippets to share, One of is some PHP+AJAX to grab the title element from a given url, mostly just so I don't have to wait for a page to load to check a link.
See: The File
Code:
 1 <?php
 2  error_reporting(!E_WARNING);
 3  $target = $_POST['url'];//'http://tylerthomas.me';
 4  $pass = preg_match('#(http|ftp|https)://[w-_]+(.[w-_]+)+([w-.,@?^=%&amp;:/~+#]*[w-@?^=%&amp;/~+#])?#i',$target);
 5  if($pass){
 6   $domdocument = new domdocument();
 7   $source = file_get_contents($target); 
 8   $domdocument->loadHTMLFile($target);
 9   $title = $domdocument->getElementsByTagName('title');
 10   echo $title->item(0)->nodeValue;
 11  }else{
 12   die('FAILURE - BAD URL: ' . $target);
 13  }
 14 ?>

See: The File
Code:
 1 <html>
 2  <head>
 3   <title>Grab Title</title>
 4   <script type="text/javascript">
 5    function AJAX(url, varString){
 6     var xmlHttp=null;
 7       try
 8      {
 9      // Firefox, Opera 8.0+, Safari
 10      xmlHttp=new XMLHttpRequest();
 11      }
 12       catch (e)
 13      {
 14      // Internet Explorer
 15      try
 16        {
 17        xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
 18        }
 19      catch (e)
 20        {
 21        xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
 22        }
 23      }
 24     if (xmlHttp==null)
 25       {
 26       alert ("Your browser does not support AJAX!");
 27       return;
 28       } 
 29     
 30     xmlHttp.onreadystatechange = function() {
 31      if (xmlHttp.readyState == 4 && xmlHttp.status==200){
 32       
 33        document.getElementById('title').innerHTML = xmlHttp.responseText; //Do something iwth response if you like.
 34       
 35      }
 36     }
 37     
 38     xmlHttp.open("POST",url,true);
 39     xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
 40     xmlHttp.send(varString);
 41    }
 42    function grabTitle(url){
 43     //alert('ha');
 44     AJAX('grabtitle.php','url='+url)
 45    }
 46    
 47   </script>
 48  </head>
 49  <body onload="" onclick="">
 50   
 51   <h3>Grab a page title</h3>
 52   <p>enter a url starting with http://, hit enter</p>
 53   <form onsubmit="grabTitle(document.getElementById('url').value);return false;">
 54    <input type="text" id="url" value="" />
 55   </form>
 56   <div id="title"></div>
 57  </body>
 58 </html>


And another is mostly just me playing in object oriented JS, but it's an interesting perspective on bandwidth.
See: The File
Code:
 1 
 2 <html>
 3  <head>
 4   <script type="text/javascript">
 5    var DLDATA = function(){  
 6     this.container = document.getElementById('container');
 7     this.first = false;
 8     this.second = false;
 9     this.rangeIDstr = 'ratesizetime';//used for the ranking of sliders to decide math, pretty sexy
 10     
 11     this.recalc = function(slider, reset){
 12      /*default params*/
 13      reset = reset || false;
 14      /*end default params*/     
 15      if(this.first && this.second && this.second != id){
 16       this.first = this.second;
 17       this.second = false;
 18       this.rangeIDstr = 'ratesizetime';
 19       this.rangeIDstr = this.removeStr(this.first, this.rangeIDstr);
 20       return;
 21      }
 22      /*prelims*/    
 23      rate = document.getElementById('rate'); 
 24      rateval = document.getElementById('rateval'); 
 25      raterank = document.getElementById('raterank'); 
 26      size = document.getElementById('size');  
 27      sizeval = document.getElementById('sizeval'); 
 28      sizerank = document.getElementById('sizerank'); 
 29      time = document.getElementById('time');
 30      timeval = document.getElementById('timeval');
 31      timerank = document.getElementById('timerank'); 
 32      if(reset){//reset if done setting second slider, and attempting to move more 
 33       this.first = false;
 34       this.second = false;
 35       this.rangeIDstr = 'ratesizetime';
 36       raterank.innerHTML = '';
 37       rateval.innerHTML = '';
 38       sizerank.innerHTML = '';
 39       sizeval.innerHTML = '';
 40       timerank.innerHTML = '';
 41       timeval.innerHTML = '';
 42       size.value = "50%";
 43       time.value = "50%";
 44       rate.value = "50%";
 45       return;
 46      }//else, as you were
 47      
 48      id = slider.getAttribute('id'); 
 49      
 50      
 51      switch(id){//self updates for sliders
 52       case 'rate':
 53        document.getElementById(id + 'val').innerHTML = this.formatSize(slider.value);
 54        break;
 55       case 'size':
 56        document.getElementById(id + 'val').innerHTML = this.formatSize(slider.value);
 57        break;
 58       case 'time':
 59        document.getElementById(id + 'val').innerHTML = this.formatTime(slider.value);
 60        break;
 61       default:
 62        alert(id + ': wtffff');
 63        break
 64      }
 65      
 66      
 67      
 68      if(!this.first && !this.second){//first slider, only update own value
 69       this.first = id;
 70       //document.getElementById(id + 'rank').innerHTML = 1;//debug
 71       this.rangeIDstr = this.removeStr(id, this.rangeIDstr);
 72      } 
 73      if(!this.second && this.first && this.first != id){ //second slider, third is known, begin updating both self and third   
 74       this.second = id;
 75       //document.getElementById(id + 'rank').innerHTML = 2;//debug
 76       this.rangeIDstr = this.removeStr(id, this.rangeIDstr);
 77      }
 78      if (this.first && this.second){    
 79       //document.getElementById(this.rangeIDstr + 'rank').innerHTML = 3;//debug
 80       switch (this.rangeIDstr){//choose leftover one, alter accordingly.
 81        case 'rate':
 82         rate.value = size.value / time.value //bytes yo.
 83         rateval.innerHTML = this.formatSize(rate.value);
 84         break;
 85        case 'size':
 86         size.value = (rate.value * time.value); 
 87         sizeval.innerHTML = this.formatSize(size.value);
 88         break;
 89        case 'time':      
 90         time.value = size.value / rate.value;  
 91         timeval.innerHTML = this.formatTime(time.value);
 92         break;
 93        default:
 94         alert(this.rangeIDstr);
 95         break;
 96       } 
 97      } 
 98     }
 99     
 100     this.addLeadingZero = function(digit){//mhm more bs
 101      if(digit < 10){
 102       digit = "0"+digit
 103      }
 104      return Math.round(digit, 2);
 105     }
 106     
 107     this.formatSize = function(INTbytes){// no more conversions please this is ridic
 108      f_GB = Math.floor(INTbytes / Math.pow(1024,3));
 109      INTbytes -= (f_GB * Math.pow(1024,3));
 110      f_MB = Math.floor(INTbytes / Math.pow(1024,2));
 111      INTbytes -= (f_MB * Math.pow(1024,2));
 112      f_KB = Math.floor(INTbytes / (1024));
 113      INTbytes -= (f_KB * (1024));
 114      f_B = Math.floor(INTbytes / 1);
 115      f_size = this.addLeadingZero(f_GB) + ' GB : ' + this.addLeadingZero(f_MB) + ' MB : ' + this.addLeadingZero(f_KB) + ' KB : ' + this.addLeadingZero(f_B) + ' B';
 116      
 117      
 118      return f_size;
 119      
 120      
 121     }
 122     
 123     this.formatTime = function(INTseconds){//convert seconds into days/hrs/min/sec without that pesky time library? ugh.
 124      f_days = Math.floor(INTseconds / (60*60*24));
 125      INTseconds -= (f_days * (60*60*24));
 126      f_hours = Math.floor(INTseconds / (60*60));
 127      INTseconds -= (f_hours * (60*60));
 128      f_minutes = Math.floor(INTseconds / (60));
 129      INTseconds -= (f_minutes * (60));
 130      f_seconds = Math.floor(INTseconds / 1);
 131      f_time = this.addLeadingZero(f_days) + ' Days : ' + this.addLeadingZero(f_hours) + ' Hours : ' + this.addLeadingZero(f_minutes) + ' Minutes : ' + this.addLeadingZero(f_seconds) + ' Seconds';
 132      return f_time;
 133     }
 134     
 135     this.removeStr = function(needle, haystack){//om nom nom nom 
 136      gage = needle.length;
 137      firstHalf = haystack.substr(0, haystack.indexOf(needle));
 138      secondHalf = haystack.substr(haystack.indexOf(needle) + gage);
 139      return firstHalf + secondHalf;
 140     }
 141     
 142     this.debugInfo = function(variables){//fucking sexy to work with
 143      debugDiv = document.getElementById('debugDiv');
 144      debugStr = '';
 145      for(var i in variables){
 146       debugStr += i + ': ' + variables[i] + '<br />';
 147      }
 148      debugDiv.innerHTML = debugStr;
 149     }
 150    }
 151    
 152    var DL = new DLDATA();//instantiate
 153   </script>
 154   <style>
 155    input{
 156     width:100%;
 157    }
 158    *{
 159     font-size:24px;
 160    }
 161   </style>
 162  </head>
 163  <body onload="var DL = new DLDATA();" >
 164   <h2>The Amazing Dial-Up Investigator Thing!</h2>
 165   <button onclick="DL.recalc(false,true);">ReseT</button><br />
 166   <span id="raterank"></span>Rate: <span id="rateval"></span><input type="range" min="0" max="1048576" step="1024" value="50%" onchange="DL.recalc(this);" id="rate" /><br />
 167   <span id="sizerank"></span>Size: <span id="sizeval"></span><input type="range" min="0" max="1073741824" step="1048576" value="50%" onchange="DL.recalc(this);" id="size" /><br />
 168   <span id="timerank"></span>Days: <span id="timeval"></span><input type="range" min="0" max="259200" step="900" value="50%" onchange="DL.recalc(this);" id="time" />
 169   <div id="container"></div>
 170   <div id="debugDiv"></div>
 171  </body>
 172 </html>


'Sall I got for now, Gonna make butterscotch toffee for today's meal. Cannot wait to gorge. Peace webs.
Oh here's More!
I decided to do some animations, starting work on a little library for translations, resizes.
Code:
 1 <html>
 2  <head>
 3   <script type="text/javascript" src="smoother.js">
 4    
 5   </script>
 6   <style>
 7    
 8   </style>
 9  </head>
 10  <body>
 11   <button onclick="toolkit.smooth('500px', 'width')">long</button>
 12   <button onclick="toolkit.smooth('100px', 'width')">short</button>
 13   <button onclick="toolkit.smooth('10px', 'height')">fat</button>
 14   <button onclick="toolkit.smooth('1px', 'height')">thin</button>
 15   <button onclick="toolkit.cfg.smooth.bln_stop = true;">Smoother.cfg.smooth.stop()</button><br />
 16   speed<input id="speed" type="range" onchange="updateSelf(this)" min="0" max="10" step="1" value="1" /><span id="speeddiv"></span>
 17   <div id="test" style="width:20px;height:5px;background-color:#1c1c1c;" > </div>
 18   <script type="text/javascript">  
 19    hr = document.getElementById('test');
 20    var toolkit = new Smoother('toolkit', hr);
 21   </script>
 22  </body>
 23 </html>


and more

Code:
 1 
 2 //smooth transition from x to y, various transitions.
 3    var Smoother = function(varname, targetObject){
 4      /*construct*/  
 5      this.cfg = {};
 6      this.cfg.smooth = {
 7       "str_echo":null,
 8       "int_target":0,
 9       "int_fps":30,
 10       "int_modifier":0,
 11       "int_speed":1,//percentage, 1 = 100% = 1px/frame
 12       "ref_interval":null,
 13       "bln_stop":false,
 14       "str_mode":'',
 15       "bln_busy":false
 16      };
 17      /*end construct*/
 18      
 19      this.smooth = function(target, mode){
 20      
 21       this.cfg.smooth.bln_stop = false;
 22       
 23       this.cfg.smooth.str_mode = mode;
 24       this.cfg.smooth.str_echo = (mode == 'width') ? targetObject.style.width: targetObject.style.height;      
 25       this.cfg.smooth.int_target = target;
 26       
 27       if(parseInt(this.cfg.smooth.str_echo) < parseInt(this.cfg.smooth.int_target) && this.cfg.smooth.int_modifier == 0){
 28        this.cfg.smooth.int_modifier = 1;
 29       }else if(parseInt(this.cfg.smooth.str_echo) > parseInt(this.cfg.smooth.int_target) && this.cfg.smooth.int_modifier == 0){
 30        this.cfg.smooth.int_modifier = -1;
 31       }
 32       
 33       console.log(this.cfg.smooth.int_modifier);
 34       fpsConvert = 1000/this.cfg.smooth.int_fps;
 35       
 36       if(!this.cfg.smooth.bln_busy){
 37        this.cfg.smooth.bln_busy = true;
 38        this.cfg.smooth.ref_interval = setInterval(varname+".smoothLoop()", fpsConvert);
 39       }
 40      }
 41      
 42      this.smoothLoop = function(){
 43       /*stop rules*/
 44       if(this.cfg.smooth.int_modifier == 1){
 45        if(parseInt(this.cfg.smooth.str_echo) >= parseInt(this.cfg.smooth.int_target)){
 46         this.cfg.smooth.bln_stop = true;
 47        }       
 48       }else if(this.cfg.smooth.int_modifier == -1){
 49        if(parseInt(this.cfg.smooth.str_echo) <= parseInt(this.cfg.smooth.int_target)){//passed target? you done fucked up.
 50         this.cfg.smooth.bln_stop = true;
 51        }
 52       }
 53       /*end stop rules*/ 
 54       
 55       if(this.cfg.smooth.bln_stop){//stop it if its flagged to be stopped, do shutdown
 56        clearInterval(this.cfg.smooth.ref_interval); 
 57        this.cfg.smooth.bln_busy = false;
 58        this.cfg.smooth.int_modifier = 0;
 59        return;
 60       } 
 61       
 62       this.cfg.smooth.int_speed = document.getElementById('speed').value,
 63       patt = /[a-zA-Z][^0-9]+/g;
 64       suffix = patt.exec(this.cfg.smooth.str_echo);
 65       this.cfg.smooth.str_echo = parseInt(this.cfg.smooth.str_echo) + this.cfg.smooth.int_modifier * this.cfg.smooth.int_speed;//change the output: x = x + (+/- modifier * px/frame)
 66       this.cfg.smooth.str_echo = this.cfg.smooth.str_echo + suffix;
 67       if(this.cfg.smooth.str_mode == 'width') { 
 68        targetObject.style.width = this.cfg.smooth.str_echo; 
 69       }else if(this.cfg.smooth.str_mode == 'height'){ 
 70        targetObject.style.height = this.cfg.smooth.str_echo;
 71       }
 72      }     
 73    }
 74    function updateSelf(obj){
 75     div = obj.getAttribute('id').concat('div');
 76     document.getElementById(div).innerHTML = document.getElementById(obj.getAttribute('id')).value;
 77    }
 78 



2011-08-29
August Twenty-Nine Two Thousand Eleven
My Templates File (again)

Alright, since it was pointed out to me how I kinda half assed my template system, I finished it:
Code: movies.css
 1 div.sh_movie, div.sh_movie_detail{
 2  width:700px;
 3  margin:auto;
 4 }
 5 
 6 div.sh_movie{
 7  
 8 }
 9 
 10 div.sh_movie b, div.sh_movie_detail b, div.sh_search_bar b{
 11  color:#ffffff;
 12 }
 13 
 14 div.sh_movie_detail hr{
 15  width:150px;
 16  margin-left:5px
 17 }
 18 
 19 div.sh_movie_detail{
 20 
 21 }
 22 
 23 span.sh_rating_detail{
 24  margin-left:50px;
 25  color:#ffffff;
 26 }
 27 
 28 div.sh_search_bar{
 29  margin-left:50px;
 30 }
 31 
 32 div.sh_search_result{
 33  color:#ffffff;
 34  width:700px;margin:auto;
 35 }


Code: sh_movie.html
 1 <div class="sh_movie">
 2  <b onclick="initMovies('?showdetail=1&m_id={id}')">{title}</b>
 3  <div id="Holder{id}" class="rateholder" onmouseout="reset('bar{id}','{rating}')" onmousedown="ajaxFunction('Holder{id}','bar{id}',{id})" onmousemove="Calculate('Holder{id}','bar{id}',event)">
 4   <div id="bar{id}" class="ratebar" style="width:{bar_width}px">Rate&nbsp;Me</div>
 5  </div>
 6 </div>
 7 <br />
 8 

Code: sh_movie_detail.html
 1 <div class="sh_movie_detail" >
 2  <b onclick="initMovies('?listmovies=1')">{title}</b>
 3  <div id="Holder{id}" class="rateholder" onmouseout="reset('bar{id}','{rating}')" onmousedown="ajaxFunction('Holder{id}','bar{id}',{id})" onmousemove="Calculate('Holder{id}','bar{id}',event)">
 4   <div id="bar{id}" class="ratebar" style="width:{bar_width}px">Rate&nbsp;Me</div>
 5  </div>
 6  <hr />
 7  {rating_detail}
 8  <a target="_blank" href="http://www.lmgtfy.com/?q={title}+streaming">Watch Now</a>
 9 </div>
 10 

Code: sh_rating_detail.html
 1 <span class="sh_rating_detail" >
 2  {u_name} >> {u_rating}
 3 </span>
 4 <br />

Code: sh_search_bar.html
 1 <div class="sh_search_bar">
 2  <b>Add Flick : </b>
 3  <input type="text" id="imdb_search" />
 4  <input type="button" value="Search" id="imdb_searchbutton" onclick="initMovies('?imdbsearch=1&title=' + document.getElementById('imdb_search').value)" />
 5 </div>
 6 

Code: sh_search_result.html
 1 <div class="sh_search_result" id="{title}" onclick="initMovies('?addmovie=1&title={title}')">
 2  <b>{title}</b>
 3 </div>
 4 


There you go.

-Buddah



2011-08-24
August Twenty-Four Two Thousand Eleven
My Templates File
I recently made a templates file to use with my movies app, I'm sharing it so you CSS devs can play with it. Thar you go.
Code:
 1 <?php
 2 Class templates{
 3  function __construct(){
 4  
 5  }
 6  
 7  function sh_movie($id, $title, $rating){
 8   $html = "";
 9   $html .= "<div style='width:700px;margin:auto;'>";
 10   $html .= "<b style='color:#ffffff' onclick=\"initMovies('?showdetail=1&m_id=$id')\">$title</b>";
 11   $html .= "<div id='Holder$id' class='rateholder' onmouseout='reset(\"bar$id\",\"$rating\")' onmousedown='ajaxFunction(\"Holder$id\",\"bar$id\",$id)' onmousemove='Calculate(\"Holder$id\",\"bar$id\",event)'>";
 12   $html .= "<div id='bar$id' class='ratebar' style='width:" . $rating * 10 . "%;'>Rate&nbsp;Me";
 13   $html .= "</div></div></div><br />";
 14   return $html;
 15  }
 16  
 17  function sh_movie_detail($id, $title, $rating, $rating_detail){
 18   $html = "";
 19   $html .= "<div style='width:700px;margin:auto;'>";
 20   $html .= "<b style='color:#ffffff;float:none;' onclick=\"initMovies('?showdetail=1&m_id=$id')\">$title</b>";      
 21   $html .= "<div id='Holder$id' class='rateholder' style='display:inline-block;float:left;' onmouseout='reset(\"bar$id\",\"$rating\")' onmousedown='ajaxFunction(\"Holder$id\",\"bar$id\",$id)' onmousemove='Calculate(\"Holder$id\",\"bar$id\",event)'>";
 22   $html .= "<div id='bar$id' class='ratebar' style='width:" . $rating * 10 . "%;'>Rate&nbsp;Me";
 23   $html .= "</div></div>";
 24   $html .= '<hr style="width:150px;margin-left:5px" />'; 
 25   foreach ($rating_detail as $key=>$ratingD){
 26    $this_rating = split(':', $ratingD);
 27    $html .= '<span style="margin-left:50px;color:#ffffff;">';
 28    $html .= $this_rating[0] . " >> " . $this_rating[1];
 29    $html .= "</span><br />";
 30    
 31   }
 32   $html .= '<a target="_blank" href="http://www.lmgtfy.com/?q=' . $title . '+streaming">Watch Now</a>';
 33   //$html .= '';
 34   $html .= "</div>";
 35   return $html;
 36  }
 37  
 38  function search_result($title){
 39   $title = preg_replace('/ss+/', ' ', $title);
 40   $html = '';
 41   $html .= '<div style="color:#ffffff;width:700px;margin:auto;" id="' . $title . '" onclick="initMovies('?addmovie=1&title=' . $title . '')">';
 42   $html .= '<b>' . $title . '</b>';
 43   $html .= '</div>';
 44   $html .= '';
 45   
 46   return $html;
 47  }
 48  
 49  function search_bar(){
 50   $html = '<div style="margin-left:50px;">';
 51   $html .= '<b style="color:#ffffff;">Add Flick : </b>';
 52   $html .= '<input type="text" id="imdb_search" />';
 53   $html .= '<input type="button" value="Search" id="imdb_searchbutton" onclick="initMovies('?imdbsearch=1&title=' + document.getElementById('imdb_search').value)" />';
 54   $html .= '</div>';
 55   return $html;
 56  }
 57 }
 58 ?>



2011-07-28
July Twenty-Eight Two Thousand Eleven
Tinychat API Step by Step How-To
I had a hell of a time figuring out how to utilize the tinychat API. I finally got it though so now I'm going to put the steps in order so that you won't have the same trouble.

- Go to Tinychat's devsite, create an account, create an application, and take a look at it to get your API key and Secret API key
- Now at the top, click on Documentation, then on any of the embed variables links at the left. If you notice, each time you click on an embed variables documentation link, the value for 'room' changes in the tinychat var. You need to use this room number on any embeds you intend to interface with. You must also replace the 'key' value 'api_key' with your applications API key.
Code:
 1 
 2 <script type='text/javascript'> 
 3 var tinychat = { room: "4e31c819ea799", //Your room number for embeds
 4 key: "replace_with_your_api_key", 
 5 join: "auto"};
 6 </script> 
 7 <script src="http://tinychat.com/js/embed.js"></script> 
 8 <div id="client"></div>
 9 

- Now when you intend to gather info on this room from php you will need:
Code:
 1 
 2 <?php
 3 $api_key = "your_api_key_here";
 4 $api_secret = "your_api_secret_here";
 5 
 6 $room = "4e31c819ea799";
 7 
 8 $auth = md5($api_secret . ":" . $room . ":" . "roominfo");
 9 
 10 $room = file_get_contents("http://tinychat.apigee.com/roominfo&result=json&room={$room}&key={$api_key}&withip=1&auth={$auth}");
 11 
 12 $room = json_decode($room);
 13 print_r($room);
 14 ?>
 15 

- Assuming you put your keys and room numbers in the right places, you should be able to see whos in your room. From here on it's all you.

Code: Room Info Template
 1 <?php
 2 Class TCRoomInfo{
 3  function __construct(){ 
 4   $api_key = "your_api_key";
 5   $api_secret = "your_secret_key";
 6 
 7   $room = "your_room_number";
 8 
 9   $auth = md5($api_secret . ":" . $room . ":" . "roominfo");
 10 
 11   $room = file_get_contents("http://tinychat.apigee.com/roominfo&result=json&room=" . $room . "&key=" . $api_key . "&withip=1&auth=" . $auth);
 12 
 13   $this->room = json_decode($room);
 14  }
 15  
 16  function dump(){  
 17   print_r($this->room);
 18  }
 19  
 20  function summary(){
 21   $summary = '';
 22   $summary .= '<p>';
 23   $summary .= 'Topic: ' . $this->room->topic;
 24   $summary .= '<br />';
 25   $summary .= 'Name: ' . $this->room->name;
 26   $summary .= '<br />';
 27   $summary .= 'Users: ' . $this->room->usercount;
 28   $summary .= '<br />';
 29   $summary .= 'Broadcasting: ' . $this->room->broadcastercount;
 30   $summary .= '</p>';
 31   echo $summary;
 32  }
 33  
 34  function userlist(){
 35   $userlist = '';
 36   $userlist .= '<table><tr style="height:120px;">';
 37   foreach($this->room->users as $key=>$user){
 38    if($key%4 == 0){
 39     $userlist .= '</tr>';
 40     $userlist .= '<tr style="height:120px;">';
 41    }
 42    $userlist .= '<td style="width:160px;background-image:url('' . $user->pic . '');">';
 43    $userlist .= '<div class="userinfo">';
 44    $userlist .= 'Name: ' . $user->name;
 45    $userlist .= '<br />';
 46    $userlist .= 'Cam: ' . ($user->broadcasting ? 'on' : 'off');
 47    $userlist .= '<br />';
 48    $userlist .= 'Mod: ' . ($user->oper ? 'yes' : 'no');
 49    $userlist .= '<br />';
 50    $userlist .= 'IP: ' . $user->ip;
 51    $userlist .= '</div>';
 52    $userlist .= '</td>';
 53   }
 54   $userlist .= '</tr></table>';
 55   echo $userlist;
 56  }
 57 }
 58 
 59 $TCR = new TCRoomInfo();
 60 $TCR->summary();
 61 $TCR->userlist();
 62    ?>



2011-07-24
July Twenty-Four Two Thousand Eleven
Sundays
I've tried a lot of different 'start here' attitudes; I've tried starting many different times. Not often do I find myself past the 'start here' attitude though, usually something rooted in emotion stirs up and puts me back in the 'stay here' attitude; where I want everything to stay the same while my mind has a chance to catch up.

When I review my starts I find that I always have a condition in mind, not necessarily a goal, but a condition that I'd like to sustain or improve upon; but it's always just one. I try to convince myself that I'm doin alright, I've got X or I've got Y goin' for me. As for the stalls, it seems they come as I transition from one condition to the next. One goal seems to slip from my grasp as another comes into focus.

I think more than anything I need to emplor my patience. I need to be more patient: with myself as I patch together some kind of a life around me; with others as those patches will inevitably move between us. Let the foundation solidify before building atop.

I can become more patient if I start thinking in longer terms than I have been. As much as I'd like to live day to day, I can't be completely day to day either.

I don't like the word goal, but I have an idea of who I want to be.



2011-06-14
June Six Two Thousand Eleven
Chess
Well, I've been working on a little project that I thought would be fun, Chess. I wanted to see how difficult it would be to code a multiplayer chess applet from scratch. Turns out, not so hard, just tedious; lots and lots of nested logic. As of right now, there is a lobby that displays currently active games to join with the ability to create a game. The game iteself works, complete with move validation, but theres still a bit left to do. I still need to add some code to highlight possible moves, detect 'check' and 'checkmate', promote pawns, and some obscure move called 'en passant'.



2011-05-25
May Twenty Five Two-Thousand Eleven
Mysql PHP Class
I built this little class for interfacing with mysql DB's in a simpler way. Thought I'd share it.
Code:
 1 <?php
 2 /**
 3 * mysql.php
 4 *
 5 * <p>This file initiates a database connection and facilitates manipulating
 6 * a mysql database with simple OOPPHP function calls.</p>
 7 *
 8 * PHP Version 5.3.5
 9 *
 10 * @category Obj
 11 * @package  Mysql
 12 * @author   Tyler Thomas <tylerethomas@gmail.com>
 13 * @license  http://opensource.org/licenses/gpl-3.0.html GNU Public License (GPLv3)
 14 * @link     http://www.hordeofnightmares.net
 15 */
 16 
 17 /**
 18 * Mysql Class
 19 *
 20 * <p>This object initiates a database connection and facilitates manipulating
 21 * a mysql database with simple OOPPHP function calls.</p>
 22 * <p>YOU MUST SELECT A DATABASE WITH fncSelectDB() BEFORE RUNNING QUERIES</p>
 23 *
 24 * @category Obj
 25 * @package  Mysql
 26 * @author   Tyler Thomas <tylerethomas@gmail.com>
 27 * @license  http://opensource.org/licenses/gpl-3.0.html GNU Public License (GPLv3)
 28 * @link     http://www.hordeofnightmares.net
 29 */
 30 class Mysql
 31 {
 32     /**
 33     *@var string server path (usually localhost)
 34     */
 35     private $_strServer;
 36     /**
 37     *@var string DB UserName
 38     */
 39     private $_strUserName;
 40     /**
 41     *@var string DB Password
 42     */
 43     private $_strPassword;
 44     /**
 45     * __construct()
 46     * 
 47     * <p>when this class is instantiated, the constructor will
 48     * initialize the mysql login variables
 49     * passed to it at instantiation.</p>
 50     *
 51     * @param string $strServer   String for mysql server URI
 52     * @param string $strUserName String for mysql server login Username
 53     * @param string $strPassword String for mysql server login Password
 54     *
 55     * @access public
 56     */
 57     public function __construct($strServer, $strUserName, $strPassword)
 58     {
 59         //error_reporting(E_ALL /*^ E_NOTICE*/);
 60         //object member assignments
 61         $this->strServer = $strServer;
 62         $this->strUserName = $strUserName;
 63         $this->strPassWord = $strPassword;
 64     }
 65     /**
 66     * fncReadQuery()
 67     * 
 68     * <p>This function is used when obtaining
 69     * results from a SELECT SQL statement.</p>
 70     *
 71     * @param string $strSQL String for mysql statement to be sent to the server
 72     *
 73     * @return Array $out returns array of records returned from SQL statment
 74     *
 75     * @access public
 76     */
 77     public function fncReadQuery($strSQL)
 78     {
 79         $objLink = mysql_connect(
 80             $this->strServer,
 81             $this->strUserName,
 82             $this->strPassWord
 83         );
 84 
 85         mysql_select_db($this->strDataBase);
 86         $result = mysql_query($strSQL, $objLink);
 87         $out = array();
 88         for ($i = 0; $out[$i] = mysql_fetch_assoc($result); $i++) {
 89             // runs till it fails after all records read
 90         }
 91         array_pop($out);// remove final EMPTY array node created on failure
 92         //mysql_free_result($result);//only needed for super large queries
 93         mysql_close($objLink);
 94         return $out;
 95     }
 96     /**
 97     * fncWriteQuery()
 98     * 
 99     * <p>this function is used when editing
 100     * a table via UPDATE or INSERT SQL statements.</p>
 101     *
 102     * @param string $strSQL String for mysql statement to be sent to the server
 103     *
 104     * @return Boolean returns true on success, dies on failure
 105     *
 106     * @access public
 107     */
 108     public function fncWriteQuery($strSQL)
 109     {
 110         $objLink = mysql_connect(
 111             $this->strServer,
 112             $this->strUserName,
 113             $this->strPassWord
 114         );
 115         mysql_select_db($this->strDataBase);
 116         mysql_query($strSQL, $objLink) or die(
 117             'fncWriteQuery failed:' . $strSQL . ' | ' . mysql_error()
 118             );
 119         mysql_close($objLink);
 120         return true;
 121     }
 122     /**
 123     * fncCSDB()
 124     * 
 125     * <p>This function is used to easily select databases,
 126     * it will also create databases if they do not exist
 127     * i.e. fncCreateSelectDataBase</p>
 128     *
 129     * @param string $strDB String the database to choose
 130     *
 131     * @return Boolean returns true on success, dies on failure
 132     *
 133     * @access public
 134     */
 135     public function fncCSDB($strDB)
 136     {
 137         $objLink = mysql_connect(
 138             $this->strServer,
 139             $this->strUserName,
 140             $this->strPassWord
 141         );  //connect
 142         $result = mysql_query(
 143             'CREATE DATABASE IF NOT EXISTS ' . $strDB . ';',
 144             $objLink
 145         );// create db if it doesnt exist
 146         $db_selected = mysql_select_db($strDB, $objLink); // test
 147         if (!$db_selected) {
 148             die ('Cannot use ' . $strDB . ': ' . mysql_error()); //die on failure
 149         } else {
 150             $this->strDataBase = $strDB;//on success, set object property
 151         }
 152         mysql_close($objLink);//disconnect
 153         return true;//hasn't died, so return true
 154     }
 155 }?>



2011-04-17
April Seventeen Two-Thousand Eleven
Standardized Coding

I've read a lot about 'good practice' vs 'bad practice' in programming, but I had no idea how I could focus on trivial things like bracket placement when I have a fun idea that I want to see happen sooner than later. However I know someday someone might want to actually READ my code, so I should make an effort to take the effort out of reading it.

I read about PEAR's standards and was immediately infatuated with it, but it was still so tedious to put all those little standards into practice when no one is looking over my shoulder. Alas I've found the solution(s).

I Installed PEAR onto WAMP and proceeded to install a couple little tools I don't think I'll ever go without again: CodeSniffer and phpDocumentor.

I'll let you google for those while you oogle over this:
Code:
 1 
 2 <?php
 3 /**
 4 * preloadDir.php
 5 
 6 * <p>This file will scan a given directory for files (originally for images) 
 7 * to preload i.e. append them to the page in a hidden div.</p>
 8 *   
 9 * PHP Version 5.3.5
 10 *
 11 * @category Scripts
 12 * @package  PreloadDir
 13 * @author   Tyler Thomas <tylerethomas@gmail.com>
 14 * @license  http://opensource.org/licenses/gpl-3.0.html GNU Public License (GPLv3)
 15 * @link     http://www.tylerthomas.me
 16 
 17 */
 18 
 19 /**
 20 * PreloadDir Class
 21 
 22 * <p>I can't imagine a reason to have multiple instances of this
 23 * but why the hell not</p>
 24 *
 25 * @category Scripts
 26 * @package  PreloadDir
 27 * @author   Tyler Thomas <tylerethomas@gmail.com>
 28 * @license  http://opensource.org/licenses/gpl-3.0.html GNU Public License (GPLv3)
 29 * @link     http://www.tylerthomas.me
 30 */
 31 class PreloadDir
 32 {
 33     /**
 34     * Public $files array
 35     *
 36     * @var array will contain filenames (as strings)
 37     **/
 38     public $files = array();
 39     /**
 40     * __construct()
 41     * <p>when this class is instantiated, the constructor will
 42     * initialize the array of files
 43     * in the given directory ($dir)</p>
 44     *
 45     * @param string $dir String pointing to directory to preload e.g. "../images"
 46     *
 47     * @access private
 48     */
 49     private function __construct($dir)
 50     {
 51         $items = scandir(realpath($dir));
 52         $path = "http://www.tylerthomas.me/" . $dir . "/";
 53         $x=0;
 54         foreach ($items as $fname) {
 55             $extension = pathinfo($fname);
 56             $extension = $extension['extension'];
 57             if (substr($fname, 0, 1) != "." && $extension != 'db' && strlen($extension) >=3) {
 58                 //$fname = realpath($path.$fname);
 59                 $this->files[$x] = $path . $fname;
 60                 $x++;
 61             }
 62         }
 63     }
 64     
 65     /**
 66     * getHTML()
 67     * <p>This function iterates through the collected files in 
 68     * the {@link $files} array and parses them into valid 
 69     * HTML and returns the string of code.</p>     
 70     *
 71     * @access public
 72     * @return object
 73     */
 74     public function getHTML()
 75     {
 76         $doc = new DOMDocument('1.0');
 77         
 78         $div = $this->_createElement($doc, "div", null, array('style'=>'display:none;'));
 79         $div = $doc->appendChild($div);
 80         
 81         foreach ($this->files as $key=>$file) {
 82             $image = $this->_createElement($doc, "img", null, array('src'=>$file));
 83             $image = $div->appendChild($image);
 84         }
 85         
 86         return $doc->saveHTML();
 87     }
 88     
 89     /**
 90     * _createElement()
 91     *
 92     * <p>This is just a quick function for creating elements complete with 
 93     * innerHTML and attibute information.</p>
 94     * 
 95     * @param object $domObj     the PHP dom object
 96     * @param string $tag_name   the name of the new tag
 97     * @param string $value      the innerHTML of the tag (optional)
 98     * @param array  $attributes attributes to apply to the new element (optional)
 99     *
 100     * @access private
 101     * @return object
 102     */
 103     private function _createElement($domObj, $tag_name, $value = null, $attributes = null)
 104     {
 105         $element = ($value != null ) ? $domObj->createElement($tag_name, $value) : $domObj->createElement($tag_name);
 106 
 107         if ($attributes != null) {
 108             foreach ($attributes as $attr=>$val) {
 109                 $element->setAttribute($attr, $val);
 110             }
 111         }
 112 
 113         return $element;
 114     }
 115 }
 116 /*
 117     <?php 
 118     //Image Preload
 119     include_once('./classes/preloadDir.php');    
 120     $test = new PreloadDir('images');
 121     echo $test->getHTML();    
 122     ?>*/
 123 ?>

Also see: The phpDocumentor output
Oh and this too
Oh and this too

Turns out this script didn't speed up load times at all whatsoever, I don't know what made me think it would. It would probably work for a gallery app tho. It's free code, go for it.



2011-04-13
April Thirteen Two-Thousand Eleven
Alert the Crowd
Someone recently gave me an idea for a video chat site that I host, they wanted the ability to wake someone up if they were sleeping on cam.

I thought this was a novel idea, and I thought I might be able to do it, so I gave it a shot.

This is what I came up with: an inconspicuous button that when pressed by any one user on the site, will play an alarm sound for everyone connected to the site.

The PHP
Code:
 1 class alert{
 2 
 3     public function alert(){
 4         error_reporting(E_ALL /*^ E_NOTICE*/);
 5                     
 6         $this->link = mysql_connect("localhost","uname","pword");
 7         mysql_select_db('hordeofn_newsite');
 8         
 9             $this->set =   (isset($_POST['set']) ? ($this->setAlarm($_POST['set']) ? 1 : 0) : 0);
 10             $this->reset =  (isset($_POST['reset']) ? ($this->setAlarm() ? 1 : 0) : 0);
 11             $this->check = (isset($_POST['check']) ? ($this->checkAlarm() ? 1 : 0) : 0);
 12         mysql_close($this->link);
 13     }
 14     
 15     public function checkAlarm(){
 16         $sql = 'SELECT * FROM main';
 17         $result = mysql_query($sql, $this->link);
 18         while($row = mysql_fetch_array($result)){
 19             if($row['soundoff'] == 1){
 20                 return true;
 21             }
 22             else{
 23                 return false;
 24             };
 25         }
 26     }
 27 
 28     public function setAlarm($set = 0){
 29         $sql = 'UPDATE main SET soundoff='.($set?1:0).' WHERE 1';
 30         mysql_query($sql, $this->link) or die('query failed [update]' . mysql_error());
 31         return true;
 32     }
 33 
 34 }
 35 
 36 $alert = new alert();
 37 $out = "";
 38 $out .= (isset($_POST['check']) ? $alert->check : "");
 39 $out .= (isset($_POST['set']) ? $alert->set : "");
 40 $out .= (isset($_POST['reset']) ?  $alert->reset : "");
 41 echo $out;

The Javascript
Code:
 1 soundManager.url = './swf/';
 2 var mySound = '';
 3 var intervalID = '';
 4 var intervalID2 = '';
 5 soundManager.onload = function() {
 6     mySound = soundManager.createSound({
 7         id: 'mySound',
 8         url: './src/alert.mp3',
 9         volume: 50,
 10         loops: 1,
 11         multiShot: false,
 12         autoPlay: false
 13     });   
 14     intervalID = window.setInterval('fiddle(1,0,0)', 1000); //check every second
 15     
 16     intervalID2 = window.setInterval('soundManager.setVolume("mySound",0);',5000);//mute every 5 seconds,
 17 }
 18 
 19 function fiddle(check, set, reset){
 20     var xmlHttp=null;
 21       try
 22         {
 23         // Firefox, Opera 8.0+, Safari
 24         xmlHttp=new XMLHttpRequest();
 25         }
 26       catch (e)
 27         {
 28         // Internet Explorer
 29         try
 30           {
 31           xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
 32           }
 33         catch (e)
 34           {
 35           xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
 36           }
 37         }
 38     if (xmlHttp==null)
 39       {
 40       alert ("Your browser does not support AJAX!");
 41       return;
 42       } 
 43     varString = '';
 44     varString += (check ? 'check=1' : '');
 45     varString += (set ? '&set=1' : '');
 46     varString += (reset ? '&reset=1' : '');
 47     url = "script/alert.php";
 48     xmlHttp.onreadystatechange = function() {
 49     if (xmlHttp.readyState == 4 && xmlHttp.status==200)
 50         {
 51             parse(xmlHttp.responseText,check,set,reset); //Do something iwth response if you like.
 52         }
 53     }
 54     xmlHttp.open("POST",url,true);
 55     xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
 56     xmlHttp.send(varString);
 57  }
 58  
 59  
 60  function parse(inn,check,set,reset){
 61     if(check == 1 && set == 0 && reset == 0 && inn == 1){//if db = 1
 62         //document.getElementById('response').innerHTML = inn;//debug
 63         soundManager.setVolume("mySound",50);
 64         mySound.play();
 65         //fiddle(0,0,1);
 66     }else{    
 67         //document.getElementById('response').innerHTML = 'err';//debug
 68     }
 69  }   
 70  
 71  function swapButton(obj,color){   
 72     obj.style.backgroundImage = (color==1?"url('./img/buttonred.png')":obj.backgroundImage = "url('./img/buttongreen.png')");
 73 }
 74  //clearInterval(intervalID);

The HTML
Code:
 1 <script src="./script/soundmanager2.js"></script>
 2 <script src="./script/alert.js"></script>
 3 <div id="button" class="green" onmousedown="swapButton(this,1);fiddle(0,1,0);" onmouseup="swapButton(this,0)" onmouseout="swapButton(this,0);fiddle(0,0,1);">&nbsp;</div>
 4  <div id="response"><!-- debug output --></div>


It was fun while it lasted, but, it was somewhat annoying as you can imagine.

It basically works by a javascript loop. well two really. One checks the DB every second and sounds the alarm if it's set, the other loop mutes every four seconds. If the flag is set, the alarm will sound for a minimum of four seconds and then continue checking the flag.



2011-03-22
March Twenty-Two Two Thousand Eleven
An Impass
The more I delve into this code for comments on this blog of mine, the more I feel like I should give up on this 'omg learn php filesystem' thing and just make it use a DB instead. The blog works fine, and I could definitely make comments (add, edit, delete, reply) work with regexp+bbcode but...do I want to? A DB would really make things work a lot more smoothly, would probably even make my search algorithm faster, not to mention filesystem vulnerabilities when using AJAX etc with FS apps.