Archive for category Code

Web Service using JSONP from External Domain – PHP – JQuery

You may want to look at this previous post where I setup a PHP Webservice that uses JSON PDO – Accessed by JQuery AJAX

OK, so this code will use php to generate the JSON code that will get delivered over the internet to the JSONP (JSON Padding) client on an external domain. This allows your webservice to be available too whoever wants to call it.

Here is the PHP Code: (Not all of it, but enough to get the idea)

//http://SERVER_domain.com/webservice.php
private function GetTriviaTag($row) {
	$t = new Tag();
	$t->id = $row['id'];
	$t->triviaid = $row['triviaid'];
	$t->tagid = $row['tagid'];
	return $t;
}
public function GetWhere($where) {
	$retArray;
 
	$sql = "SELECT * FROM trivia_tags WHERE {$where}";
	foreach ($this->pdo->query($sql) as $row)
	{
		$retArray[] = $this->GetTriviaTag($row);
	}
	return $retArray;
}
$where = " (1 = 1)";  // THIS WILL SELECT ALL
$tarray = GetWhere($where);
 
//OUTPUT JSON:
header('Content-type: application/json');
echo $_GET['callback'];  // <-- THIS IS IMPORTANT FOR EXTERNAL DOMAIN ACCESS!!!
echo "(" . json_encode($tarray) . ")";

And now, to access it from javascript in an external domain (non – SERVER_domain.com ):

http://CLIENT_domain.com/Test.html:

<html>
	<head>
		<title>Test</title>
		<script src="http://code.jquery.com/jquery-latest.js"></script>
	</head>
	<body>
		<div id="triviaQuestions"> loading... </div>
		<script>
			$(function() {
				// THE 'callback=?' in this request is IMPORTANT FOR EXTERNAL DOMAIN ACCESS!!!
				$.getJSON('http://SERVER_domain.com/webservice.php&callback=?', function(data) {
					var items = [];
					var htmlResult = "";
					$.each(data, function(key, val) {
						htmlResult += "<br />Q: "+ val.id +", '"+ val.question +"";
					});
					$('#triviaQuestions').html(htmlResult);
				});
			});
		</script>
	</body>
</html>

, , , , , , , , , , , , , , , , , , , , , , , , ,

No Comments

PHP Webservice that uses JSON PDO – Accessed by JQuery AJAX

You may want to look at this previous post where I setup a Web Service using JSONP from External Domain – PHP – JQuery

The HTML that calls the Javascript:

<div id="taglist"></div>
<input name="searchTags" id="searchTags" type="text" />
<input type="button" name="searchtags" onclick="getTags()" value="search"/>
<div id="tagresult">
</div>

The JavaScript (JQuery) AJAX Request and Response Processing:

function getTags()
	{
		var q = $('#searchTags').val();
		$.getJSON('ws.php?type=tag&wN=name&wO=like&wV=' + q, function(data) {
			var items = [];
			var htmlResult = "";
			$.each(data, function(key, val) {
				//As you can see, you can access the JSON (at the bottom of the page) by doing val.PROPERTYNAME:
				htmlResult += "<br />Add : <a href=\"#\" onclick=\"addTag("+ val.id +", '"+ val.getfullname +"'); return false;\">"+ val.getfullname +"</a>";
			});
			$('#tagresult').html(htmlResult);
		});
	}

PHP Code that returns JSON in the PHP file called by the AJAX: (ws.php)

	$ta = new TagAccess();
	$tarray = $ta->GetTagsWhere(" {$whereName} LIKE '%{$whereVariable}%'");
	header('Content-type: application/json');
	echo "",  json_encode($tarray), "";

The GetTagsWhere Helper Function:

    public function GetTagsWhere($where) {
    	$retArray;
 
    	$sql = "SELECT * FROM tags WHERE {$where}";
    	// THE PDO Object was created previously
	foreach ($this->pdo->query($sql) as $row)
	{
		$retArray[] = $this->GetTag($row);
	}
	return $retArray;
    }

JSON Returned:

[{"id":"4","name":"FICTION","parentid":"3","getfullname":"BOOKS > FICTION"},{"id":"5","name":"NON-FICTION","parentid":"3","getfullname":"BOOKS > NON-FICTION"}]

, , , , , , , , , , ,

No Comments

ASP.Net Update Panel – Javascript Event – jQuery Click

I needed to add a onclick event to a textbox in asp.net to change it to remove text from a textbox onClick when it is clicked.
The normal code would look something like this:

1
<asp:TextBox  ID="txtStoreLocatorZip" ValidationGroup="CustomerServiceEmail" runat="server" Text="Enter Zip" CssClass="txtStoreLocatorZip_CssClass" />
1
2
3
4
5
6
7
8
9
<script>
        if ($('.txtStoreLocatorZip_CssClass').val() == 'Enter Zip') {
            $('.txtStoreLocatorZip_CssClass').click(function () {
                if ($('.txtStoreLocatorZip_CssClass').val() == 'Enter Zip') {
                    $('.txtStoreLocatorZip_CssClass').val('');
                }
            });
        }
</script>

But, this won’t quite work because my textbox is in a UpdatePanel’s ContentTemplate and the javascript is not read on postback.

So, This is what I ended up doing (a simplified version):

1
2
3
4
5
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
	<ContentTemplate>
		<asp:TextBox  ID="txtStoreLocatorZip" ValidationGroup="CustomerServiceEmail" runat="server" Text="Enter Zip" CssClass="txtStoreLocatorZip_CssClass" />
	</ContentTemplate>
</asp:UpdatePanel>
1
2
3
4
5
6
7
8
9
10
11
12
<script>
	Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);
	function endRequestHandler(sender, args) {
		if ($('.txtStoreLocatorZip_CssClass').val() == 'Enter Zip') {
			$('.txtStoreLocatorZip_CssClass').click(function () {
				if ($('.txtStoreLocatorZip_CssClass').val() == 'Enter Zip') {
					$('.txtStoreLocatorZip_CssClass').val('');
				}
			});
		}
	}
</script>

This will add an endRequest handler to the end of the partial page postback so that you can call a nice little function at the end of it.

Hope this helps some people!

, , , , , , ,

No Comments

Asp.Net – Adding Parameters to CommandType.Text

This is how you add parameters to a standard CommandType.Text SQL call.

This should prevent sql injection attacks.

        Using conSQL = New SqlConnection("CONNECTION STRING TO DATABASE")
            Try
                str = "SELECT * FROM TableName where customerid = @CustomerID and CartType = @CartType"
                cmdSQL = New SqlCommand(str, conSQL)
                cmdSQL.CommandType = CommandType.Text
                cmdSQL.Parameters.AddWithValue("@CustomerID", CustomerID)
                cmdSQL.Parameters.AddWithValue("@CartType", cartType)
                cartcount = cmdSQL.ExecuteScalar()
            Catch ex As Exception
                cartcount = 0
            End Try
        End Using

, , , , , ,

No Comments

Asp DropDownList – States – ListItem Example

Asp DropDownList - States - ListItem Example
Compiled List of US State Drop Downs for Asp.Net Forms:

Hope this helps!

