EastBay CodeHaus
Notes on Programming and Software Development. And now Arduino and Electronics!
Sunday, February 5, 2012
blog.bjrn.se: Let’s build an MP3-decoder!
blog.bjrn.se: Let’s build an MP3-decoder!: Even though MP3 is probably the single most well known file format and codec on Earth, it’s not very well understood by most programmers – for many encoders/decoders is in the class of software “other people” write, like standard libraries or operating system kernels. This article will attempt to demystify the decoder, with short top-down primers on signal processing and information theory when necessary. Additionally, a small but not full-featured decoder will be written (in Haskell), suited to play around with.
Saturday, February 4, 2012
DS1307 Library -- Real Time Clock
Electronics - Henning Karlsen: Library: DS1307
The DS1307 serial real-time clock (RTC) is a low-power, full binary-coded decimal (BCD) clock/calendar plus 56 bytes of NV SRAM. Address and data are transferred serially through an I²C, bidirectional bus. The clock/calendar provides seconds, minutes, hours, day, date, month, and year information. The end of the month date is automatically adjusted for months with fewer than 31 days, including corrections for leap year. The clock operates in either the 24-hour or 12-hour format with AM/PM indicator, but the library only supports the 24-hour mode. The DS1307 has a built-in power-sense circuit that detects power failures and automatically switches to the backup supply. Timekeeping operation continues while the part operates from the backup supply.
I2C RTC DS1307 AT24C32 Real Time Clock Module
Vendor Description
vendor: geiliable-store
The DS1307 can be interface to using the Wire library or by Henning Karlson's custom DS1307 library. Use Henning's library if you don't need any other I2C devices and want to save the code space of the Wire library.
"This is the DS1307 Real Time Clock developed by one of our designer waiman. The module comes fully assembled and pre-programmed with the current time (ok, so it's our current time - MST). The included Lithium coin cell battery (CR1225 41mAh) will run the module for a minimum of 9 years (17 years typical) without external 5V power. The DS1307 is accessed via the I2C protocol."
- Two wire I2C interface
- Hour : Minutes : Seconds AM/PM
- Day Month, Date - Year
- Size: 28x25x10mm
- Leap year compensation
- Accurate calendar up to year 2100
- DS1307 based RTC with LIR2032 battery (Battery include)
- 1Hz output pin
- 56 Bytes of Non-volatile memory available to user
vendor: geiliable-store
The DS1307 can be interface to using the Wire library or by Henning Karlson's custom DS1307 library. Use Henning's library if you don't need any other I2C devices and want to save the code space of the Wire library.
4 Channel 5V Relay Module
Vendor Description:
This is a 5V 4-Channel Relay module, It can be controlled directly by a wide range of microcontrollers.
vendor: ekitszone
This is a 5V 4-Channel Relay module, It can be controlled directly by a wide range of microcontrollers.
- Each 5V Relay need 20mA driving current
- 5V TTL control input
- Indication LED for each Relay's Status
vendor: ekitszone
LCD Keypad Module
Vendor's description:
- This is a LCD Keypad module for ARDUINO & FREEDUINO board.
- It directly plugs into the ARDUINO or FREEDUINO board, no seldering required.
- The LCD is a 16*2 HD44780 compatible LCD with WHITE characters & BLUE backlight.
- It uses ARDUINO LCD4Bit library with few modifications.
- It only uses AD0 on ARDUINO or FREEDUINO board for the 5 push-buttons.
vendor: ekitszone
Monday, August 30, 2010
Oracle Packages that include Java
Here's a cheat sheet for including Java stored procedures in packages.
Write a class:
public class OracleFoo {
public static void myproc(int port, String s) throws Exception {
}
}
Compile and Load:
javac OracleFoo.java
loadjava -u scott/tiger OracleFoo.class
Declare a package:
create or replace package oraclefoo
as
procedure myproc(port number, s varchar2)
as language java name 'OracleFoo.myproc(int, java.lang.String)';
end;
Call:
begin
oracletbslow.myproc(7728,'[1,"a","b1",{}]');
oracletbslow.myproc(7727,'[1,"a","b2",{}]');
end;
Permissions:
need to set these, double-check notes...
public class OracleFoo {
public static void myproc(int port, String s) throws Exception {
}
}
Compile and Load:
javac OracleFoo.java
loadjava -u scott/tiger OracleFoo.class
Declare a package:
create or replace package oraclefoo
as
procedure myproc(port number, s varchar2)
as language java name 'OracleFoo.myproc(int, java.lang.String)';
end;
Call:
begin
oracletbslow.myproc(7728,'[1,"a","b1",{}]');
oracletbslow.myproc(7727,'[1,"a","b2",{}]');
end;
Permissions:
need to set these, double-check notes...
Saturday, August 28, 2010
hello world for erasme pl/sql-json package
Here's a hello world program for the erasme pl/sql json package.
I need to figure out how to do it outside the context of a dictionary.
declare
my_obj json.JSONStructObj;
my_tab json.JSONArray;
begin
-- {}
json.newJSONObj(my_obj);
json.closeJSONObj(my_obj);
dbms_output.put_line(json.JSON2String(my_obj));
-- {'a':'b'}
json.newJSONObj(my_obj);
my_obj := json.addAttr(my_obj, 'x', 'hello');
my_obj := json.addAttr(my_obj, 'y', 99);
json.closeJSONObj(my_obj);
dbms_output.put_line(json.JSON2String(my_obj));
end;
I need to figure out how to do it outside the context of a dictionary.
declare
my_obj json.JSONStructObj;
my_tab json.JSONArray;
begin
-- {}
json.newJSONObj(my_obj);
json.closeJSONObj(my_obj);
dbms_output.put_line(json.JSON2String(my_obj));
-- {'a':'b'}
json.newJSONObj(my_obj);
my_obj := json.addAttr(my_obj, 'x', 'hello');
my_obj := json.addAttr(my_obj, 'y', 99);
json.closeJSONObj(my_obj);
dbms_output.put_line(json.JSON2String(my_obj));
end;
Wednesday, August 25, 2010
Six Keys to Being Excellent at Anything - Tony Schwartz - The Conversation - Harvard Business Review
Six Keys to Being Excellent at Anything - Tony Schwartz - The Conversation - Harvard Business Review:
- Pursue what you love.
- Do the hardest work first.
- Practice intensely
- Seek expert feedback, in intermittent doses.
- Take regular renewal breaks.
- Ritualize practice.
Edna at Singapore Speedpost, please email me!
Ugh... I've got a shipment of stuff coming via Speedpost from Singapore, and I can't sign up for email shipment notifications because their main page explicitly rejects my email address.
Interestingly, the guilty party (Edna) put in a comment taking the blame for the situation. It seems she's never come across a two-letter login name!
http://www.speedpost.com.sg
function isEmail(Mail) {
Mail=Mail.toLowerCase();
return (Mail.search(/^([a-z]+)([a-z0-9\-\_\.]{1,100})([a-z0-9]+)\@([a-z0-9]+)([a-z0-9\-\.]*)([a-z0-9]+)\.([a-z]{2,6})$/) != -1);
}
function checkEmail() {
var eml = document.onlineform.txtEmail.value;
if (isEmail(eml)) {
document.onlineform.action='speedpost_services_track_check.asp';
document.onlineform.submit();
}
else
{
alert("Invalid email address. Pls re-enter.");
}
}
Saturday, August 22, 2009
Unreality - An Awesome Collection of Star Trek Bloopers |
Unreality - An Awesome Collection of Star Trek Bloopers |: "Call me crazy but there’s something awfully funny about a Vulcan that all of a sudden starts laughing and cursing because he forgot his line. I’m a huge fan of bloopers. Nothing’s better than when you see how “human” someone truly is. And no time is more human than screwing up in the middle of a scene and laughing your ass off."
Friday, August 21, 2009
An AskTom about database APIs
An interesting note by Tom regarding APIs in the database.

