Thursday, December 18, 2008

AutoComplete Bug: item has comma won't select (but I have workaround)

Found an AutoComplete bug:

I've just found a bug with AutoComplete plugin. If one of the items in the list retrieved has an embedded comma in the string, the string is not considered 'matched'. This is with options 'multiple' false.

This I discovered because I've implemented the 'afterNoMatch()' method (see an other post to this list). If I select an item from the list that has an embedded comma, it will trigger the afterNoMatch() and consider the item not matched.

This could impact otherse even if they don't have this patch because this means the mustMatch option will not trigger as they think it will.

I haven't found the true cause, but it would seem to have something to do with multiple selections - like it's on by default anyway. So the workaround is to specify another multipleSeparator character. Here, I use backtick:

$("#mcOrgName").setOptions({multipleSeparator: '`' });

where mcOrgName is the jquery name of the field I'm using autocomplete for.

Here's hoping the author does a bugfix, but in the mean time, this workaround should enable full functionality presuming you don't need backticks in the text you're selecting.

Enjoy!

Thursday, December 11, 2008

JQuery AutoComplete: code/diff for new option afterNoMatch

Below please find a mod for adding an option to AutoComplete.

The option is 'afterNoMatch'. It specifies a function to call if the value provided does not match any value in the dropdown box. This has been mentioned as a problem, and I needed a solution. So, here it is.

