Monday, December 30, 2013

Enable UART2 On BeagleBone Black for RS232 Cape


  1. Use this script to ensure UART2 is enabled in the device tree: https://github.com/victorporof/BeagleBone-SPI-UART
  2. Enable ttyO1 it in the firmware using this guide (makes the device appear): http://www.element14.com/community/blogs/mirandasoft/2013/07/30/beaglebone-black-rapid-activation-of-ttyo1-ttyo2-ttyo4-and-ttyo5
  3. Put a paperclip into the RS232 port like in the picture on this page: http://sensorsblog.com/serial-communications/rs232loopbacktest/
  4. echo hello > /dev/ttyO1
  5. cat /dev/ttyO1

Sunday, December 29, 2013

Clustering With Leaflet

http://jmduke.com/blog/2013/12/28/seattle-911

The Z Layout

I'm definitely going to use this technique on my next business site: http://design.tutsplus.com/articles/understanding-the-z-layout-in-web-design--webdesign-28

Two Column Match - Flask + HandsOnTable

I'm getting more comfortable with Flask, so I decided to experiment with Google App Engine + Flask + HandsOnTable.

Here's the application I made: http://twocolumnmatch.appspot.com/match

It takes the contents of the 2nd column and matches it to the rows of the first column. Just press the "Match" button to see what it does.

I've found myself doing what this application does a few times, but I manually create two python lists and compare them in IDLE. This application streamlines that process quite a bit.

Here's the code: https://github.com/pawl/2ColumnMatch

Thursday, December 26, 2013

SQLalchemy - Simple Select Query

from sqlalchemy import create_engine, MetaData, Table

engine = create_engine('sqlite:///cars.db', echo=False)
metadata = MetaData(bind=engine)

table = Table('cars', metadata)
stmt = table.select()
for row in stmt.execute():
    print row

Entity-Attribute-Value - Dynamic Database Columns

This page has a great example of when to use the Entity-Attribute-Value data model: http://stackoverflow.com/questions/7933596/django-dynamic-model-fields

I'm planning to use it for an application I'm making which has user defined fields.

Wednesday, December 18, 2013

SHOW COLUMNS or Get Column Names From SQLalchemy SELECT Query


Rob Wouter's answer really helped me out:

You can either find the columns by calling result.keys() or you can access them through calling v.keys() inside the for loop.
Here's an example using items():
for v in result:
    for column, value in v.items():
        print('{0}: {1}'.format(column, value))

Wednesday, December 11, 2013

AttributeError: 'dict' object has no attribute '_set_parent_with_dispatch' - SQLalchemy



The documentation says: "Keyword arguments can be specified by specifying the last argument as a dictionary"

So you will need to change this:
__table_args__ = (
{'sqlite_autoincrement': True},
            UniqueConstraint('filename', 'path')
            )

to this:
__table_args__ = (
            UniqueConstraint('filename', 'path'),
            {'sqlite_autoincrement': True}

            )

Flask-Admin Foreign Key Columns Allowing Editing

Make sure you have a row id number as your primary key for your child table. Having a composite primary key didn't seem to save when I was editing the form.

Thursday, December 5, 2013

Wednesday, November 27, 2013

jPanelMenu Causing Document.Ready() To Run Twice

This line in jquery.jpanelmenu.js is the cause:
$('body > *').not(jP.menu + ', ' + jP.options.excludedPanelContent).wrapAll('<div class="' + 'jPanelMenu-panel' + '"/>');

You will need to comment it out and wrap everything in your body tag manually with:
<div class="jPanelMenu-panel" style="position: relative; left: 0px;">
</div>

The end result will look like:
<body>
<div class="jPanelMenu-panel" style="position: relative; left: 0px;">
all your code....
</div>
</body>


This page helped me figure it out: http://doctype.com/trying-jquery-wrapall-seems-wrap-content-twice

Tuesday, November 5, 2013

Catch ldap_bind(): Unable to bind to server: Invalid credentials

I used the tip from this page: http://bytes.com/topic/php/answers/600903-ldap_bind-warning-instead-false

"You can get around this if you supress warning and error messages by
putting a @ in front of the function name:

$ldapbind = @ldap_bind($ldapconn, $ldaprdn, $ldappass);"

Yii Google Chart Extension

Here's YiiWheel's google chart wrapper extension: https://github.com/2amigos/yiiwheels/blob/master/widgets/google/WhVisualizationChart.php

I downloaded just the WhVisualizationChart file and put this in my view:

$this->widget('ext.WhVisualizationChart', array(
    'visualization' => 'PieChart',
    'data' => $chartDataProvider,
    'options' => array(
        'pieHole'=> '0.5',
        'backgroundColor'=>array('fill'=>'transparent'),
    ),
    'htmlOptions'=>array('style'=>'width:100%; height:375px'),
));