<asp:dropdownlist ID="ddlState" runat="server">
    <asp:listitem Value="" Selected="True">Select a State</asp:listitem>
    <asp:listitem value="AL">Alabama</asp:listitem>
    <asp:listitem value="AK">Alaska</asp:listitem>
    <asp:listitem value="AZ">Arizona</asp:listitem>
    <asp:listitem value="AR">Arkansas</asp:listitem>
    <asp:listitem value="CA">California</asp:listitem>
    <asp:listitem value="CO">Colorado</asp:listitem>
    <asp:listitem value="CT">Connecticut</asp:listitem>
    <asp:listitem value="DC">D.C.</asp:listitem>
    <asp:listitem value="DE">Delaware</asp:listitem>
    <asp:listitem value="FL">Florida</asp:listitem>
    <asp:listitem value="GA">Georgia</asp:listitem>
    <asp:listitem value="HI">Hawaii</asp:listitem>
    <asp:listitem value="ID">Idaho</asp:listitem>
    <asp:listitem value="IL">Illinois</asp:listitem>
    <asp:listitem value="IN">Indiana</asp:listitem>
    <asp:listitem value="IA">Iowa</asp:listitem>
    <asp:listitem value="KS">Kansas</asp:listitem>
    <asp:listitem value="KY">Kentucky</asp:listitem>
    <asp:listitem value="LA">Louisiana</asp:listitem>
    <asp:listitem value="ME">Maine</asp:listitem>
    <asp:listitem value="MD">Maryland</asp:listitem>
    <asp:listitem value="MA">Massachusetts</asp:listitem>
    <asp:listitem value="MI">Michigan</asp:listitem>
    <asp:listitem value="MN">Minnesota</asp:listitem>
    <asp:listitem value="MS">Mississippi</asp:listitem>
    <asp:listitem value="MO">Missouri</asp:listitem>
    <asp:listitem value="MT">Montana</asp:listitem>
    <asp:listitem value="NE">Nebraska</asp:listitem>
    <asp:listitem value="NV">Nevada</asp:listitem>
    <asp:listitem value="NH">New Hampshire</asp:listitem>
    <asp:listitem value="NJ">New Jersey</asp:listitem>
    <asp:listitem value="NM">New Mexico</asp:listitem>
    <asp:listitem value="NY">New York</asp:listitem>
    <asp:listitem value="NC">North Carolina</asp:listitem>
    <asp:listitem value="ND">North Dakota</asp:listitem>
    <asp:listitem value="OH">Ohio</asp:listitem>
    <asp:listitem value="OK">Oklahoma</asp:listitem>
    <asp:listitem value="OR">Oregon</asp:listitem>
    <asp:listitem value="PA">Pennsylvania</asp:listitem>
    <asp:listitem value="RI">Rhode Island</asp:listitem>
    <asp:listitem value="SC">South Carolina</asp:listitem>
    <asp:listitem value="SD">South Dakota</asp:listitem>
    <asp:listitem value="TN">Tennessee</asp:listitem>
    <asp:listitem value="TX">Texas</asp:listitem>
    <asp:listitem value="UT">Utah</asp:listitem>
    <asp:listitem value="VT">Vermont</asp:listitem>
    <asp:listitem value="VA">Virginia</asp:listitem>
    <asp:listitem value="WA">Washington</asp:listitem>
    <asp:listitem value="WV">West Virginia</asp:listitem>
    <asp:listitem value="WI">Wisconsin</asp:listitem>
    <asp:listitem value="WY">Wyoming</asp:listitem>
</asp:dropdownlist>

More State Drop Downs After the fold:
Read the rest of this entry »

, , , , , , , , , , , , , , ,

1 Comment

Asp.Net VB – Listview – ItemCommand – DataKeys – CommandName – SQL

Asp.Net VB - Listview - ItemCommand - DataKeys - CommandName - SQL

Here is a basic Listview that has an ItemCommand and ItemDataBound:

Frontend Code:

<asp:ListView ID="lvAddresses" runat="server" DataKeyNames="AddressID,BillingAddressID,ShippingAddressID">
        <LayoutTemplate>
            <asp:PlaceHolder ID="itemPlaceholder" runat="server"></asp:PlaceHolder>
        </LayoutTemplate>
        <ItemTemplate>
            <table class="noborder address_book" cellpadding="0" cellspacing="0"><tbody>
                <tr>
                    <td colspan="2">
                        <%#DataBinder.Eval(Container.DataItem, "FirstName")%> <%#DataBinder.Eval(Container.DataItem, "LastName")%><br>
                        <%#DataBinder.Eval(Container.DataItem, "Address1")%><br>
                        <%#DataBinder.Eval(Container.DataItem, "City")%>, <%#DataBinder.Eval(Container.DataItem, "State")%>, <%#DataBinder.Eval(Container.DataItem, "Zip")%><br>
                        <%#DataBinder.Eval(Container.DataItem, "Phone")%><br>
                        <span class="caption"><asp:LinkButton ID="lnkMakeDefault_Billing" CommandName="MakeDefault_Billing" runat="server">Click to make Default Billing Address</asp:LinkButton></span>
                        <span class="caption"><asp:Literal ID="litMakeDefault_Billing" runat="server" Text="Default Billing Address"></asp:Literal></span>
                        <br />
                        <span class="caption"><asp:LinkButton ID="lnkMakeDefault_Shipping" CommandName="MakeDefault_Shipping" runat="server">Click to make Default Shipping Address</asp:LinkButton></span>
                        <span class="caption"><asp:Literal ID="litMakeDefault_Shipping" runat="server" Text="Default Shipping Address"></asp:Literal></span>
                    </td>
                </tr>
                <tr>
                    <td>
                        <asp:Button ID="Button1" runat="server" Text="EDIT" CommandName="EDITAddress"/>
                    </td>
                    <td>
                        <asp:Button ID="btnREMOVE" runat="server" Text="REMOVE" CommandName="REMOVEAddress"/>
                    </td>
                </tr>
            </tbody></table>
 
        </ItemTemplate>
    </asp:ListView>