If the autocomplete cannot return a value (it's not found by the JSON lookup), the callback is called. At this point, I reset the values of a div and a hidden field holding the ID of the thing I was looking for.

This may not be perfect, but it does get the job done.

First, how to call it:

<script type="text/javascript">

var autocompleteJSON = function(raw) {
var json = typeof(raw) === "array" ? raw : raw.resultSet;
var parsed = [];
for (var i=0; i <json.length; i++) {
var row =json[i];
parsed.push({
data: row,
value: row["orgName"] + ' [' + row["id"] + ']',
result: row["orgName"]
});
}
return parsed;
};

function afterNoMatch() {
document.forms[0].mcOrgID.value = 'nomatch';
locationDiv = document.getElementById('mcOrgLocationDiv')
locationDiv.innerHTML = "<b>Manually Entered Organization Name - No location.</b>";
return;
}

function formatCompanyName(row) {
ret = row["orgName"] + " (id: " + row["id"] + ") " + row["orgCity"] + ", " + row["orgState"]
document.forms[0].mcOrgID.value = row['id'];
return ret
}

</script>

<script>
$(document).ready(function(){
var data = "Core Selectors Attributes Traversing Manipulation CSS Events Effects Ajax Utilities".split(" ");
$("#mcOrgName").autocomplete('BrowseOrgsJSON.py')
.result(function(event, data, formatted) {
//alert("Got data back from server: name=" + data['orgName'] + ", id=" + data['id'] + ", city=" + data['orgCity'] + ", state=" + data['orgState'] + ", formatted=" + formatted);
$("#mcOrgLocationDiv").html('Location: ' + data['orgCity'] + ', ' + data['orgState'] + ' (Textura Organization id: ' + data['id'] + ')' );
document.forms[0].mcOrgID.value = data['id'];
});

$("#mcOrgName").setOptions({scrollHeight : 400 });
$("#mcOrgName").setOptions({queryArgument : "search" });
$("#mcOrgName").setOptions({formatItem : formatCompanyName });
// $("#mcOrgName").setOptions({autoFill : true }); CANNOT DO THIS WITH SUBSTRING SEARCH.
$("#mcOrgName").setOptions({mustMatch : false });
$("#mcOrgName").setOptions({dataType : "json" });
$("#mcOrgName").setOptions({parse : autocompleteJSON });
$("#mcOrgName").setOptions({selectFirst : false });
$("#mcOrgName").setOptions({extraParams : {'includeOffSystem': 'False'} });
$("#mcOrgName").setOptions({afterNoMatch : afterNoMatch });
});
</script>


Now, here's the code. I'll start off with the diff and then cut/paste the section the code is in case the code changes between now and the time you're reading this.

In jquery.autocomplete.js, the function hideResultsNow() is changed to be the following:


function hideResultsNow() {
var wasVisible = select.visible();
select.hide();
clearTimeout(timeout);
stopLoading();
if (options.mustMatch) {
// call search and run callback
$input.search(
function (result){
// if no value found, clear the input box
if( !result ) {
if (options.multiple) {
var words = trimWords($input.val()).slice(0, -1);
$input.val( words.join(options.multipleSeparator) + (words.length ? options.multipleSeparator : "") );
}
else
$input.val( "" );
}
}
);
}
else
{
// call search and run callback
$input.search(
function (result){
if( !result ) {
options.afterNoMatch();
}
}
);
}

if (wasVisible)
// position cursor at end of input field
$.Autocompleter.Selection(input, input.value.length, input.value.length);

};


and one option is added to the options section:


...
max: 100,
mustMatch: false,
afterNoMatch: function() { return; },
extraParams: {},
selectFirst: true,
...


Now for the technical diff:


Index: resources/js/jquery/autocomplete/jquery.autocomplete.js
==============================================================
307a308,319
> else
> {
> // call search and run callback
> $input.search(
> function (result){
> if( !result ) {
> options.afterNoMatch();
> }
> }
> );
> }
>
310a323
>
403a417
> afterNoMatch: function() { return; },

Friday, August 22, 2008

CodeStriker: Inappropriate IOCTL for device

I just had a troubleshooting session with a nifty code review tool called codestriker.

All of a sudden, we're getting an error of: "Inappropriate IOCTL for device" during creation of a new topic. This is maddening. I found lots of references to this, but nothing about what's going on to cause it. I can write to the directory, I can touch files there, everything seems to work, but no joy.

So, I tried putting in a modification to test the return values of the open statements in the code (/var/www/codestriker/codestriker-1.9.4/lib/Codestriker/Repository/Subversion.pm):


push @args, '--revision';
push @args, 'HEAD';
push @args, $self->{repository_url} . '/' . $url;

my $read_stdout_data;
my $read_stdout_fh = new FileHandle;
my $ret = open($read_stdout_fh, '>', \$read_stdout_data);
if (not $ret) { die("Died on open of file stderr",
$read_stdout_fh, ", msg: ", $!); }


my $read_stderr_data;
my $read_stderr_fh = new FileHandle;
my $ret = open($read_stderr_fh, '>', \$read_stderr_data);
if (not $ret) { die("Died on open of file stderr",
$read_stdout_fh, ", msg: ", $!); }


Codestriker::execute_command($read_stdout_fh, read_stderr_fh, $Codestriker::svn, @args);
$file_url = 1;
open($read_stderr_fh, '<', \$read_stderr_data); while(<$read_stderr_fh>) {
if (/^svn:.* refers to a directory/) {
$file_url = 0;
last;
}
}

Adding the 'if not ret...' lines after the opens fixed the problem. Note, I had to restart apache with /etc/init.d/httpd restart and tail /var/www/error_log to fix a minor syntax error first, but it worked out.

Tuesday, August 12, 2008

How I Would Run the Stargate System

How I Would Run the Stargate Program
by Kevin J. Rice

Preface: This is written as if Stargate was real. It isn't, it's a nice pair of shows on TV with human actors and all that. But, sometimes it's fun to put yourself into a fictional 'universe' and think about how you'd run things differently.

In the Stargate: SG1 and Stargate:Atlantis universe, the SGn teams and Atlanteans venture forth to interact with several worlds in which large numbers of humans live at roughly an 1850's level of civilization. There is a lot of rough housing, with some horse and buggy transportation, outhouses, and a lot of preindustrial development.

This is mostly consistent throughout the gate network: Settlements on most worlds have a relatively low technological level compared with modern U.S. manufacturing and service-sector capabilities.

If I were in charge of Atlantis, I would be doing things quite a bit differently. I would create a set of survival packs (gift packs to newly met worlds) and start visiting these worlds with the express intent of bringing them up to modern standards of development capacity.

Here are my plans and reasoning:

1. Reveal the Gate

Everyone (on other planets) presumes we know about the gate already anyway. Domestically, all major Earth governments know about it and have adjusted their foreign policies somewhat. So, why not? It seems to me that very little is to be gained by keeping the Gate system secret from the population of Earth. In fact, I would argue that a large scale commerce between various worlds would be the best course of action. Certainly, many more kids would be inspired to study hard so they could grow up to be engineers and businessmen building things on other planets.

2. Set Up A Stargate Emigration Authority

Many millions of people around the world would love to emigrate to a near-'virgin' planet where they could farm, raise cattle, prospect/mine, be left alone, etc. There are lots of countries that are very repressive and if it were known that it was possible or even easy to emigrate to one such world, they would flee their home country and ask for transport to the new world. This would presumably be pretty cheap to do. We witnessed this writ large in the 1800's into the American midwest. This would take significant population pressure off portions of the globe where resources are scarce and populations large.

3. Reveal Spaceflight Technology

Spaceflight tech in the SG1 universe is presented as having many solved problems available. In fact, the dreadnaught spaceships already built are testimony that the Americans, at least, know how to build and use this technology.

Likewise, spreading out to create outposts on other planets and in large, independent, and dispersed space stations lowers the risk of catastrophic attack on Earth affecting Human tech development. Every computer programmer knows, if you have something important, back it up! Humanity is important, let's "back it up". Outposts do that.

4. Develop large-scale Ring-based Transportation Infrastructure

I would create a special set of rail lines that allow two way rail transport through the ring system. This would enable large industrial commerce. Further transport could be enabled with the Al-Kesh transport ships.

Commerce, and therefore GDP growth, depends on transportation infrastructure. Getting goods to and from market efficiently lowers the cost of the goods.

5. Create a "Gate System Peace Corps"

Peace Corps volunteers/employees have taught schools, built bridges, wells, roads, etc., all over the world and have created both goodwill and a better educated populace. This obviously benefits both the U.S. and the host country. The hosts get a higher standard of living, they buy our goods and sell us things, use the money to create better factories and a richer populace that can better afford our products and vice versa, etc. Economics of free trade are not zero-sum: they are positive-sum in that everyone benefits.

A gate corps would do the same thing, and present significant opportunities for good storytelling. Story lines could be culled from the annals of the Peace Corps themselves. Most of all, we should send teachers and textbooks to other worlds, getting them into the 20th century so we are better able to become a galaxy-spanning civilization capable of resisting outside threats like aliens and inside threats like pandemics and terrorism.

6. Explore from Another Planet

Many times during SG1 it was demonstrated that merely dialing up another world could present huge problems and possibly destroy Earth:
- Black hole world
- Nasty parasitic insect world
- Gua'ould worm world
- etc.

So, my proposal is the creation of an Gate EXploration Authority (GEXA) on ANOTHER planet. This would be a well-defended but very much separate world in which gate teams explore new worlds and report back on their findings. Should contact with the GEXA planet be lost, Earth is still safe. Automated receivers hidden on nearby moons could receive log reports broadcast non-directionally; we could gate to a nearby world, then fly a ship to pick up the logs from those receivers, should contact be lost, etc.

7. Ring System to Earth's Moon

I don't know if this is possible in the fictional phyics of Stargate. However, it would be cool and solve many problems of mass transportation to/from this location. An outpost there would have some very cool aspects, including a great tourist industry, and reinforcing the idea that the Earth is a very small place. Then, maybe our petty fights (wars) might be less interesting compared to getting rich off-planet.

8. Reveal Some Military Tech

Further, if we want to create viable defenses against "the bad guys", we have to create and deploy large scale defensive systems. The nations of the Earth are engaged in an arms race, but with tech that doesn't match the 'bad guys'. So, fix that, and we'll be able to defend ourselves because we've already fought each other with this technology. Note, this could be troublesome.

---------

Overall, I would be running things significantly differently than the SG1 universe presents it. Of course, writers, you're welcome to my ideas if you thank me in the credits!

Thursday, July 31, 2008

Harriett Miers and Karl Rove: Contempt!

Again, again I cry, What of the Jail Cell in the basement of the capitol building, used throughout the 1800's to hold anyone congress found to be in contempt. The judiciary can thus be consulted AFTER THE FACT for confirmation of the solemn and proper nature of this citation of contempt. If Judges in their proper course find Congress' justifications lacking, of course the person(s) may be released. However, the burden is then on the defendant to be prompt and proper in their defense, deliberations, and legal ponderings.

On behalf of the good citizens of these United States of America, I cry, Havoc! Let slip the dogs, let us take the debate to the higher plane of prompt action. I pray thee Congress, take by your assemblage that confidence that befits the just representatives of the People. Assert thee your relevance and assuage this wrong. These contemptible scoundrels trodding heavily your constitutional duties and sauntering off, noses in the air. The time to act is at hand, Congress! Let your oath-sworn duties of oversight return to you a sense of dignity and forthright action !

All the country cries out for action... Shall we be waiting forevermore?

We the people demand: Justice Delayed is Justice Denied.

Tuesday, July 29, 2008

Dreaming of Cheap Power

I'm having a dream of cheap electric power and wondering what it would mean...

Ok, so presume an electrical generation technology, whatever technology it is, goes into massive production. Let's pick one for giggles - solar. What it is doesn't matter - the power it generates and the socioeconomic consequences are the interesting thing to me.

Our "giggles" tech is solar, in the form of solar panels that can be manufactured for 1 cent a kilowatt or less in very large quantities. This is not that far off, really. See this National Renewable Energy Laboratory NREL Presentation . It says on Page 15 that the break even for electricity from PV instead of coal / nuclear is $2 per Watt-peak. The 'Watt-Peak' measurement is the amount of electricity in watts that a module can generate in full sun.

Okay, say it's 5 years from now, and Obama has won and put a signficant budget into renewable energy tech, and it has yielded the somewhat predictable result of lowering costs consistent with the last 15 years of experience curves (see wikipedia for 'experience curve').

This means US production capacity of solar is about 320,000 MW, which is about 33% of our usage. This curve gets nicer the next 2 years, and we're looking at a shutdown of all coal-fired, oil-fired, and natural-gas fired power plants for daytime base load. Existing nuclear plants can handle nighttime loads.

What has just happened to the domestic economy?

1. Coal mining in the Appalachian range ceases. Miners are out of work, which is probably beneficial to their health. Government programs step in but only partially help. Depression hits in isolated areas around these plants.

2. Installation of commercial and residential solar and wind calls for large numbers of qualified electricians.

3. Many houses decide to go off-grid. Others install larger systems and generate power to sell to the utilities.

4. Coal-fired plants going offline leads to sharp drops in carbon dioxide emissions. The U.S. becomes compliant with the Kyoto Treaty even though we never signed it.

5. Mercury and sulfur dioxide emissions from coal plants cease, leading to cleaner air all up and down the eastern U.S. seabord (coastline).

6. Residential and commercial installation of batteries for nighttime use drive experience curves for batteries, specifically lithium ion batteries. This drastically lowers costs for this early technology. PHEV (Plug-in hybrid electric vehicles) or EV (battery-only electric vehicles) become much more popular due to their simplicity and lower cost.

7. Detroit (the big 3) stop production on the last direct-drive internal combustion engine since it is cheaper and easier to create hybrids.

8. Some large disasters happen with home battery installations causing large fires (LiOH batteries can do that, especially cheap ones). Standards change to put batteries in fireproof rooms or in concrete/metal cases outside the home much like air conditioning condensers.

9. Someone figures out how to use electric energy to create natural gas out of air, water, and coal. Many cars switch to natural gas.

10. American spending on Iraq, a credit crunch, and bad inflation combine to produce a drop in the stock market as global investors turn to expanding economies instead of the USA. Gradually the business cycle returns to normal and the economy expands again. Luckily, there is production of PV locally, and there's many jobs to be found due to green energy investments (due to high prices on the international market for oil).

11. Global oil consumption is way down due to the fall in exchange rate for the dollar. This reduces demand, which drops price. However, inflation raises prices again, and consumers feel the pinch.

12. Less real money for oil is going to middle-eastern countries, Canada, Mexico, Venezuela, and Russia. These economies suffer greatly. Saudi Arabia and several other governments have revolutions which put reactionary, fundamentalist governments in place. These could have been prevented by transitions to J-Curve power-sharing governments with checks and balances. Loss of income destabilizes the ruling elite, but in the end the power devolves to the masses and slowly stable democracies or balanced monarchies emerge.

13. China emerges as the largest economy in the world. PV output from Chinese plants exceeds any other countries. Large installations in the Gobi desert power much of China's infrastructure.

14. India surpasses the USA in size of the economy, due to U.S. shrinkage as well as Indian growth. Indian wealth drives up demand for finished goods, moving production plants (industrial manufacturing) for ultra-cheap goods to Africa. Low wage jobs in Vietnam, Cambodia, Laos, start migrating to Chad, Niger, Liberia, South Africa, Zimbabwe, etc.

15. China launches several probes of the moon, Mars, Venus, etc., showing off economic strength and technical prowess.

16. A medium-size epidemic kills several hundred thousand in southeast asia, and the rest of the world is scared. There is talk of requiring health checks and quarantine areas to international airline flight arrangements.

17. The Artic sea becomes ice-free in the summer. Ellsmere Island and Greenland start to slough off large icebergs. There is serious talk of global sea level rises of feet, not fractions of an inch. Belgium, Italy (because of Venice), and Bangladesh start shouting about global warming instead of just being "very concerned".

18. Due to decreasing income, Russia decends into instability along the left of the J-Curve. Authoritarians win there, but lose control of the security situation due to insufficient funds and a sprawing country with a bad economy.

19. Primarily due to bad economics, a Russian nuclear weapon (from the former Soviet Union) is stolen/purchased and detonated somewhere in the world, for political reasons. Tens of thousands are killed and a city decimated. Suddenly, cost becomes no object in the search for and sequestration of all remaining nuclear arsenals as well as chemical and biological weapons.

20. The nuked city and global reaction to it drastically reduce demand for nuclear power plants; some in the process of being constructed are stopped.

21. Global carbon dioxide production starts to decrease but just barely in 2018. It then falls sharply as developing nations turn off coal and turn on to the now-cheaper renewables.

22. Existing CO2 in the atmosphere raises temperatures enough to melt and split off a sizeable chunk of the West Antartic ice sheet, raising global sea levels over 1 foot inside of 3 years. Panic ensues in low-laying countries. Bangladesh starts a war with India for resettling rights on higher ground. Several pacific islands are lost entirely.

23. CO2 emissions rights are traded on all world exchanges. The Arbor Day Foundation (ADF) becomes the largest recipient ever of a corporate donation, $4 billion, from the government of Belgium. ADF starts planting trees worldwide, including massive numbers of almond, olive, and palm trees across the middle east.

24. A category-4 hurricane strikes Philadelphia and causes large scale destruction in nearby states as well, including New Jersey and even into New York. Increasing numbers of severe hurricanes are blamed on global warming.

25. Britain's summer, and that of western Europe, is noticibly foreshortened and sea temperatures are blamed. The EU makes a deal with Brazil to purchase, cease development on, and put under military control an increasingly large section of Amazon rainforest, to prevent deforestation.

--- That's it for today. lots of bad news. But lots of good news, too. The average people living in the middle east are going to be better off, with more of a chance at representative governments, but it's also riskier for them if they make autocratic choices along the left side of the J curve. People the world over are in worse shape environmentally from the effects of the changes, but they are forced to make better ecological decisions by obvious circumstances affecting their checkbooks.

As the problems mount, the onus for green change becomes huge. On the other hand, so many changes in so little time present vast problems for maintaining stability. Reactionary conservatism is usually the result of this kind of instability, but the conservatives can take the "green" label away from the left in the name of religion, less government interference (deregulation of energy production and distribution), etc.

Monday, July 28, 2008

using libcurl, pycurl on for xml post

I had to do an xml call to get data from a remote server. it had to be a post request.
This is a simple example of using PycURL (pycurl) to access the libcurl library. I had been doing a python popen3() call to '/usr/bin/curl' and passing the params. This was ugly. A co-worker recommended pycurl. So, here it is, the sample code:

c = pycurl.Curl()
c.setopt(pycurl.URL, ncServerURL)
c.setopt(pycurl.POST, 1)
c.setopt(pycurl.HTTPHEADER, ["Content-type: text/xml"])
c.setopt(pycurl.TIMEOUT, ncServerMaxTime)
c.setopt(pycurl.CONNECTTIMEOUT, ncServerMaxTime)
c.setopt(pycurl.NOSIGNAL, 1) # disable signals, curl will be using other means besides signals to timeout.
c.setopt(pycurl.POSTFIELDS, xmlRequest)
import StringIO
b = StringIO.StringIO()
c.setopt(pycurl.WRITEFUNCTION, b.write)
c.perform()
ncServerData = b.getvalue()

This would only work after I installed pycurl. However, I'm running this on Ubuntu Hardy Heron, and Hardy wanted apt-get to install libcurl version 7.18.0. But pycurl wanted version 7.18.2 minimum. So, I had to go back a version on pycurl. Recommendation: hand-install pycurl version 7.16.4 (the one previous to 7.18.1) and it will work.

Enjoy!

Tuesday, July 15, 2008

Tried Used HVAC places

I sent a bunch of emails yesterday to various companies that buy and sell used HVAC equipment. I said I wanted to buy used blower fans.

I don't think I'm going to find any of these. Alas.

Monday, July 14, 2008

Vertical Axis Windmil - Materials problems

I've been trying to do preliminary design work on a windmill as a for-fun project. That is, besides the fact that I've got a lot going on around the house fixup-wise, I thought it would be a fun build.

So, basic decision #1:
Question: propeller or vertical axis wind turbine?
Answer: Unequivocally, I'm going with VAWT:
- very tight suburban location with high trees nearby
- aesthetics important;
- chaotic winds are typical
- simple build is better, this is practice.

Decision #2: Surface area available to wind?
Answer: Probably maximum of 1 to 3 square meters.

Decision #3: Type of turbine?
no answer yet. I found it's very hard to buy squirrel cage / blower fans as a one-off. Everyone wants to sell me 500 of them at once, for lots of money.

I called a company in Canada and found they were already going to be making some for another customer and would just extend the production run for me. The price was about $120 for a crossflow blower fan, which is a cylinder 30 inches tall by 8 inches diameter with the outside serrated and each tab bent at an angle (google 'crossflow blower' to find an example).

That's 240 square inches of wind-face for $120 = about $0.50 per square inch. This might be a great solution for someone, but I'm too cheap for this. This is a for-fun project and I'm budgeting about $200 for the whole thing. Since I'd need about 10 of them to get my surface area, I'd be 5x my budget and still without any other major components. Plus, I'd have to wait a couple of months since I'm tacked onto another order, but I understood that.

The lady at this company was very nice, though, and kind to speak with me given I'm a random person to call her and ask such a wierd question. If you're interested, the company name is www.eucania.com.

I'll have to think more about how to do this more inexpensively. I'm thinking I'd like something like a savonius rotor, since it's cheap to make. I just put out the call to my mother and her church group to start collecting a bunch of extra-large V-8 juice or grapefruit juice cans (the 6-inch diameter fans). I know that'll be cheaper, but it's going to be a more complex build, and I'm going to be fighting complexity this whole time.