and this in my controller:

public function actionIndex()
{
        $chartDataProvider = array(
            array('Task', 'Hours per Day'),
            array('Work', 11),
            array('Eat', 2),
            array('Commute', 2),
            array('Watch TV', 2),
            array('Sleep', 7)
        );
$this->render('index', array('chartDataProvider'=>$chartDataProvider));
}

Examples on how to use it are at the bottom of this page: http://yiiwheels.2amigos.us/site/charts#visualizationchart

Monday, October 28, 2013

Wednesday, October 23, 2013

CSqlDataProvider Using Special Data Attribute - Yii

Just posted this on the Yii forum after I found out that using the special data attribute in a column requires a syntax like 'value'=>'$data["issueCount"]' when you're using CSqlDataProvider:
http://www.yiiframework.com/forum/index.php/topic/48219-special-data-attribute-syntax-in-cactivedataprovider-vs-csqldataprovider/


Thursday, October 17, 2013

Enabling SSL On Apache


This is a quick overview of the process of adding an SSL certificate to apache (for next time...):
  1. Generate your private key and CSR with:
    openssl req -new -newkey rsa:2048 -nodes -keyout yourdomain.key -out yourdomain.csr
  2. Request your certificate
  3. Save requested certificate onto server in a .crt file
  4. Download the intermediary/root cert from http://www.symantec.com/page.jsp?id=roots
  5. Make your site file in /etc/apache2/sites-enabled/ look like this:
<VirtualHost *:443>


        SSLEngine On
         SSLCertificateFile /home/youruser/yourdomain.crt
         SSLCertificateKeyFile /home/youruser/yourdomain.key
         SSLCACertificateFile /var/www/verisign.crt

        ServerName www.yourdomain.com

        DocumentRoot /var/www/yourdomain


An explanation of each of those certificates:
SSLCertificateFile - This is the certificate you received after your request.
SSLCertificateKeyFile - This is the private key you generated in step 1.
SSLCACertificateFile - This is the intermediary cert you downloaded from verisign.

Wednesday, October 16, 2013

Friday, October 11, 2013

Yii quickdlgs Without UrlManager Enabled

EQuickDlgs::iframeButton(
array(
'controllerRoute' => 'controller/create',
'dialogTitle' => 'Create New Record',
'dialogWidth' => 800,
'dialogHeight' => 600,
'openButtonText' => 'Add Record',
'closeButtonText' => 'Close',
//'openButtonHtmlOptions' => array(...),
)
);


With the code above, I was getting the following error:
The system is unable to find the requested action "create?qdsClass=EFrameJuiDlg".

I had to change line 79 in EFrameJuiDlg.php inside the quickdlgs extension from:
            $url .= '?' . http_build_query($this->urlParams);
to:
            $url .= '&' . http_build_query($this->urlParams);

Tuesday, October 8, 2013

htmlspecialchars() expects parameter 1 - Yii (echmultiselect)

htmlspecialchars() expects parameter 1 to be string, array given C:\xampp\htdocs\yii\framework\web\helpers\CHtml.php(98) 
The error only occurred when trying to apply the echmultiselect filter to the filter above the gridview.

Here's what I did to fix:
1. Went to the Yii framework folder and found the following file: yii\framework\web\helpers\CHtml.php

2. Modifed line 98 from "return htmlspecialchars($text,ENT_QUOTES,Yii::app()->charset);" to:
"return htmlspecialchars(print_r($text, true),ENT_QUOTES,Yii::app()->charset);"

Then you need to implement the echmultiselect extension in the view (my example shows adding it for site_status):

3. Added this php code to the view: $data= CHtml::listData(Nvdaily::model()->findAll(), 'blahblahblah', 'blahblahblah');
(but it should probably be in the model)

4. Made my 'columns' array look like this:
'columns'=>array(
'id',
'blah',
'blahblah',
array (
            'name'=>'blahblahblah',
            'filter'=> $this->widget('ext.EchMultiselect.EchMultiselect',
array(
                'model' => $model,
                'dropDownAttribute' => 'blahblahblah',
                'data' => $data,
                'options' => array('buttonWidth' => 80, 'ajaxRefresh' => true),
            ),
            true // capture output; needed so the widget displays inside the grid
),
),
array(
'class'=>'bootstrap.widgets.TbButtonColumn',
),
),

Sunday, October 6, 2013

SQL Formatter

I had no idea this existed until now: http://www.dpriver.com/pp/sqlformat.htm

It makes your SQL queries more readable.

I learned about it from this thread: http://www.reddit.com/r/PHP/comments/1n8kgz/how_do_you_write_readable_sql_queries/

Error Handling In mysqldb - Python

