Code Slinger

Computer hardware is great and I have lots of it as the owner of a computer company. However when you want that cold plastic composite and metal thingy to do something...you need code.

Code Projects
  • Code Projects in C++,C#,PHP,Java

    Code Projects in C++,C#,PHP,Java

  • Future Tech

    Future Tech

X-NLP

X-NLP

Extreme Natural Language Processing.
Read More
Data Bots

Data Bots

Internet Bots for Crawling, Scraping and Data Mining
Read More
Vid Automatic

Vid Automatic

Creating rich real time video products and streaming services.
Read More
VR Hacker

VR Hacker

The Hacking of Virtual Reality with the Oculus Rift.
Read More

Mail2Blogger with Images (PHP)

blogger_smash

Blogger allows you to send posts via email, intended for on the go posting via mobile devices and such. To activate this feature you have to update your blog settings with a secret key.

1. Log into Blogger
2. Select “Settings for your Blog”
3. Select “Mobile and email”
4. Where it says “Posting using email” there is a box, in front of the box is your username, following the box is @blogger.com. In the box put your secret key.
5. On the radio selection below that make sure “Publish email immediately” is selected.
6. Click Save Settings

Now all you have to do to send a post to your blog is send it to that email address that contains your secret key. The title of your email will be the title. Keep in mind that if your email automatically adds a signature to your email that it will probably also appear on your post.

You can include an image that appears at the top of the article by attaching an image in your email. Blogger saves this to its server and hosts it (10MB limit for images)
Using PHP we can now easily post new blog articles at any time or even automatically using the PHPMAILER class from Synchro at Github. It is best that you use a gmail account email that is associated with your blog to reduce any imperial entanglements. Also by using gmail account and this method you are not required to have a running mail server or do any other funky relaying (great for those doing projects in XAMPP.)

include('class.phpmailer.php');

$gmail_your_name = "YOUR NAME";
$gmail_username = "YOUR GMAIL USERNAME";
$gmail_password = "YOUR GMAIL PASSWORD";
$gmail_email = "YOUR GMAIL EMAIL ADDRESS";
$blogger_secret_key = "YOUR BLOGGER SECRET KEY";
$blogger_url = "YOUR BLOGGER URL";
$image_location = 'C:/YOUR LOCATION OF IMAGE/IMAGE.JPG';
$email_title = "EMAIL TITLE";
$email_body = "EMAIL BODY"; // HTML OK

$mail = new PHPMailer();
$mail->IsHTML(true);
$mail->IsSMTP();
$mail->;SMTPAuth = true;
$mail->SMTPSecure = "ssl";
$mail->Host = "smtp.gmail.com";
$mail->Port = 465;
$mail->Username = $gmail_username;
$mail->Password = $gmail_password;
$fromname = $gmail_your_name;

$To = trim($gmail_username.'.'.$blogger_secret_key.'@blogger.com',"\r\n");

$mail->AddAttachment($image_location);
$mail->From = $gmail_email;
$mail->FromName = $fromname;
$mail->Subject = $email_title;
$mail->Body = $email_body;
$mail->AddAddress($To);
$mail->set('X-Priority', '3'); //Priority 1 = High, 3 = Normal, 5 = low
$mail->Send();

If you are keeping a database of your posts for other projects such as twittering and other linking you can extract the new posts link with the following code. Just add it after the end of the above code.

sleep(15); // blogger enough time to receive and update the post (15 seconds)
$bf = file_get_contents($blogger_url);
list($t,$b1) = explode("'post-title entry-title'",$bf,2);
list($t,$b2) = explode('<a href=",$b1,2); list($b3,$t) = explode(">',$b2,2);
$bb = trim(str_replace('"','',$b3));
$bb = trim(str_replace("'",'',$bb));
$blog_post_url = trim(str_replace(' ','',$bb));<a href="http://charleshays.com/wp-content/uploads/2013/07/blogger_smash.png"><img src="http://charleshays.com/wp-content/uploads/2013/07/blogger_smash-300x300.png" alt="blogger_smash" width="300" height="300" class="alignnone size-medium wp-image-102" /></a>
echo 'NEW POST AT='.$blog_post_url;
</a>