Backend Code:

Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
 
        FindIt()
 
    End Sub
    Private Sub FindIt()
 
        lblAddresses.Text = ""
 
        Dim sqlDataConnection As System.Data.SqlClient.SqlConnection = CDataAccess.OpenDatabase
        Dim conStr As String = sqlDataConnection.ConnectionString
        sqlDataConnection.Close()
 
        Dim selectCommand As String = "SELECT Address.*, Customer.BillingAddressID, Customer.ShippingAddressID"
        selectCommand &= " FROM Address INNER JOIN Customer ON Address.CustomerID = Customer.CustomerID"
        selectCommand &= " WHERE Address.CustomerID = @CustomerID AND Address.Deleted = 0"
 
        Dim sds As New SqlDataSource()
        sds.ConnectionString = conStr
        sds.SelectParameters.Clear()
 
        sds.SelectParameters.Add("CustomerID", 12345)
        sds.SelectCommand = selectCommand
 
        lvAddresses.DataSource = sds
        lvAddresses.DataBind()
    End Sub
 
    Protected Sub lvAddresses_ItemCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewCommandEventArgs) Handles lvAddresses.ItemCommand
        Dim dataItem As ListViewDataItem = e.Item
        Dim currentDataKey As DataKey = lvAddresses.DataKeys(dataItem.DataItemIndex)
        Dim AddressID As Integer = currentDataKey("AddressID")
        Dim BillingAddressID As Integer = currentDataKey("BillingAddressID")
        Dim ShippingAddressID As Integer = currentDataKey("ShippingAddressID")
 
        'MakeDefault_Billing
        'MakeDefault_Shipping
        'EDITAddress
        'REMOVEAddress
        If String.Equals(e.CommandName, "MakeDefault_Billing") Then
            MakeDefault(AddressID, True)
        ElseIf String.Equals(e.CommandName, "MakeDefault_Shipping") Then
            MakeDefault(AddressID, False)
        ElseIf String.Equals(e.CommandName, "EDITAddress") Then
            EditAddress(AddressID)
        ElseIf String.Equals(e.CommandName, "REMOVEAddress") Then
            RemoveAddress(AddressID)
        End If
    End Sub
 
    Protected Sub lvAddresses_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewItemEventArgs) Handles lvAddresses.ItemDataBound
        Dim dataItem As ListViewDataItem = e.Item
 
        If e.Item.ItemType = ListViewItemType.DataItem Then
            Dim currentDataKey As DataKey = lvAddresses.DataKeys(dataItem.DataItemIndex)
            Dim AddressID As Integer = currentDataKey("AddressID")
            Dim BillingAddressID As Integer = currentDataKey("BillingAddressID")
            Dim ShippingAddressID As Integer = currentDataKey("ShippingAddressID")
            lit = e.Item.FindControl("litMakeDefault_Billing")
            Dim lit2 As Literal = e.Item.FindControl("litMakeDefault_Shipping")
            lnk = e.Item.FindControl("lnkMakeDefault_Billing")
            Dim lnk2 As LinkButton = e.Item.FindControl("lnkMakeDefault_Shipping")
 
            lit.Visible = Not lnk.Visible
        End If
 
    End Sub

, , , , , , , , , , , , , , , , , , , , , , , ,

No Comments

ASPDotNetStoreFront: Adding Topic to XML Packages or .aspx Pages

This is how you add a DotNetStoreFront’s Topic into a XMLPackage:

<xsl:value-of select="aspdnsf:Topic('TOPIC_NAME')" disable-output-escaping="yes"/>

Now, if you want to add it to a .aspx or .ascx page on dnsf:

<aspdnsf:Topic runat="server" ID="Topic1" TopicName="TOPIC_NAME" />

, , , , , , , , , , , , , ,

No Comments

Simple PHP Pseudo Proxy

php proxy simple pseudo

This is the code for a simple php pseudo proxy. If you are blocked by a firewall and google cache isn’t working for some reason. You can use a url with this php file in it:

<?php
$filename = $_GET["url"];
if (isset($filename))
{
        $handle = fopen($filename, "rb");
        $contents = stream_get_contents($handle);
        print $contents;
        fclose($handle);
}
else
{
        echo "url";
?>
<form method="GET">
<input type="text" name="url" /><input type="submit"/>
</form>
<?php
}
?>

Then you can go to where the url is hosted and try something like this:

index.php?url=http%3A%2F%2Fwww.last.fm%2Fuser%2Fdanfolkes%2Fcharts%3Frangetype%3D6month%26subtype%3Dartists

, , , , , ,

No Comments

Facebook Website Integration – HTML


To integrate Facebook on to a website without the use of a facebook app you need these things:

Once you have both of those things you can do this in feedburner:

  • Add a new feed (your facebook url)
  • Go to the publicize tab
  • Go to BuzzBoost
  • Sroll down and fill out the form, you will be given html code.
  • <script src="http://feeds.feedburner.com/DanielFolkessFacebookStatusUpdates?format=sigpro" type="text/javascript" ></script>
    <noscript><p>Subscribe to RSS headline updates from: 
    <a href="http://feeds.feedburner.com/DanielFolkessFacebookStatusUpdates"></a>
    <br/>Powered by FeedBurner</p> 
    </noscript>
  • Preview:

And that’s it!
You can now style it up a little bit with some CSS and stuff.

, , , , , , , , , ,

No Comments

Java – Singleton / Global – Data Access – SQLite

This will make a Java global object:

import java.io.File;
import java.io.IOException;
 
import com.almworks.sqlite4java.SQLite;
import com.almworks.sqlite4java.SQLiteConnection;
import com.almworks.sqlite4java.SQLiteException;
import com.almworks.sqlite4java.SQLiteJob;
import com.almworks.sqlite4java.SQLiteQueue;
import com.almworks.sqlite4java.SQLiteStatement;
 
public final class DataAccess {
	// Singleton Stuff
	private static class SingletonHolder { 
	     public static final DataAccess INSTANCE = new DataAccess();
	}
	public static DataAccess getInstance() {
	     return SingletonHolder.INSTANCE;
	}
	// End Singleton Stuff
 
 
	private String HomePath = "";
	private File DBFile;
	private static SQLiteQueue queue;
	private boolean initalized = false;
 
	private DataAccess()
	{
		if (!initalized)
		{
			initDB();
 
			initalized = true;
		}
	}
 
	private void initDB()
	{
		DBFile = locateDBFile();
		DeleteDatabaseContents();
	}
	private File locateDBFile()
	{
		File f = null;
		try{
			HomePath = System.getProperty("user.home");
    	    System.out.println("HomePath: " + HomePath);
    	    f = new File(HomePath + "/database.sqlite");
    	    if (f.canRead())
    	    	return f;
    	    else
    	    {
        	    boolean success = f.createNewFile();
        	    if (success) {
        	        // File did not exist and was created
        	    } else {
        	        // File already exists
 
        	    }
    	    }
    	} catch (IOException e) {
    		//Maybe try a new directory.
    	}
		return f;
	}
 
	private void DeleteDatabaseContents()
	{
		queue.execute(new SQLiteJob<Object>() 
		{
		    protected Object job(SQLiteConnection connection) throws SQLiteException 
		    {
		      // this method is called from database thread and passed the connection
				StringBuilder sb = new StringBuilder();
				sb.append("DROP TABLE IF EXISTS Playlist;");
				sb.append("DROP TABLE IF EXISTS Settings;");
				//sb.append("DELETE FROM someTable;");
				//sb.append("DELETE FROM someTable;");
 
 
				connection.exec(sb.toString());
				return null;
		    }
		});
	}
	public String getHomePath()
	{
		return HomePath;
	}
}

Now you can run this from anywhere:

DataAccess da;
da = DataAccess.getInstance();

Source: http://en.wikipedia.org/wiki/Singleton_pattern

, , , , , , , ,

No Comments

PHP API – Google Calendar – Updating Visibility

The Privacy / Visibility Part:

$event->visibility->value = "http://schemas.google.com/g/2005#event.private";

Here it is in context: Read the rest of this entry »

, , , , , , , , , , , , , , , , ,

2 Comments

Minecraft – Script – Backup – Update Server – Restart

This is the script I use that will:

  • Automatically backup minecraft map
  • Automatically update minecraft server
  • Automatically restart the server if it stops or dies
#!/bin/bash
while [ true ]; do
   # make md5 of current file for update check.
   md5sum minecraft_server.jar > minecraft_server.jar.md5
   wget -o updatelog.log -N --trust-server-names http://www.minecraft.net/download/minecraft_server.jar
   # display updated status
   if md5sum -c --status minecraft_server.jar.md5 
   then
    echo "Server Up to Date."
   else
    echo "Updated Server!"
   fi
   java -Xmx1024M -Xms1024M -jar minecraft_server.jar nogui
   rsync -a --delete --progress /home/dan/serv/minecraft/world "/home/dan/serv/minecraft/bak/world"`eval date +%Y%m%d`""