API's -- all about API's. The applications don't do table level stuff, the apps don't even really *know* about tables. I have a schema. On top of schema we have an API that does the data stuff. In the application we call this API but have our own application logic as well (only application logic is in the application, data logic is -- well, right where it belongs -- next to the data, waiting for the 'next great programming paradigm to come along') [...] Applications -- a dime a dozen. They come, they go, they have programming paradigm of the week. Data -- priceless. Most of it has been here for a long long long time. Most all of it will be here after we are dead.

Sunday, August 9, 2009
Computer Eyeglass Lenses
Computer Eyeglass Lenses: "Computer No-Line Lenses are an occupational progressive lens, a no-line multifocal that corrects near, intermediate and, to a degree, distance vision. It has a larger intermediate zone than regular progressive lenses, leaving less space for distance. Computer eyeglass lenses are generally not suitable for driving or regular wear."
Saturday, August 8, 2009
What does "flatdown" mean?
It's reference in the OPML spec.
Here's an explanation:
First, flatdown, in UserLand's outliner terminology, is a direction. The complete list of directions is: up, down, left, right, flatup, flatdown and nodirection. They are used as parameters to the op.xxx verbs which take a direction as a parameter. The first four are structured directions. Going up from an outline element takes you to its previous sibling, down takes you to the next sibling. Left takes you to the parent, right takes you to the first child. The flat directions, flatup and flatdown view the outline as a linear sequence, not structured. Imagine the outline displayed on a screen. To go flatup you'd go to the outline element displayed immediately before, to go flatdown you'd go to the outline element displayed immediately after.
Thursday, August 6, 2009
Note to a Software Vendor, regarding Document Managment Integration
Hi ----,
Thanks for getting back so soon. I hope you can look at this issue over your entire product line. Here's the situation as I see it.
Ancient Times:
- I had "my" computer, "my" files, I managed everything myself. It was all about me, Me, ME! If you wanted a file, I would mail it to you or copy it to a network share.
- I have at least two computers, a desktop and a laptop. My files are under revision control and stored in a central repository. I sync files to my local box and work on them. Sometimes I work on the same file on two boxes -- my desktop coz it has a big screen, and my laptop coz I can take it to meetings. If you want a file, I can just tell you where it is on the central server and you can access it at your leisure. And good news for you, I have two copies each of [your product].
- easy to check in / check out in revision control system.
- - making documents into single files
- - adding support for various revision systems
- - adding hooks so revision system plugins can be created
- easy multi-machine usage.
Friday, March 13, 2009
Self-Education Resource List
Self-Education Resource List: "The internet is an invaluable resource to self-educated learners. Below is a list of some of the most helpful sites out there including opencourseware materials, free libraries, learning communities, educational tools, and more."
Thursday, March 12, 2009
Java Stored Procedure in Oracle, Database Interaction
Java Stored Procedure in Oracle, Database Interaction:
"Table of Contents:
# Java Stored Procedure in Oracle, Database Interaction
# A Simple Java Class
# Getting Java Classes into Oracle Database
# How to make Classes available to Oracle
# How to execute the Java Stored Procedures"
Wednesday, March 11, 2009
How to Get Bruce Lee Like Strength Without Ever Going to a Gym | Zen Habits
How to Get Bruce Lee Like Strength Without Ever Going to a Gym | Zen Habits: "Here’s just a few of the ways you can start getting stronger, faster and more toned without ever stepping into a gym:"
Tuesday, March 10, 2009
sql developer filter entry bug
Here's a bug with the filter entry field in sql developer.
1. enter a filter which gets saved. In this case,
owner='joshm'
2. now clear the filter field.
3. type 'o'. "owner='joshm'" pops up as a completion. the typed 'o'
is highlighted.
5. type another character, for example 'x'. the 'o' is erased because
it is highlighted.
6. once in this mode it becomes nearly impossible to type, since
each character erases the previous.
Wednesday, May 30, 2007
Making Fizzy Fruit
Making Fizzy Fruit: "For Fizzy Fruit roll-out in schools, the following
fresh whole and sliced fruit are recommended:
Apples, Fuji, Gala, Pink Lady and Red Delicious
(sliced and treated for browning)
Cantaloupe
Grapes, Red Flame Seedless
Mangoes
Nectarines
Oranges, Mandarin and Navel
Pears, Asian and Bartlett
Pineapple Spears
Plums, Red and Black
Strawberries
Tangerines, Clementine
Watermelon"
Tuesday, May 29, 2007
using dbms_application_info
exec DBMS_APPLICATION_INFO.SET_MODULE( NULL,NULL );
exec DBMS_APPLICATION_INFO.SET_MODULE('my module', 'my action');
exec DBMS_APPLICATION_INFO.SET_ACTION('my action 2');
exec DBMS_APPLICATION_INFO.SET_CLIENT_INFO('my client info');
-- exec DBMS_APPLICATION_INFO.SET_SESSION_LONGOPS(rindex, slno,
-- 'Test Operation', obj, 0, sofar, totalwork, 'Contract', 'Contracts');
select sid,program,module,action,client_info from v$session where username='MH';
Thursday, May 24, 2007
'Star Wars' at 30: Still a geek's paradise
'Star Wars' at 30: Still a geek's paradise: "Friday marks the anniversary of the 1977 movie that made it cool to be a sci-fi dork."
FARK.com: (2823158) LOLPRESIDENT!!!1 Add your own in thread (with voting - link goes to samples)
FARK.com: (2823158) LOLPRESIDENT!!!1 Add your own in thread (with voting - link goes to samples): "LOLPRESIDENT!!!1 Add your own in thread (with voting - link goes to samples)"
Wednesday, May 23, 2007
Marginal Revolution
Marginal Revolution:
"How to debate with one's wife
Even if I can debate with the devil himself, I cannot debate with my wife. She has, namely, only one syllogism, or rather none at all...The consequence of this is that all my skill in debating becomes a luxury item for which there is no demand at all in my domestic life. If I, the experienced dialectician, fairly well exemplify this course of justice, which according to the poet's dictum is so very long, my wife is like the royal Danish chancery, kurz and b�ndig [short and to the point], except that she is very different from that august body in being very lovable.
That is again Kierkegaard, from Prefaces."
Tuesday, May 22, 2007
Oracle/PLSQL: Oracle System Tables
Oracle/PLSQL: Oracle System Tables: "an alphabetical listing of the Oracle system tables that are commonly used."
Desc - Describe an Oracle Table, View, Synonym, package or Function
Desc - Describe an Oracle Table, View, Synonym, package or Function:
"An alternative to the DESC command is selecting directly from the data dictionary -
DESC MY_TABLE
is equivalent to
SELECT
column_name 'Name',
nullable 'Null?',
concat(concat(concat(data_type,'('),data_length),')') 'Type'
FROM user_tab_columns
WHERE table_name='TABLE_NAME_TO_DESCRIBE';"
Tuesday, February 13, 2007
python xml-rpc, supporting 64-bit ints
xml-rpc is nice, but brain-dead in that it doesn't support 64-bit integers. There are a couple of extensions to the xml-rpc standard that suggest a new tag for this. If you're using the python xml-rpc library and wish to have 64-bit int support, you can comment out the two lines below in xmlrpclib.py:
def dump_long(self, value, write):
#if value > MAXINT or value <>
# raise OverflowError, "long int exceeds XML-RPC limits"
write("")
write(str(int(value)))
write("\n")
dispatch[LongType] = dump_long
Wednesday, January 31, 2007
Does p4d care about depot file permissions? No.
Does p4d on linux care about the file permissions in the depot?
Specifically, if the permissions are set from 644 to 755 will p4d still operate properly?
Perforce responds:
Having the executable bit set on depot files won't affect p4d. However make sure the Linux user starting p4d has write permission on depot directories/files.
Saturday, January 13, 2007
Tracing an Oracle session in 10g
Setting permissions:
Turn the trace on and off:GRANT EXECUTE ON SYS.dbms_monitor TO username;
EXECUTE dbms_monitor.session_trace_enable
(session_id=>NULL, serial_num=>NULL, waits=>TRUE, binds=>TRUE);
EXECUTE dbms_monitor.session_trace_disable
(session_id=>NULL, serial_num=>NULL);
Older versions of Oracle:
Look at the results with tkprof. The "aggregate" flag is especially useful.alter session set timed_statistics=true; alter session set max_dump_file_size=unlimited; alter session set tracefile_identifier='Hello'; alter session set events '10046 trace name context forever, level 12';
Wednesday, October 4, 2006
LD_DEBUG: debugging ld.so on linux
David Baraff told me about this awesome way to see what ld.so is doing on linux.
$ LD_DEBUG=help /bin/cat
Valid options for the LD_DEBUG environment variable are:
libs display library search paths
reloc display relocation processing
files display progress for input file
symbols display symbol table processing
bindings display information about symbol binding
versions display version dependencies
all all previous options combined
statistics display relocation statistics
unused determined unused DSOs
help display this help message and exit
To direct the debugging output into a file instead of standard output
a filename can be specified using the LD_DEBUG_OUTPUT environment variable.
Tuesday, June 13, 2006
Wednesday, June 7, 2006
Stopping in a C++ function called via Python
How do i tell totalview to stop at a line number in a particular file?
This is a C++ function in a SO which is being loaded as part of a python import.
Leaf Nunes has the most awesome answer:
I
'm not sure how you tell totalview via totalview, but you can tell the
C++ to stop at a line by adding:
asm("int $3");
This is the only way i've seen to pre-set a breakpoint in C code
referenced by a python binary running under totalview.
Once it's stopped, you should be able to look around all the libraries
the python binary has loaded and set breakpoints as you desire.
Arun Rao:
If you run the python program until it finishes, then you can set the breakpoint because the library will have been loaded, and restart the process.
Introspecting python variables (to print a debug message)
I asked about introspecting python variables. I was looking for something similar to Tcl's upvar command. I received a couple of good responses. I didn't ever end up using them for debugging, but I sure learned a lot more about Python introspection than I knew previously.
Alex Mohr:
We have to remember that an arbitrary number of variables, all with different names, can refer to the same object. For example,Erick Tryzelaar:foo = 'something'bar = fooNow suppose I say, printvars('message', bar). The printvars function will get a reference to the 'something' string, but it doesn't know that the name of the reference I called you with was 'bar' rather than 'foo'. This function will take your argument, and look through globals() and find all the names that refer to that object, and then print those out, but this is almost certainly slow, fragile and useless:def printvars(msg, *args): print msg, ':', for arg in args: matches = [] for name, val in globals().items(): if arg is val: matches.append(name) for match in matches: print match+',', print '=', repr(arg)+';', print ''If I use this as with my hypothetical example above, it produces this output:>>> printvars('message', bar) message : bar, foo, = 'something'
This is doable with scary python black magic:
import sys
def foo(msg, *args):
caller = sys._getframe(1)
print msg, ' '.join(['%s=%s' % (x, caller.f_locals[x]) for x in args])
x = 5
y = 6
foo('hello', 'x', 'y')
hello x=5 y=6
Lars Damerow:
I agree with Erick and Alex here -- you can't get away from passing the variable names in as strings, since Python just considers variable names to be string keys for the local and global scope dictionaries. I also second Erick's opinion that using sys._getframe is not a good idea. It may look redundant, but the simplest and most bulletproof approach is probably something like this:Jim Atkinson:def printvars(msg, *args): print msg, ' '.join(['%s=%s' % (x, v) for (x, v) in args]) >>> x = 1 >>> y = 2 >>> printvars("hello", ("x", x), ("y", y)) hello x=1 y=2We could make that a lot cleaner if Python had macros, but it doesn't. If we knew that all of the desired variables are in the same dictionary (which includes locals() and globals()), we could obviously clean up the calls like this:def printvars(msg, scope, *args): print msg, ' '.join(['%s=%s' % (x, scope[x]) for x in args]) >>> x = 1 >>> y = 2 >>> printvars("hello", locals(), "x", "y") hello x=1 y=2
Although you cannot avoid giving the name as well as the value for the variable. You can use keyword syntax to pass them and avoid having to type quotes around the name.
def printvars(msg, **kw):
print msg,
keys = kw.keys()
keys.sort()
for key in keys:
print "%s=%r", (key, kw[key])
print
x = 1
y = 2
printvars ("hello", x=x, y=y)
hello x=1 y=2
The only downside is that you cannot control the order of the variables, it is always alphabetical.
Wednesday, May 31, 2006
Prevent omnigraffle from writing bundles
Sometimes omnigraffle will rewrite a file into a bundle. It can be configured not to do this:
defaults write com.omnigroup.OmniGraffle PrivateGraffleFlatFile 0 defaults write com.omnigroup.OmniGrafflePro PrivateGraffleFlatFile 0
Thursday, April 27, 2006
Wednesday, March 29, 2006
How to Create a REST Protocol
How to Create a REST Protocol:
"REST is an architectural style that can be used to guide the construction of web services. Recently, there have been attempts to create such services that have met with mixed success. This article outlines a series of steps you can follow in creating your protocol--guidance that will help you get all the benefits that REST has to offer, while avoiding common pitfalls."
Tuesday, February 28, 2006
Python: how to tell if a class variable exists?
I have a debugging dump methodin which I would like to do something like:
if self.foo exists:
print foo
Here are some of the responses I received from my coworkers:
try:
print self.foo
except AttributeError:
print "self.foo doesn't exist."
if self.__dict__.has_key("foo"):
foo = getattr(self, 'foo', None)
if hasattr(self, 'foo'):
# for class variables
if hasattr(self.__class__, 'foo'):
Monday, October 24, 2005
Python: retrieving the oracle error code
Anthony Tuininga gave me this hint on retrieving the Oracle error code from a cx_python program:
try:
cursor.execute("select 1 / 0 from dual")
except cx_Oracle.DatabaseError, e:
print "Exception:", e # this is what you are looking at right now
errorObj, = e.args # this is the actual "error" that cx_Oracle raises
print "ErrorCode:", errorObj.code
print "ErrorMessage:", errorObj.message
Causing Guido van Rossum to ask
This is overly subtle. Why not write
errorObj = e.args[0]
and received the response
No particularly good reason -- it just happens to be a way of indicating that there should be one and only one entry in the list. An exception is raised if there is not whereas args[0] does not raise the exception. Its an open question which is the better code.
Subscribe to:
Posts (Atom)