What is Spinning and a Spin Function (PHP)

dreamstimesmall_2869597

Spinning Basics 101

Spinning generally refers to randomly generating articles, content and data based on option sets. Typically a template or as I call it a “boil plate” is created identify the set. I will address the use of spinning for generating articles and other sentence content but as you will easily derive the content does not need to be limited to just words and sentences, you can spin html, CSS, PHP code, data and more.
Say we have a sentence such as “I love my car.” How else could we say this?

I love my automobile.

I like my car.

I really like my vehicle.

These sentences roughly all portray the same meaning but each is distinctly different. When it comes to unique article generation this technique can be invaluable. All we have to do get all these variations and other combinations is generate a boiler plate for the sentence like so.

I {really |}{love|like} my {car|automobile|vehicle}.

So as you can see above all versions of the sets of words are contained in the curly brackets each version separated by the pipe character (the straight vertical line.) Pipe us used because it one has been a standard data delimiter and two because it also a shortcut for OR in programming logic. There is no so called standardization for spinning but it is widely used.

In our example we can see that when spun the set {love|like} means there is equally likely chance that either word will be chosen and used in this spot. For {really|} we see there is only one word, but there is still a pipe followed by a bracket, this indicates there is a chance that really or “nothing” will be selected. Also the last set contains car, automobile and vehicle all with an equal chance to be chosen.

But say we wanted the word ”love” to have a greater chance then like to be chosen? If each of the two words has a 50/50 chance we can increase the odds for the word like by going {like|love|love} now “love” has 2 in 3 chances or 66% probability of being chosen. Same thing can be applied if we want to reduce the odds of the word “really” we can go {really|||} now we have 3 blank spaces to the one choice for “really” giving the word only a 25% chance of being used.

Nested Spinning

With recursive functions such as the one at the end of this article, you can create boiler plates with nested spins, that is spins within spins.
For example:

Spinning is a {{great|wonderful|good} tool|hot {topic|subject}} for SEO.
When nesting it can start to become confusing to decipher the text but if you break it down like so it is easier to see.

{
	{great|wonderful|good} tool
	|
	hot {topic|subject}}
}

If the first element of the top spin is chosen followed by the second element of the nested spin we get “Spinning is a wonderful tool for SEO.”
Spinning has no restrictions on the levels of nesting you want to add.

Spinning Function for PHP

This has been a very introductory article on the concepts of spinning, most spinning also incorporates deeper elements such as dynamic variables, synonym spinning, adjective and grammar injection and more.

If you are ready to get spinning using some simple PHP code here you go.

function spin($s)
	{
	preg_match('#\{(.+?)\}#is',$s,$m);
	if(empty($m)) return $s;
	$t = $m[1];
	if(strpos($t,'{')!==false)
		{
		$t = substr($t, strrpos($t,'{') + 1);
		}
	$parts = explode("|", $t);
	shuffle($parts);
	$s = preg_replace("+\{".preg_quote($t)."\}+is", $parts[array_rand($parts)], $s, 1);
	return spin($s);
	}

Of course you can create similar functions in almost any language including C++,C#, Perl, Python and so on.

Kicking the Hash Bucket (PHP)

 

If you have ever studied or taken a class that discusses searching and sorting algorithms and their efficiencies you will be familiar with sequential search, binary search and others. However was bucket search ever mentioned? As a PHP programmer you might be using bucket search not even realizing it. Bucket search is absolutely the fastest most efficient and less complex method available. When using a language PHP that supports hash variables it gets even better and more beneficial.

A normal array uses only integers for the keys.

A[0],A[1],A[2]…

A hash array allows you to use strings as the keys.

A[apple],A[orange],A[banana]…

In traditional methods when you want to search an array for an element to be retrieved you must iterate through the array until you find key and retrieve the value.  However bucket searches allow you to instantly retrieve the information based on the key value with no iteration, as the key is a pointer to the location in memory where the value is stored. That is the power of bucket search and I welcome any comments of another method that proves otherwise.