done

Code Explained:

This will put the server in an infinite loop. You can kill it by hitting Control+C a couple times in a row.

while [ true ]; do

This will make a hash of the current minecraft_server.jar and then download the newest copy using wget.

md5sum minecraft_server.jar > minecraft_server.jar.md5
wget -o updatelog.log -N --trust-server-names http://www.minecraft.net/download/minecraft_server.jar

This will run minecraft in headless mode and with a limit on RAM.

java -Xmx1024M -Xms1024M -jar minecraft_server.jar nogui

This will create a backup of the minecraft world folder in a backup folder. You probably should work on this part.

rsync -a --delete --progress /path/to/minecraft/world "/path/to/minecraft/bak/world"`eval date

Well, hope this helps someone. Have a good day.

No Comments

Rsync – Speed Limit – Trickle – Slow

Install rsync and trickle:

sudo apt-get install rsync
sudo apt-get install trickle

Now you can run rsync:
This will download at a limit of 80 KB/s from host:

rsync -auvPe "trickle -d 80 ssh" user@host:/src/ /dst/

Explanation of Commands:

-a, --archive               archive mode; equals -rlptgoD (no -H,-A,-X)
-u, --update                skip files that are newer on the receiver
-v, --verbose               increase verbosity
-P  --progress              show progress during transfer
-e, --rsh=COMMAND           specify the remote shell to use
trickle -d 80  = -d rate    Limit the download bandwidth consumption to rate KB/s.

, , , , , , , , , , , , , , , , ,

No Comments

Outlook Rule : Only at Specific Times

Lets say you want to have a rule in outlook send to you only between specific times in the day.

  • Only after 6pm and before 8am
  • Only on your lunch hour
  • When you are not at work

I will explain this by having emails forward to my cell phone, only when I am normally not at the office. (From 6pm-8am) This way, I will be able to receive important emails that may require special outside assistance.

What I do is:

  • Create a special category called FWD
  • Use other rules to set messages into the FWD category if I want them forwarded. (Explained Below)
  • Then, create a rule to run last in the rules list called FWD Rule
  • *Important Part* This will check the time on the messages, if it’s within the specified hours, it will forward the email (Explained Below)

Creating a Rule to set the FWD Category:
Your Rule Description should look something like this. The important part is that it is assigning it to the FWD Category:

Apply this rule after the message arrives
with 'Emergency from client' in the subject
    and marked as 'high importance'
    and assigned to 'FWD' Category

The Rule that will email header* for UTC times. Make sure it’s assigned to the FWD category. And then FWD it:

Apply this rule after the message arrives
with '2011 23:' or '2011 02:' or ... '2011 10:' in the message header
    and assigned to 'FWD' category
forward it to 'email@example.com'

* This should work on most emails, but if you want to look at the email header Right-click on the message in the Inbox and select Message Options.
* I included the 2011 and the colon to make it more specific.

UTC Time for 6pm – 8am:
Email Header contained:
X-OriginalArrivalTime: 18 Feb 2011 03:23:52.0368 (UTC)
So I searched for:

2011 23:,2011 01:,2011 02:,2011 03:,2011 04:,2011 05:,2011 06:,2011 07:,2011 08:,2011 09:,2011 10:,2011 11:

, , , , , , , , , , , , , , , , ,

3 Comments

jQuery – Ajax – Extra Parameters – GET, success

Here is the standard jQuery Ajax call with success handler as well as the ability to pass another parameter to an external function:

	$.ajax({
			type: "GET",
			url: Humancurl,
			dataType: "xml",
			success: function(data){
				NameOfFunctionToParseReturnedData(data,ExtraParameter);
			}
		});

Here is the standard jquery ajax call with success handler:

$.ajax({
  url: 'ajax/test.html',
  success: function(data) {
    $('.result').html(data);
    alert('Load was performed.'+data);
  }
});

No Comments

Ubuntu Samba – Read-Write-FSTAB-Cifs-Mount


This is my current setup for my two Ubuntu 10.10 (Maverick Meerkat) boxes. One shares a read/write folder to the other. This is my setup. I think the key to this is having the same username on both computers having access to the files.

You might have to run this on the the folder:
sudo chmod -R 777 /path/to/files
sudo chown -R usernameonbothcomputers:usernameonbothcomputers /path/to/files

I installed samba by doing: sudo apt-get install samba

/etc/samba/smb.conf : (on the computer serving the files)

[global]
	workgroup = WORKGROUP
	server string = %h server (Samba, Ubuntu)
	dns proxy = no
 
	interfaces = 127.0.0.0/8 eth0
	bind interfaces only = yes
 
	log file = /var/log/samba/log.%m
	max log size = 1000
	syslog = 0
 
	panic action = /usr/share/samba/panic-action %d
	encrypt passwords = true
	passdb backend = tdbsam
	obey pam restrictions = yes
	unix password sync = yes
	passwd program = /usr/bin/passwd %u
	passwd chat = *Enter\snew\s*\spassword:* %n\n *Retype\snew\s*\spassword:* %n\n *password\supdated\ssuccessfully* .
	pam password change = yes
 
	guest account = nobody
	invalid users = root
	usershare allow guests = yes
 
[MyFiles]
	path = /path/to/share
	writable = yes
	read only = no
	valid users = usernameonbothcomputers

sudo /etc/init.d/smbd reload

/etc/fstab : (on the computer accessing the files)

//SAMBASHAREsSERVERNAME/MyFiles /path/to/mount cifs users,,noatime,username=usernameonbothcomputers,password=theuserspassword 0 0

You should be able to run this to mount all things in your fstab:
sudo mount -a

, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,

No Comments

.Net – Sending Email with In Memory Attachment

This VB.Net code takes the FileUpload control’s PostedFile and without saving it to the filesystem attaches it to an MailMessage and sends an email.

Advantages:

  • No threading, read/write permissions needed.
  • One line of code.

Front End:

<asp:FileUpload ID="fileUpload" runat="server" />

Code:

Dim m As New MailMessage()
m.Attachments.Add(New Attachment(fileUpload.PostedFile.InputStream, fileUpload.FileName))

, , , , , , , , , , , , , , , , , , , , , , , , ,

No Comments

Pitchfork 'Best New Albums' Torrent Search

Pitchfork_Best_new_Music_BTJunkie_Search

Ok so this might be slightly illegal, but I am really just generating some links.

I wrote some code that will take the RSS feed from this page: http://pitchfork.com/reviews/best/albums/ and searches BTJunkie for torrents.

Here it is in action:
http://danfolkes.com/pitchfork_torrent_albums_best/

Here is the source: (also here)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?php
  echo "<table border=1>";
  $doc = new DOMDocument();
  $doc->load('http://feeds2.feedburner.com/PitchforkBestNewAlbums');
 
  foreach ($doc->getElementsByTagName('item') as $node) {
	echo "<tr><th colspan='2'>";
	$title = $node->getElementsByTagName('title')->item(0)->nodeValue;
	echo $title;
    $doc2 = new DOMDocument();
 	$doc2->load("http://btjunkie.org/rss.xml?query=".urlencode($title));
	echo "</th></tr>";
	foreach ($doc2->getElementsByTagName('item') as $node2) {
		echo "<tr><td></td><td>";
		$link = "<a href='".$node2->getElementsByTagName('link')->item(0)->nodeValue."' target='_blank'>";
		$link.= $node2->getElementsByTagName('title')->item(0)->nodeValue."</a>";
		echo $link;
		echo "</td></tr>";
	}
 
  }
  //print_r($arrFeeds);
  echo "</table>";
 
?>

No Comments

PHP Base64_Encode – Intentionally screwing up pictures

A screwed up base64 image.  Replaced all of the 'da' with 'ha'

A screwed up base64 image. Replaced all of the 'da' with 'ha'

So, I was a little bored so I made some PHP code.

This is what it does:

  • Takes query string values
  • Pulls an image from the web
  • base64_encodes it.
  • Distorts the image.
  • Replaces some of the base64 string data with other string data.
  • Outputs the image in an img tag.

Hope this helps someone, let me know if it does IN THE COMMENTS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<?php
	if ((isset($_GET['i']))&&(isset($_GET['f']))&&(isset($_GET['r'])))
	{
		$find = $_GET['f'];
		$replace = $_GET['r'];
		$type = "gif";
		print_r($_GET);
 
		if (isset($_GET['t']))
		{
			$type = $_GET['t'];
		}
		$imgfile = $_GET['i'];
		$contents = implode (file($imgfile));
		$start = base64_encode($contents);
 
 
		$start = str_ireplace($find, $replace, $start);
 
	echo '<img src="data:image/'.$type.';base64,' . $start . '" />';
	}
	else
	{
	?>
		Try: <a href='base64.php?i=http://ec.europa.eu/culture/media/programme/images/logos/02/02.gif17.gif&f=lo&r=ha&t=gif'>http://ec.europa.eu/culture/media/programme/images/logos/02/02.gif17.gif&f=lo&re=ha&t=gif</a>
	<?php
	}
 
?>

, , , , , , , , ,

1 Comment

JQuery – Example Documents for Presentation

jquery-selectors

I gave a presentation at work on JQuery.

So, I made a documentation page and a example html page with jquery calls at the bottom.

This should be able to help someone out there in internet land.

View the post to see code.

Read the rest of this entry »

No Comments

PHP Gmail Imap Connection with Database Insert

gmail php mysql imap
Using PHP, We will connect to a Gmail mailbox and pull down the last message headers and to and from email addresses.
With this data, we will insert it into a MySQL Database and then delete the message from the IMAP Server.

LET ME KNOW IF THIS HELPED YOU IN THE COMMENTS! Enjoy!

Here is the code:
Read the rest of this entry »

5 Comments

jQuery: Check All of the Checkboxes

This will check all of the checkboxes inside of an element (div,span,table) with a class of outerClassName

$(".outerClassName :checkbox").attr('checked', true);

Tip: you must have the jQuery library referenced before using this line of code.

No Comments

TikiWiki – Tracker Email Subject Improvement-Modification

tikiwiki

The template for the Tracker email is here:
\tikiwiki\templates\mail\tracker_changed_notification_subject.tpl

I changed it to this so that it would improve the way it looks in emails:

{$mail_trackerName}{tr} - #{/tr}{$mail_itemId}{tr} modified.{/tr}

, , , , , , , , , , ,

No Comments

Override the window.onload javascript function

1. Creates a blank function
2. Checks onload for a function.
2a. Sets the originial onload function as temp
3. calls the new function initMap() before the originial temp onload function.

Pretty cool!

Code:

1
2
3
4
5
6
7
var temp=function(){ return 1;};
if( window.onload )
{
      //override "placeholder" with whatever already exists in onload
     temp = window.onload;
}
window.onload=function(){ TheFunctionYouWantToCall(); temp();};

2 Comments

Rotating Circular Periodic Table – Javascript

Circular_form_of_periodic_table_sm

I just saw an article on this site about the merits of a circular periodic table by Mohd Abubakr Design

I thought it would be nice to have one that rotates. So I used the jQuery and jQuery-Rotate library on it to make it spin.

I hope this will be help someone and I hope to make additions to it in the future.
[[View Rotating Circular Periodic Table]]

, , , , , , , , , , , ,

2 Comments

DanFolkes FLVPlayer – Create your own FLVPlayer (like jw-flv-player) with no branding

DanFolkes-FLVPlayer

Using Flash CS4: Read the rest of this entry »

, , , , , , , ,

No Comments

Started to work on a Simple Photo Slideshow.

It’s going to be a lot like:

http://www.evrium.com/store/fg2p_details.php

But much cheaper.

, , , ,

No Comments

Hubble Image RSS Feed

hs-2009-13-a-web

I have used Google Reader to mash two image rss feeds together for Hubble.

Here is the HTML page for it:
https://www.google.com/reader/shared/user%2F15478232717259537591%2Flabel%2FHubble

Here is the RSS Feed:
http://www.google.com/reader/public/atom/user%2F15478232717259537591%2Flabel%2FHubble

Based off of:
http://hubblesite.org/newscenter/newscenter_rss.php
and
http://www.spacetelescope.org/rss/feed.xml

Enjoy space nerds.

, , , , , , , , , , , , , , , ,

No Comments

IP Locator Webservice – PHP – Ipmap – Command Line

This is similar to my Python script here:
http://danfolkes.com/index.php/2009/04/29/ipmapcom-python/

It uses this sites service to pull the location of each user:
http://www.ipmap.com/

It outputs in XML, Plain Text, and HTML.
Fields:

  • ip
  • hostname
  • ipreverse
  • country
  • region
  • city
  • blacklist
  • gmaps

HERE IS THE LINK TO THE WEB SERVICE SITE:
http://www.danfolkes.com/ipmaps/

No Comments