I've had issues with queries failing and leaving connections open (enough to stall a server...). I know python's oursql library supports using the WITH keyword, and I think it will close the connection when there is an unexpected error. However, I'm not sure if I'm ready to move to a different library for MySQL (it's working well).

Here's what I'm currently doing to close the cursor and connection, then re-raise the error:

import MySQLdb

conn = MySQLdb.connect(user="username", passwd="secret", db="database", charset='utf8')
cur = conn.cursor()

try:
cur.execute("INSERT INTO testTable (userid) VALUES(%s);" % id)
conn.commit()
except:
cur.close()
conn.close()
raise
finally:
print "Insert Successful"

Friday, October 4, 2013

haufe.sharepoint Python Library - URLs With %20

I changed line 25 of the haufe.sharepoint library to fix an issue I was having with URLs which had %20 (the url encoded space character):

New Code:
location = urllib.quote(self.location(), safe=":/")

Old Code:
location = self.location()

Just try using a URL with %20 with haufe.sharepoint to see what I'm talking about.

Thursday, October 3, 2013

urllib2.URLError Python SUDS library

To figure this out, you're going to need logging. Turn on logging with the following:


import logging logging.basicConfig(level=logging.INFO) logging.getLogger('suds.client').setLevel(logging.DEBUG) logging.getLogger('suds.transport').setLevel(logging.DEBUG) logging.getLogger('suds.xsd.schema').setLevel(logging.DEBUG) logging.getLogger('suds.wsdl').setLevel(logging.DEBUG)

pip 1.3 Not Working Behind Proxy

http://pythontesting.net/python/pip/

Like this article says, it's fixed in the dev version of pip.

Bootstrap Starter Templates

http://startbootstrap.com/all-templates

Wednesday, October 2, 2013

Tuesday, October 1, 2013

MySQL Not Starting On Reboot

http://stackoverflow.com/questions/9859381/how-make-mysql-start-automatically-linux-cli-only

I was able to to the following, based on the post above:

  1. sudo apt-get install sysv-rc-conf
  2. sudo sysv-rc-conf
  3. mark the 6 column for mysqld or mysql.server (6 = reboot)

Note: I tried sudo update-rc.d mysql.server defaults and it didn't work. It gave me the following error: System start/stop links for /etc/init.d/mysql.server already exist.

Tuesday, September 24, 2013

Fira Font

https://github.com/mozilla/Fira

Mozilla's new Fira font looks great. Looking forward to use it on some future projects.

Thursday, September 19, 2013

MySQL IF Statement Affect On Speed

if(`table`.`start`='0000-00-00','',`table`.`start`)

That's the part of my query that was increasing the execution time by 10x. 

I changed it to just `table`.`start` (without the IF statement) and the query was 10x faster.

Tuesday, September 17, 2013

Phonegap Start (for Phonegap Build)

"A Hello World application to get started with PhoneGap Build."

Twilio PHP Library Using A Proxy

https://github.com/twilio/twilio-php/issues/144

I found a spot where I can add a proxy to the twilio PHP library.

Go to TinyHttp.php and add the highlighted part (using your own URL of course):
$opts[CURLOPT_PROXY] = 'http://xxx.xxx.xxx.xxx:8080/';
try {
      if ($curl = curl_init()) {

Failed to connect to socket /var/run/dbus/system_bus_socket

Error: Can't find out if NetworkManager is running: Failed to connect to socket /var/run/dbus/system_bus_socket: No such file or directory.
The following fixed the problem:
apt-get install dbus
(if you already have dbus installed: sudo service dbus start)
/etc/init.d/network-manager start


What caused the error?:
/etc/init.d/network restart

Monday, September 16, 2013

Could not initialize NMClient

** (process:17986): WARNING **: error: could not connect to NetworkManager


Fix: Try running with sudo.

For example: sudo nm-tool | grep DNS

Sunday, September 8, 2013

Check If Script Is already Running - Python

http://pythonhosted.org/tendo/


import tendo

# If is there another instance already running:
# display the message “Another instance is already running, quitting.”, and return -1 error code.
me = SingleInstance()

Tuesday, September 3, 2013

Fighting WinSCP Time-Outs

http://www.lampdocs.com/blog/2008/10/winscp-how-to-prevent-timeouts/

That's a guide to making WinSCP send a dummy command every 30 seconds to keep your connection alive. It's way better than constantly having to type in your password.

Crontab Mistake

I wanted to run a script every 20 minutes, so I put this into my crontab:
20 * * * * sh script.sh

That's wrong. That only runs it once every hour 20 minutes into the hour. For example, "20,40 * * * * sh bash.sh" would run it twice - 20 and 40 minutes into the hour.

To run the script every 20 minutes like I was expecting:
*/20 * * * * sh script.sh

Monday, September 2, 2013

Include yiiGridView Javascript

http://chevronscode.com/yii-include-preload-yiigridview-javascript/

I ended up with the following code at the top of the page (since I'm not using a layout):

Yii::app()->clientScript->registerCoreScript('jquery');
$assetsScriptUrl = Yii::app()->getAssetManager()->publish(Yii::getPathOfAlias('zii.widgets.assets'));
Yii::app()->getClientScript()->registerScriptFile($assetsScriptUrl .'/gridview/jquery.yiigridview.js');

Monday, August 19, 2013

PHP Best Practices

https://phpbestpractices.org/

Things I learned:

  • It's easy to install PHP-APC for quick opcode caching, and it apparently serves the same purpose as memcached for a single server.
  • Memcache and Memcached are two different libraries.
  • There's a different (a small one) in speed between single and double quotes.
  • Use phpass to store passwords.

Friday, August 16, 2013

Set Up Wordpress For FTP

If it's asking you for FTP login information when you try to update wordpress or a plugin, you don't need to do that! Chances are you don't have permissions correctly configured on that directory. Make sure apache owns the directory. On ubuntu, this will probably work (depending on which user owns apache):

sudo chown -R www-data:www-data /var/www

Wednesday, August 14, 2013

Add Multiple Unique Indexes - MySQL

alter table users add unique index(id, name, phone);

Bootstrap Span Is Overlapping

Try setting a static width on the span. This ensures responsive knows when to put it on another line. It solved my issues with the spans overlapping.

example: add style="width: 520px" to your div with class="span6"


mysql-client 5.6 or phpmyadmin for mysql 5.6

Mysql-client 5.6 doesn't seem to exist, and you don't need it. Phpmyadmin installs mysql-client 5.5 automatically, and that works with mysql server 5.6. If you're having issues, you probably need to run "sudo dpkg-reconfigure phpmyadmin".

Turn Off MySQL Strict Mode

http://nickbartlett.com/wordpress/how-to-turn-off-mysql-strict-mode/

SET @@global.sql_mode= ”; will set it temporarily. (to see if it will fix your problem)

To turn it off permanently, add this setting to your my.cnf (probably in /etc/mysql/my.cnf if you're using ubuntu): 
[mysqld]
sql-mode =


If you're having issues getting this setting to work in your my.cnf, look for another my.cnf in /opt/mysql/server-5.6/my.cnf or elsewhere on your system using the "find / -name 'my.cnf'" command.

Friday, August 9, 2013

Wednesday, August 7, 2013

pymssql SELECT Always Returns None - Python

apt-get remove python-pymssql

The version from apt-get has this error. Just use easy_install to install pymssql and select statements will work.

error: Setup script exited with error: command 'x86_64-linux-gnu-gcc' failed with exit status 1

sudo apt-get install python-dev

Also try this:
sudo apt-get install libxslt1-dev libxslt1.1 libxml2-dev libxml2 libssl-dev

Sunday, July 28, 2013

WHMCS Hook - Trigger E-mail On New User Sign-Up

This script needs to go into your WHMCS hooks folder (root/includes/hooks/):

<?php

 function send_invitiation_email($vars) {

     $command = "sendemail";
$adminuser = "admin"; // Your admin username
$values["messagename"] = "Google Groups Invitation"; // exact name of e-mail template
$values["id"] =  $vars['userid'];

$results = localAPI($command,$values,$adminuser);

 }

 add_hook("ClientAdd",1,"send_invitiation_email");

 ?>

Wednesday, July 24, 2013

Bootstrap Form Builder

http://minikomi.github.io/Bootstrap-Form-Builder/

This looks great for non-technical users who want a form built. It's a great response to "Hey, make me a checklist!"...

"You make the checklist the way you want it using this site, then I'll put it on the web."


Friday, July 19, 2013

UnicodeEncodeError: 'ascii' codec can't encode character u'\ufffd' in position 12: ordinal not in range(128)

The error in the title will occur on pre-0.12.0 versions of python's Requests library. It seems to be fixed on later versions and maybe even earlier.

Here's an example of how you save a zip file from behind a corporate proxy with python's Requests library:


That's it! Just use the write function with the content of the returned request.

requests.exceptions.SSLError: [Errno 1] _ssl.c:504: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

This happens with the Requests library in python. All you need to do is set verify=false.

For example:
cookieRequest = s.post(url, data=json.dumps(payload).strip('"'), allow_redirects=False, headers=headers, verify=False)

src/pycurl.c:42:20: fatal error: Python.h: No such file or directory

The following helped to resolve this issue: sudo apt-get install python-dev

Wednesday, July 17, 2013

Writing To File - UnicodeEncodeError: 'ascii' codec can't encode characters

I was getting a lot of errors when I was trying to download a file with the python requests library. The errors looked like the following:
UnicodeEncodeError: 'ascii' codec can't encode characters in position 2-6: ordinal not in range(128)

This code ended up fixing it:

Monday, July 15, 2013

Prevent URL Encoding - Python Requests Library


Use json.dumps in the data parameter.

for example:
r = s.post(url, data=json.dumps(payload), allow_redirects=False, cookies=cookieRequest.cookies)

Tuesday, July 9, 2013

Tunnel Traffic Through Webserver Using Your Browser

Use the following command in Cygwin (using your IP and Username, of course): 
ssh yourUsername@198.168.xxx.xxx -D 2280 -i your/certificate

Set the following settings in Firefox (connect settings, under the advanced tab):


Dream Factory

https://www.dreamfactory.com/

It's suspiciously free. It's a ready to go back-end that can be accessed with APIs.

Tuesday, July 2, 2013

Easyphp Change Directory To Github

1. Right click on the easyphp icon --> configuration --> apache (this should open the httpd.conf in your easyphp apache directory)

2. Find the section labelled DocumentRootDirectory and overwrite with this:

# DocumentRootDirectory
<Directory "C:/Users/your_username/Documents/GitHub/your_project/">
    #
    # Possible values for the Options directive are "None", "All",
    # or any combination of:
    #   Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
    #
    # Note that "MultiViews" must be named *explicitly* --- "Options All"
    # doesn't give it to you.
    #
    # The Options directive is both complicated and important.  Please see
    # http://httpd.apache.org/docs/2.4/mod/core.html#options
    # for more information.
    #
    Options Indexes FollowSymLinks Includes ExecCGI

    #
    # AllowOverride controls what directives may be placed in .htaccess files.
    # It can be "All", "None", or any combination of the keywords:
    #   Options FileInfo AuthConfig Limit
    #
    AllowOverride All

    #
    # Controls who can get stuff from this server.
    #
    Require all granted

</Directory>

Setting Up Github Windows Client Behind a Proxy

1. Navigate to your git.exe directory (C:\Users\your_username\AppData\Local\GitHub\PortableGit~\bin)

2. git config --global http.proxy http://username:password@host:port/

3. git config --system http.sslcainfo /bin/curl-ca-bundle.crt

4. Open the github client (it should work now)

Saturday, June 29, 2013

move_uploaded_file To Current Path - PHP

$uploadfile = './' . basename($_FILES['file']['name']);

if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)) {
echo "File was successfully uploaded.\n";
} else {
echo "There was an issue uploading the file.\n";
}

Friday, June 28, 2013

View In Use and Will Not DROP - MySQL

I had several views in my MySQL database that were showing "In Use" and phpmyadmin would not let me drop them through the interface.

The solution:
Open the MySQL in terminal and "DROP VIEW yourView;"

Include Array From File - PHP

file.php
<?php
return array('item1','item2');
?>

Your php code:

<?php
$thisVariable = include('file.php');
print_r($thisVariable); //prints the array
?>

Sunday, June 16, 2013

Don't Use Nested IFNULL, Use COALESCE - MySQL

If you're looking for how to do a nested IFNULL, you probably need to be looking at how to use COALESCE instead. It returns the first non-null item in a list.

Example:
SELECT COALESCE(NULL,1);

Returns 1

IFNULL - MySQL

IFNULL(`field1`, `field2`)

That returns field1 if it's not null. However, it will return field2 if it is null.

Notes On JOIN - MySQL


  • If your INNER join is returning too few values and duplicates, you're probably using the wrong kind of join. Try a LEFT join.
  • INNER JOIN is the same as JOIN
  • http://i.stack.imgur.com/GbJ7N.png (diagram explaining joins)
  • LEFT JOIN is used - this will return ALL rows from Table1, regardless of whether or not there is a matching row in Table2. 

Indexes Help... A Lot

I just brought 4 queries from 15 seconds to less than 1 second by adding indexes to the columns in the ON() portion on the join.

Indexes help... A lot.

Saturday, June 15, 2013

Yii-Booster Incorrect Width

Set public $responsiveCss = false; to public $responsiveCss = true;

Thursday, June 13, 2013

group_concat - MySQL

http://mahmudahsan.wordpress.com/2008/08/27/mysql-the-group_concat-function/

This seems like it will be super useful.

If you're using "group by" and you still want to get data out of the grouped rows, then you can use this to combine multiple rows into a single row.

Wednesday, June 12, 2013

Looping Through Associative Array - PHP

http://stackoverflow.com/questions/1951690/php-how-to-loop-through-a-associative-array-and-get-the-key-name

This was totally not very intuitive. I was expecting something like this:

foreach($array as $sub) {
echo(key($sub));
}

Instead, it's this:

foreach ($decodedOutput as $key => $value) {
echo $key;
}

Friday, May 31, 2013

Sunday, May 19, 2013

Easiest Way To Consume .Net Web Services - Python

http://www.jansipke.nl/python-soap-client-with-suds/

That article was very helpful for learning to use Python's SUDS library for consuming soap web services.

Here's an example of my simple client:


from suds.client import Client
client = Client("http://xxx.xxx.xxx.xxx/API/Info.asmx?WSDL")
client.service.getInfo("05/12/2013","05/12/2013")

"05/12/2013" and "05/12/2013" are both parameters

Saturday, May 11, 2013

New Vocabulary Word

CRUD
-Create
-Read
-Update
-Delete

An example of a CRUD application would be something that tracks orders in a database. All 4 actions are going to be necessary to track those orders. CRUD: The basic database operations.

Tuesday, May 7, 2013

Dynamically Import Data From Other Workbooks - Google Spreadsheet

I made a google spreadsheet which pulls data from two other workbooks using "importRange" and QUERY function. You can use either one if you just want to pull a few columns from another spreadsheet. QUERY provides more flexibility by allowing you to use a SQL statement. Here is an example of a query which pulls 2 columns from another workbook and filters out the blank rows in column 41:

=QUERY(importRange("yourSpreadsheetKeyHere", "Donations!A3:BB200000"), "select Col41, Col2 WHERE Col41!='' ", 1)

One of the biggest pains during the entire process was google spreadsheet's vlookup. I learned the vlookup function only searches for a value in the first column in the Array. It's also helpful if you format the results of your vlookup as "Plain Text" under the numbers format drop-down. Of course, something formatted as a number won't match something formatted as plain text.

You could use this technique if you have a list of customer id's with names, and a separate spreadsheet with more customer information. With this, you could combine that information.

Javascript Excel Parser

http://niggler.github.io/js-xlsx/

That's an impressive project that allows parsing excel files in the browser.

Saturday, April 27, 2013

Green Mountain Energy's B2B Site

Green Mountain Energy has the worst B2B portal I've seen in my life. The worst parts:

  • It only works in IE (barely, and switching between browser versions in the F12 menu doesn't help)
  • The page only takes up ~30% of the browser window (see the picture)
  • Nothing is functional, I can't change my automated billing agreement because there's no submit button.
  • If you have more than one address on your account, just give up.

Update: They sent a letter saying they made a new business portal site. www.businessportal.greenmountain.com My first visit gives me an "Our site is currently down as we upgrade our systems." error message.


Friday, April 26, 2013

Don't Use == null - Python

http://stackoverflow.com/questions/3289601/null-object-in-python

It says not to use == to check for "none-ness". It's better to use:

if variable is none:
    <your code>

Why? "And the reason for choosing egg is None over egg == None: The latter can be overloaded, and is likely to break when comparing valid object with None (depends on how it's implemented, but you don't expect everyone to take comparisions with None into account, do you?), while is always works the same."

Tuesday, April 23, 2013

Something I Need To Drill Into My Brain - Python

The operation of the slicing operator:
>>> word[:2]    # The first two characters
'He'
>>> word[2:]    # Everything except the first two characters
'lpA'

Monday, April 22, 2013

Prezi Video With No Audio

I converted a wmv video to a few different formats (mp4 and flv) and still couldn't get the audio to play in Prezi. However, videos with the following codec settings will work:

Solution: Open your video with Handbrake and convert it to H264 with AAC as the selected audio codec and it will play just fine.



Tuesday, April 16, 2013

Start Ser2Sock.c On Boot


Make a shell script saying the following:
./ser2sock -b 115200 -c -w 5000 -p 10000 -s /dev/ttyUSB0 -d -g 3

Tuesday, April 9, 2013

Easiest To Set Up FTP Server

http://askubuntu.com/questions/1722/basic-ubuntu-ftp-server

"I'm going to recommend PureFTPD because it's been the simplest and easiest to use in my opinion. You'll need to install it first: sudo apt-get install pure-ftpd once it's installed it'll start itself up."

Monday, April 8, 2013

Useful Bootstrap Links

http://bootstraphero.com/the-big-badass-list-of-twitter-bootstrap-resources

Also, an user named Billy Cravens on Meetup.com left a ton of good bootstrap links (bootsnip looks especially awesome) in this post: http://www.meetup.com/HoustonCFUG/events/79862792/
Twitter Bootstrap:
href="http://twitter.github.com/boots...
Bootswatch: (free Bootstrap themes)
http://www.bootswatch.com
Wrap Bootstrap (premium Bootstrap themes)
http://www.wrapbootstrap.com
Common Bootstrap Snippets
http://www.bootsnipp.com
Bootstrap WYSIWYG editor plugin
http://jhollingworth.github.com...
Integrating Bootstrap with jQueryValidate
http://alittlecode.com/jquery-f...
Nice data grids:
http://www.datatables.net
Integrate Bootstrap with Data Tables:
http://datatables.net/blog/Twit...

HTML5 In < IE9

https://code.google.com/p/html5shiv/

I saw this javascript library in the code for the Mozilla Support page (really well done). It looks like it adds HTML5 functionality to older versions of IE. Looks like it should be really useful in the future.

Tuesday, April 2, 2013

PHP - Verify File Is Uploaded And Zip


if($_FILES["zip_file"]["name"]) {
     $filename = $_FILES["zip_file"]["name"];


     $name = explode(".", $filename);


     $continue = strtolower(end($name)) == 'zip' ? true : false;
     if(!$continue) {
           $message = "The file you are trying to upload is not a .zip file. Please try again.";
     } else {
          $message = "File Is .zip";
     }
}

Friday, March 29, 2013

PHP - Loop Through Excel Document and Print Cells


require_once 'excel_reader2.php';

foreach($reader->sheets as $k=>$data)
 {
    echo "\n\n ".$reader->boundsheets[$k]."\n\n";

    foreach($data['cells'] as $row)
    {
        foreach($row as $cell)
        {
            echo "$cell\t";
        }
        echo "\n";
    }
 }

Saturday, March 16, 2013

Head Tracking In The Browser

http://learningthreejs.com/blog/2013/03/12/move-a-cube-with-your-head/

Had no idea this was even possible, but that's an example of head tracking in the browser done with WEBRTC.

Demo: http://jeromeetienne.github.com/tquery/plugins/headtrackr/examples/demo.html

Check If Time Is Between - Python

http://stackoverflow.com/questions/1907196/how-do-i-check-if-its-monday-to-friday-and-the-time-is-between-10-am-to-3-pm

From an user named miku:

>>> import datetime
>>> d = datetime.datetime.now() 
# => datetime.datetime(2009, 12, 15, 13, 50, 35, 833175)

# check if weekday is 1..5
>>> d.isoweekday in range(1, 6)
True

# check if hour is 10..15
>>> d.hour in range(10, 15)
True

# check if minute is 30
>>> d.minute==30
False

Friday, March 15, 2013

Prevent Character Escaping - Python

http://stackoverflow.com/questions/2042342/network-path-and-variables-in-python

If you want to use network paths without adding extra slashes, you can use python's raw string function.

Here's an example of something you want to make a raw string:

source_path = r"\\mynetworkshare"

Tuesday, March 5, 2013

Check If Workbook Is Open By Name - VBA

This code from StackOverflow helped me find whether a workbook was open with its name. Here's the link to the thread: Link

Function BookOpen(strBookName As String) As Boolean
    Dim oBk As Workbook
    On Error Resume Next
    Set oBk = Workbooks(strBookName)
    On Error GoTo 0
    If oBk Is Nothing Then
        BookOpen = False
    Else
        BookOpen = True
    End If
End Function

Sub testbook()
    Dim strBookName As String
    strBookName = "myWork.xls"
    If BookOpen(strBookName) Then
        MsgBox strBookName & " is open", vbOKOnly + vbInformation
    Else
        MsgBox strBookName & " is NOT open", vbOKOnly + vbExclamation
    End If
End Sub

Sunday, March 3, 2013

"The link you have used to enter the PayPal system is invalid. Please review the link and try again."

Using an incorrect e-mail address in the hidden "business" field in your HTML form can cause this issue.

Example of the hidden field with the problem:
<input type="hidden" name="business" value="dave@davesgarage.com">

Friday, March 1, 2013

Overdue Member Calculator

https://github.com/pawl/OverdueMemberCalculator

This should help ease the pain of dealing with suspended paypal recurring payment agreements.

The page accepts variables from the URL, then generates a paypal payment button based on the person's last payment date.

HTML Skeleton / Boilerplate

Here's a good HTML skeleton/boilerplate tool: http://www.htmlshell.com/

Thursday, February 28, 2013

WebForms.js or WebUIValidation.js CDN

In the console, it was giving me two errors saying it could not GET these two files from the CDN:

To fix it, you need to delete the <script></script> references for both of the files above and make a single reference to:
<script src="http://ajax.aspnetcdn.com/ajax/4.5/6/WebFormsBundle.js" type="text/javascript"></script>

Wednesday, February 27, 2013

Raspberry Pi Text To Speech IRC Service

These are my notes for installing Eastein's announce. It's a IRC bot that will receive a message and do text to speech on the message: https://github.com/eastein/announce

Installation:

  1. Download announce and extract it to it's own folder.
  2. apt-get install python-irclib
  3. apt-get install python-pip
  4. sudo apt-get install python-dev
  5. apt-get install festival festlex-cmu festlex-poslex festlex-oald libestools1.2 unzip
  6. apt-get install speech-tools
  7. pip install pyzmq --install-option="--zmq=bundled"
    or (if you have easy_install installed):
    easy_install pyzmq
  8. download mediorc and move mediorc into directory
  9. easy_install dnspython
  10. apt-get install mplayer
  11. apt-get install sox
  12. Fix permissions:
    chmod 777 saypitchprase
    chmod 777 pitchphrase2wav

Running The Program:

Run process in background by starting a screen (first navigate to the Announce folder):
  1. (start a new screen)
  2. python announced "tcp://*:4900"
  3. (detach from screen)
  4. (start a new screen)
  5. python announcebot "chat.freenode.net" "voicebot" "#yourircchannel" "tcp://0:4901"
  6. (detack from screen)
Starting the program using mp3 files in the JSON file (as always, start in the folder which has Announce):

  1. wget http://fake.com/fake/eye_tiger.mp3 (use a real URL with an mp3 file)
  2. nano default.json
  3. enter into the json file: [ ["eye of the tiger", "eye_tiger.mp3"] ]
  4. ctrl+x and save
  5. (start a new screen)
  6. python announced "tcp://0:4900" default.json
  7. (detach from screen)
  8. (start a new screen)
  9. python announcebot "chat.freenode.net" "voicebot" "#yourircchannel" "tcp://0:4900"
  10. (detach from screen)
  11. now "!say eye of the tiger" in the IRC channel will trigger the mp3

Troubleshooting:


Ensure your Raspberry Pi audio is working: http://jeffskinnerbox.wordpress.com/2012/11/15/getting-audio-out-working-on-the-raspberry-pi/

Testing Festival (create a text file named mytext.txt with some words first):
echo "This is a test." | festival --tts
echo "this is a test" > mytext.txt
text2wave -o myaudio.wav mytext.txt
aplay myaudio.wav

adjust the volume:
http://blog.scphillips.com/2013/01/sound-configuration-on-raspberry-pi-with-alsa/
or use amixer?

Find An Image Font

This page will tell you what font an image is using: http://www.myfonts.com/WhatTheFont/

I wish this feature was included in GIMP or Photoshop.

Friday, February 22, 2013

Regex Debugger

http://www.debuggex.com/?re=&str=

Don't want to lose this link, it's going to make regex related programming a lot easier.

Tuesday, February 19, 2013

Tableizer

Freaking brilliant tool that converts spreadsheet format things to HTML: http://tableizer.journalistopia.com/tableizer.php

PhoneGap Build - cordova-2.4.0.js

If you're using Phonegap Build, you don't need to include cordova-2.4.0.js or any other specific version of cordova/phonegap. Just use phonegap.js, but you don't actually need to include phonegap.js in the file you upload to Phonegap Build.

Quote from the Phonegap Build site:
"Once you've included the necessary assets, remove the phonegap.js (cordova.js) as Build will automatically inject it during compile time."

Tuesday, February 5, 2013

Sharepoint Lists Crashing

If your sharepoint lists crash IE as soon as they open, try disabling the following IE addons:
Sharepoint spreadsheet Launcher
Sharepoint export database~

Open File With Excel Macro


This macro will ask the user to input an excel file, then open that excel file:

Sub RunMacro()
   
Dim vaFiles As Variant
Dim i As Long

vaFiles = Application.GetOpenFilename _
         (FileFilter:="Excel Filer (*.xls),*.xls", _
         Title:="Open File(s)", MultiSelect:=False)

If Not IsArray(vaFiles) Then Exit Sub

With Application
    .ScreenUpdating = False
   
    For i = 1 To UBound(vaFiles)
        Workbooks.Open vaFiles(i)
    Next i
   
    .ScreenUpdating = True
End With

End Sub

Friday, February 1, 2013

Java - Swing's Nimbus Look & Feel

Since Java SE 6 Update 10, Java has had an updated interface called Nimbus. Comparison pictures are below. 

All I needed to do to use it was add this import to the top of the .java file with my main() method:
import javax.swing.UIManager.*;

public static void main(String[] args) {
try {
    for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
        if ("Nimbus".equals(info.getName())) {
            UIManager.setLookAndFeel(info.getClassName());
            break;
        }
    }
} catch (Exception e) {
    // If Nimbus is not available, fall back to cross-platform
    try {
        UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
    } catch (Exception ex) {
        // not worth my time
    }
}
new Controller();
}


Default

Nimbus
Note: This blog post says it is slightly slower than the default: http://www.pushing-pixels.org/2008/06/17/lightbeam-measuring-performance-of-swing-look-and-feels.html