Here is some code with bucket search in action.

$fruit_color = array('apple' => 'red',
				'orange' => 'orange',
				'banana' => 'yellow');

echo 'An apple is '.$fruit_color[apple].'.';

 

There are however limitations and problems that can arise depending on the type of strings you utilize as the keys in your array, such as the use of special characters, binary characters, utf-8 characters, string is too long, white space, unknown upper and lower case conditions, and others.

Using base64_encode and a few other methods to normalize your key almost all of these issues can be resolved.

$quotes[myKey("This is Sparta!!!\n")] = 'The Movie 300';

function myKey($k)
	{
	return base64_encode(strtolower(preg_replace("/[^A-Za-z0-9]/", '', $k)));
	}

 

Find All Installed TTS Voices for Microsoft Speech Platform SDK (C#)

 

When working with Text To Speech (TTS) voices such offered in the Microsoft Speech Platform SDK and Server Runtime Languages it is not apparent that the voices are actually installed. These voices are offered in an SDK for developers but are not integrated as part of the systems TTS options as you would expect to find in the control panel, speech properties section.

Here is a quick how to for those wanting to install and use these TTS voices in their own C# project.

Download and install the SpeechPlatformRuntime.msi from here:
http://www.microsoft.com/en-us/download/details.aspx?id=24974

Make sure you install the correct version, x64 or x86.

Download and install language and voice packages you prefer from here:
http://www.microsoft.com/en-us/download/details.aspx?id=3971

Start a new C# console project in Visual Studio Express 2012 or whatever version you prefer and name it “SpeechVoicesCheck”.

Take the Micosoft.Speech.dll file and copy it into your project directory and note its location.

Add as a reference to the project by browsing to where you put Microsoft.Speech.dll and including it. This allows you to now add the in the using section to make use of the platform methods:

using Microsoft.Speech.Synthesis;

Here is the code to for the new project which will list all of your installed voice packages and some information regarding them.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Speech.Synthesis;

namespace SpeechVoicesCheck
{
    class Program
    {
        static void Main(string[] args)
        {
            SpeechSynthesizer speaker = new SpeechSynthesizer();
            Console.WriteLine("INSTALLED VOICES");
            Console.WriteLine("");

            
            foreach(InstalledVoice voice in speaker.GetInstalledVoices())
            {
                VoiceInfo info = voice.VoiceInfo;
                
                Console.WriteLine("Voice: " + info.Id + " : " + info.Name + " : " + info.Gender + " : " + info.AdditionalInfo);
                Console.WriteLine("");
            }

            Console.WriteLine("");
            Console.WriteLine("Press any key to close...");

            Console.ReadLine();

        }
    }
}

Halloween 2012 Hays House of Horror

This last Halloween and Christmas I got to experiment around with the Light-O-Rama. It is a device that lets you control AC current to up to 16 devices per box. You can link more boxes together via a network to extend this up to at least 256 connections.
Here is the result of my Halloween mix from 2012.

I am using a single 16 channel Light-O-Rama commercial grade. It requires 30 amps so it has to be plugged into two 15 amp AC outlets. I run an RJ-45 Ethernet cable from the box to the inside where it is connected to a micro mp3 player. The mp3 player has a micro SD card inside it with the play list and all the sound tracks along with the programmed sequences for tracks (making the sequences is the fun part and I will discuss that in a future article.)

One of the channels goes to a 750 watt Macho Strobe, you can see it a few times in the videos on the right side of the house but it is off screen. Two more channels are used to coordinate 6 strands of purple and orange led lights. Another channel controls the cauldron and flame on the porch, and the rest of the channels go to the 16 pumpkins (some pumpkins share the same channel.)

First 10,000 Prime Numbers

Primes, those integers that can only be divided by 1 and themselves. Here is a list of the first ten thousand prime numbers.

Integer Numbers

 

I find numbers extremely fascinating even though I am usually horrible at math I enjoy logical functions and algorithms and especially data structures (probably why I love object orientated languages so much.)  Recently I was playing with some concepts of on demand generated websites that could generate thousands of unique pages utilizing very few lines of code. There are lots of ways to do this, but at the same time I felt one of the goals must be to also generate on those pages some kinds of useful and/or meaningful information.

Within a couple of days I had a little less than thousand lines of code and about 5 web page templates put together to generate every prime number between 1 and 9,223,372,036,854,775,807. That is nine quintillion two hundred twenty-three quadrillion three hundred seventy-two trillion thirty-six billion eight hundred fifty-four million seven hundred seventy-five thousand eight hundred seven.

It’s important because it’s the limiting factor of a 64 bit integer. You’ve probably heard that computer code is really 0’s and 1’s, that’s right. In binary we count using only the digits 0 and 1 instead of 1 through 10 but you add and carry exactly the same.


0001 = 1

0010 = 2

0011 = 3

but when you have 63 of these all set to 1

111111111111111111111111111111111111111111111111111111111111111

it comes out to our magic number of 9,223,372,036,854,775,807.

Why not 64 digits? Because the last bit in PHP is reserved for indicating positive or negative. Some languages such a C allow you to extend the number by sacrificing negative numbers, this is referred to as an “unsigned integer”. But PHP does not support unsigned.

So I put this website together to try and extrapolate interesting information about numbers at IntegerNumber.com, things such as is it a prime number, what divisors and factorization values does it contain, simple hash codes and other base representations besides the standard base 10 and binary.

Just imagine however if Google or another search engine was to try and crawl and index every one of those pages. If Google could crawl 1 page a second, it would take 292,277,506,246 years to crawl every page. That is 20 times the current age of the universe. Also at roughly 1k bits of information per page the storage capacity required would be…my calculator broke…let us say lot 🙂

So to be nice to my hosting provider I decided to limit it to the integer 2,147,483,647 which is max for a 32 bit integer with a length of 31 binary 1’s. Am I not merciful.

 

Quickest Way to Find Prime (PHP)

I had run across a few code snippets of other code slingers discussing algorithms that could run fast enough for real time processing to calculate prime numbers be determining the divisors.  Being the egotistical coder I am I didn’t even bother looking at their code before quickly pulling up my notepad and jotting down a quick for loop to do just that.

The function seemed to work well enough for small integers but at larger numbers in excessive of several million the time to process the loop was excessive.  So then the fun begins, well I find it fun, a puzzle to solve, kind of like solving a Sudoku.  Figure out how to reduce the number of operations to solve the problem.

It is obvious that no divisor is greater than half the number, so (n/2) cuts the operation literally in half. But still larger integers were a taking way too long. So then reading up on some math you can calculate factorizations based on square roots that divide to equal zero. However now we are left with a factorization that looks like this: 2 * 32 * 7 * 11 * 31 * 151 * 331 for the Integer 2147483647 (the highest 32 bit integer in PHP.) Finding the factorization based on the square root of the number is quick and then you simply have to calculate every permutation. A simple sort function gets the work done in O(n^2).

Once you have the number of divisors you only have to count the number to determine if it is prime, which is two, 1 + itself.

 

function primefactor($num)
	{
	$sqrt = sqrt($num);
	for ($i = 2; $i <= $sqrt; $i++)
		{
		if ($num % $i == 0)
			{
			return array_merge(primefactor($num/$i), array($i));
			}
		}
	return array($num);
	}

function divisors($primes,$num)
	{
	$num_primes = count($primes);
	$divisors = Array();

	$limit = pow(2, $num_primes) - 1;

	for($number = 0; $number <= $limit; $number++)
		{
	  $divisor = 1;
		for($i = 0; $i < $num_primes; $i++)
			{
			$divisor *= ($number >> $i) & 1 ? $primes[$i] : 1;
			}
		$divisors[] = $divisor;
		}

	sort($divisors);
	return array_unique($divisors);
	}