2017-02-06 03:41 pm
Entry tags:

A lesson in meaningful variable naming

A variable representing a link to a website might be called $url or $link or $site. Take this project I'm working on. At one point in the code the variable might be called $url. At another point it is $link. Further on, it is $site. I want to reach back across time to my younger self and slap him the face and scream at him and impart a lesson on the value of maintaining a consistent naming convention.

So let's say $site represents a link to a website except when it doesn't because I am also using $site as a unique key to represent a website in the general sense that "this website contains web pages". For this purpose I send $site through a filter that strips out the protocol and leading www. and the ending index.html if it exists. This means that $site is not the same thing that it used to be. So $site and $link actually are two different things with two different meanings. They should be two different variables.

I fixed a few bugs just by noticing that the meaning of these variables was not consistent.

In the same program I have two variables $sites_visited and $destination_count that seem to have a similar purpose.

$sites_visited is:

  • set to 1 when process_site() is run
  • checked when recursing into new sites
  • was sent to process_site_results() in an earlier version, but this is commented out

$destination_count is:

  • increased by 1 when process_site() is run (this is a bug)
  • increased by 1 when a site's list of links is finalized
  • used by process_site_results() to determine whether the site should be included in output.

So both of them are set to true when a site is processed and were intended to be used to tell if a site is worth processing. However, they mean different things.

  • $sites_visited is true when a site has been fetched and processed.
  • $destination_count counts the number of times a site has been linked from another site. It is nonzero (true) before the site is fetched or processed.

So they remain two different variables because they account for different concepts.

2017-02-05 07:23 pm
Entry tags:

Quick thoughts on multiple inheritance

Has-A pattern:

class MyClass { 
 FooType foo;
 BarType bar;
  • each MyClass allocates space for a FooType and a BarType.
  • foo and bar establish their own namespaces.


class MyClass extends FooType, BarType { }
  • each MyClass allocates space for a FooType and a BarType.
  • The namespaces for FooType and BarType are incorporated into the MyClass namespace.

So what's the problem? Something in FooType or BarType might overlap.

General outline of a solution:

  • All namespace conflicts must be resolved by the programmer.

Considering specific examples:

1. Both FooType and BarType have a .x property?

  • Solution 1: Forced upcasting. All attempts to access MyClass.x must be upcasted to the parent. All parent methods work on their own .x property.

2. Both FooType and BarType have a .fooMethod()?

  • Solution 1: Forced upcasting. The compiler should warn if the programmer fails to resolve the conflict, and throw an error if the programmer tries to run MyClass.fooMethod() without overriding it. This can cause problems (see case 4).

3. MyClass has its own .x property?

  • Solution 1: Override parent access methods. If the property is interface-compatible with the parent's .x property, the FooType/BarType methods will run on MyClass.x instead of their own .x properties. If the property is not interface-compatible with the parent's .x, the compiler should throw an error and refuse to compile. PROBLEM: FooType and BarType may intend for their .x property to mean different incompatible things or to hold separate pieces of information. Sharing the same piece of data will introduce bugs.
  • Solution 2: Do not override parent access methods. Parents continue to operate on their own .x properties.

4. MyClass has its own .fooMethod()? Theoretically, this should override the FooType/BarType methods. However, it introduces a double-call problem.

  • Solution 1: Override parent methods. This introduces a double-call problem. If both parents have a method called every second that calls their own fooMethod(), this causes the overridden fooMethod() to be called twice per second instead of once per second.
  • Solution 2: Do not override parent methods. Parent calls to fooMethod() will call the parent version of fooMethod().


More thought needs to go into this.

  • Multiple inheritance is fine until you have a namespace collision, and then you're in trouble.
  • If you have the parent classes share data when both have a .x property, then you have the problems that each might treat .x as a different conceptual thing and that conflicting actions on the same .x may introduce race conditions that do not exist when each class uses its own data.
  • If you do not have the parent classes share data, then you have multiple copies of what might be the same conceptual thing, updates to one do not affect the other, and the state of ".x" is unclear.
  • If the child class .x overrides the property for both parent classes, then you risk the parent methods modifying the data in ways you did not intend.
  • If the child's .foo() overrides the method for both parent classes, then you might get a double-call problem when methods in both parent classes call their overridden .foo() method.
  • If the child's .foo() does not override the parent method, then you lose the ability to extend the parent class by having its .foo() method do something different.
  • The programmer may want to resolve namespace collisions in a different way for different properties and methods in the same class.

2017-01-31 01:58 am
Entry tags:

Revisiting a pet project

Gee, I think this software of mine is close to ready for release. I just need to brush it up a little.

... (create a todo list ... it's half a dozen things)

... (open the file, and there's a list of another half dozen things to do)

... (there are several known bugs that have no discernable cause)

... (none of the functions are documented and I cannot tell what one of them is supposed to return)

... (making it run well will require repeatedly rerunning it and massaging input data files)

... (it produces no output when given the same input that had produced good results the last time I had worked on it)

... (the file is still named test.pl)

This might take more time than I had thought.

2017-01-27 05:18 am

The best spam that I have received in a while

This appeal ended up in my inbox:

(If you are not the person who is in charge of this, please forward this to your CEO, because this is urgent. If this email affects you, we are very sorry, please ignore this email. Thanks)

We are a Network Service Company which is the domain name registration center in China.

We received an application from Huayi Ltd on January 16, 2017. They want to register " hfb " as their Internet Keyword and " hfb .cn ", " hfb .com.cn ", hfb .net.cn ", " hfb .org.cn ", " hfb .asia " domain names, they are in China and Asia domain names. But after checking it, we find " hfb " conflicts with your company. In order to deal with this matter better, so we send you email and confirm whether this company is your distributor or business partner in China or not?

Here is a link to my "company" that distributes HFB. In fact, you can look at all of the HFB that I am distributing.

2017-01-25 07:06 pm
Entry tags:

Unfinished parody: Marksman Blunt

Here is an unfinished parody that was found while cleaning up old files on my hard drive.

Read more... )

2017-01-10 05:51 am
Entry tags:

Some retrievals must be attempted more than once.

Here's another rough draft from my Smash fanfic. Read more... )

2017-01-03 12:28 am

Tang is OG (oldschool gamedev)

I went through some old boxes today. Mixed in between my Cub Scout stuff and stuff from my first year of SRJC was a notebook that had four pages totally filled with a chart of weapons and armor for some D&D-alike that I had forgotten I had ever worked on.
2016-12-31 04:58 pm
Entry tags:

The Harambe Song

(sung to the tune of Fleetwood Mac - Rhiannon)

Harambe lived like an ape in the zoo
Would you like a banana?
The TV showed the end of his life
And he became a legend.

Have you ever seen a gorilla
As handsome as Harambe?
Would you cry if the zookeeper shot him?
Would you give a damn?

He sat around on his gorilla butt
And now he is in heaven.
They took his life with a shot in the heart
And some say that was heartless.

Have you ever seen a 3-year-old boy
Dropped inside your pen?
Would you try to wash him in the water?
Would you try to eat him?
Would you try to eat him?

2016-12-30 06:15 pm
Entry tags:

Scheduling fictional fights

My Smash fanfic-in-progress has a schedule.

I have given myself some guidelines in designing this:

  • Some fights will happen at certain weeks in the story, and this is unavoidable. The others can be shuffled.
  • Four fighters are going to end the season at 4-2, 5-1, or 6-0 and make the finals.
  • Everyone else will end the season at 3-3 or worse.
  • Certain fighters are going to be 0-2 at week 3 so there can be side stories about their struggles.
  • Fighters on the same team do not fight each other.
  • Nobody should fight more than two fighters from any other team. This can be fudged in the offscreen fights.
  • The tournament is larger than the named characters, so fighters can fight "someone else".

I have created a logic puzzle. It's like Sudoku.

So, after a short time I now have a full schedule for all characters. One of them ends up at 4-2 instead of 5-1, and I cheated by having Alex fight "Other" offstage on two different weeks, but it will work. It does not have to be logically perfect, it only needs to carry the story. I was only trying to fit some of the fights to the formal schedule, but I had to schedule more and more of them to make it work.

2016-12-29 04:41 pm
Entry tags:

Game dev thoughts - valuing an object based on its components

Crafting with multiple inputs

Consider a game with a crafting system. Imagine that crafting an object requires several inputs.

  1. Crafter skill level
  2. Input A
  3. Input B
  4. Input C

The qualities of these inputs may be variable.

  • The crafter's skill level varies as the crafter gains experience.
  • Metals: how well refined it is
  • Food product: age and suitability
  • ... etc ...

Imagine that any input can have a quality rating from 0 to 100%. The quality of the inputs can affect the quality of the resulting product. To implement this, we must create a function to determine the output quality. Let us call our inputs [A,B,C,D], each ranging from 0-1, and create some example functions.

  • Multiplication: q = A * B * C * D
  • Summation: q = (A + B + C + D)/n where n is the number of inputs
  • Sum of squares: q = (A^2 + B^2 + C^2 + D^2)/n
  • sqrt(Sum of squares)

The multiplication function emphasizes differences from 1.0, the netural position. The addition of flawed components will create greater flaws in the result.

The summation function minimizes the effect of flawed components on the end result. The addition of perfect components will even out the result toward 1.

The sum-of-squares function will produce results somewhere in the middle of these two extremes. Taking its square root will push the quality value toward 1.

The choice of function is up to the game designer. It will help to throw several functions and examples into a spreadsheet and see what ranges of results you feel are appropriate for your game.

Crafting with weighted inputs

How about weighting the inputs so that some will matter more than the others? You will need to rewrite your algorithm.

Rules for weighting:

  • Inputs with a larger weight will have more influence on the result than inputs with a smaller weight.
  • If all weights are equal, the result should be the same as the unweighted algorithm.
  • If one weight approaches infinity while the others hold still, the result should be as if all other weights are zero.

Let us call the inputs [A,B,C,D] and their weights [Z,X,Y,W].

Helper functions

It may help to calculate how much any weight differs from the mean average weight of all objects in the set. For input weights of [5, 1, 4, 2.8], this produces [1.5625, 0.3125, 1.25, 0.875].

  • f(Z) = Z/(Z+Y+X+W) * n where n is the number of weights

It may also help to adjust the values of the weights relative to the largest weight. For the same inputs, this produces [1, 0.2, 0.8, 0.56].

  • g(Z) = Z / max(Z, Y, X, W)

Function redesign

The multiplication function (q = A * B * C * D) emphasizes the input's difference from 1.0 and compounds these differences as more inputs are added. We can create a helper function m(input, weight) to adjust this difference relative to the weight. For weights [5, 1, 4, 2.8] and all inputs 0.9, this produces [0.9, 0.98, 0.92, 0.944].

  • m(A,Z) = 1 - (1-A)*g(Z)

An analogue to the multiplication function becomes:

  • q = m(A,Z) * m(B,Y) * m(C,X) * m(D,W)

The summation function is easily modified by multiplying each input by its weight, then dividing by the sum of weights.

  • q = AZ + BY + CX + DZ / (Z+Y+X+W)

The sum of squares function can be modified similarly to the summation function.

  • q = (A^2*Z + B^2*Y + C^2*X + D^2*W) / (Z + Y + X + W)

Here is some bonus math that I was working on the other day. Imagine that you have three different crafting functions Z,X,Y that take inputs A, B, and C.

  • Z = A + 2B
  • Y = 0.5A + 2B + C
  • X = B + 3C

Now imagine that you have volumes of A, B, and C in storage; let's say 40A, 80B, 20C. How does one maximize production? This is a solved linear algebra problem so you should go looking for the appropriate method in your language's math libraries.

In Python, you lay out the functions like this:

a = [
        [1.0, 0.5, 0.0],
        [2.0, 2.0, 0.0],
        [0.0, 1.0, 3.0]
r = [40,80,20]

print scipy.optimize.linprog(c=(-1,-1,-1), A_ub=a, b_ub=r )

optimize.linprog() is used because linalg.solve() will give you negative numbers.

What if you want to weight the functions so that one is more valuable than another? I'm still working on it.

2016-12-23 10:49 pm
Entry tags:

The recruitment arc (very rough draft)

Some more of my Smash fanfic. Before the heroes get into the tournament, they have to recruit the fighters. Not everyone is cut out to join the team. Read more... )

2016-12-17 10:20 pm

Crash Champions: Thunder and Silence (rough draft)

Here's an idea that I got one morning and spent the whole rest of the day writing down. Might as well publish.


The Boddy Estate

It is a dark and stormy night outside the Boddy Estate, a Victorian mansion.

A group of detectives enter the mansion. They resemble Sam Spade, Sherlock Holmes, Jessica Fletcher, Charlie Chan, and other familiar faces. They badmouth and berate each other like the parodies in Murder By Death but are even more abrasive because they are only going to be on screen for a minute.

Lightning flashes and the power goes out, leaving them in darkness. The detectives insult each other again, their voices rising as they nearly come to blows.

Lightning flashes and thunder booms, and there is silence and darkness.

The Boddy Estate at morning

Morning breaks through the mansion's windows. Every one of the detectives is dead, sprawled all over the room. One of the bodies is hanging by a noose from a slowly spinning ceiling fan. Another has knives in his body. In the foreground, an open bottle of poison sits next to someone's drink. Spread across the ground are at least two pistols, an axe, a lead pipe, a broken candlestick, and other murder implements. There is no blood. This is PG.

At the open front door stands a group of teenagers with a Great Dane dog. One of the teenagers says: "Gee golly! It's a mystery!"

Cut to opening credits. Read more... )

2016-12-09 01:50 pm
Entry tags:

Building high level code from low level code

Consider that a class in c++ or java defines both an implementation and an interface.

Consider the similarities in these three examples:

// Example 1 
interface IFoo {
 // interface

 // implementation not defined
// Example 2
class Foo {

 // implementation
 int x;
 string y;

// Example 3
// implementation 
struct foo {
 int x;
 string y;

void foo_doStuff(); // interface

An ordinary compiler might be expected to convert lower-level code to a low-level implementation immediately upon reading it. The programmer has defined exactly how the code is to be implemented, and there is no apparent need for higher level considerations.

A hypothetical high-level compiler might first convert as much low level code as possible into a higher-level intermediary language.

  • class Foo is automatically built from struct foo and is automatically populated by the foo_() functions that operate on a struct foo.
  • interface IFoo is automatically built from the internal representation of class Foo
  • This high level representation is saved to an object file and can be accessed by any programming language that can load libraries.

Additional thoughts:

  • An autodoc tool can produce documentation from the resulting high-level objects, especially if the high level object includes comments or links back to the original source code.
  • An IPC mechanism can send the object definition to the receiving side if the receiving side does not have the structure defined.
  • The compiler can detect classes that are binary-compatible with one another and allow them to be casted without harm.

Also, it should be possible for a sufficiently smart compiler to recognize that some for-loops are examples of an iteration. These can be interpreted upwards to a high-level description of an iteration like foreach x in myArray{...} for which the developer has provided a low-level implementation for (i=0; i<length; i++){...}

I cannot think of any benefit to doing this, but it could potentially be done.

2016-11-28 01:26 pm
Entry tags:

DoJ wants to consider anonymity evidence of a crime

Techdirt has been following a Department of Justice request for expansion of powers.

In addition, the DOJ wants permission to break into "compromised" computers and poke around inside them without the permission or knowledge of the owners of these computers. It also wants to treat anything that anonymizes internet users or hides their locations to be presumed acts of a guilty mind. The stripping of jurisdictional limits not only grants the FBI worldwide access for digital seizures and searches, but also encourages it to go venue shopping for judicial rubber stamps.

Like many expansions of power during the Obama administration, no law is changing. They are simply declaring that they will do this from now on.

2016-11-27 12:03 am
Entry tags:

The Second String

Here's an unfinished story that I started as a response to the Avengers movie.

Read more... )
2016-11-26 01:54 pm
Entry tags:

A brief comparison of 20th century communist ideologues

Ho Chi Minh lived a life of sin
that's high livin with coke and vin

Mao Tse Tung liked his girls real young
He'd take them home and give them tongue

Fidel Castro went for the asshole
He was a bearded Cuban pederasto

Joseph Stalin was real big ballin and all around the clock
Babushkas lined up for seven blocks to ride his commie cock

2016-11-26 04:23 am
Entry tags:

Crash Champions character profiles

From one of my fanfics in progress, meet Mick and his team of combatants who seem very familiar but have been renamed so I could feel comfortable changing their characterization to suit the development of the story. Read more... )

2016-11-16 08:09 pm


Put the best five guys in the NBA together on one team and put them on the court. You'll see brilliant plays by one player at a time, but they won't play to their peak potential because they're not used to playing with each other as a team. They are not familiar with each others' instincts. They are not used to working together.

Take the guys ranked 25 through 30 and let them train for a month, practice, and get used to each other. Then put them up on the court against the top five guys. They'll win. Why?

Because 25 through 30 is six people.

2016-11-10 05:38 pm
Entry tags:

Reviewing Trump's plan for his first 100 days

From NPR:


* FIRST, propose a Constitutional Amendment to impose term limits on all members of Congress;

The parties tell the Congressmen what to say and who to give favors to or else they don't get support for their next campaign and they don't have a job in two years. Congressmen are already interchangeable cogs in a corrupt system. The proposed remedy only regulates the time of their replacement with new cogs. It does not address the corruption.

Alternative: Zephyr Teachout found that lobbying used to be a crime. Legal historians should conduct further research in this area to see if such a law could be enforced.

* SECOND, a hiring freeze on all federal employees to reduce federal workforce through attrition (exempting military, public safety, and public health);

So Trump is promising not to add any of his own people to government? I don't think he has thought this through.

Alternative: Seek out corrupt individuals and wasteful departments and cut them. Seek input from federal employees about wasteful spending and guarantee new jobs for anyone whose reports lead to the cutting of their own job.

* THIRD, a requirement that for every new federal regulation, two existing regulations must be eliminated;

Such strict requirements usually cause more harm than good.

Alternative: Seek out and streamline poor regulation.

* FOURTH, a 5 year-ban on White House and Congressional officials becoming lobbyists after they leave government service;

I would extend this to all managerial-level employees.

* FIFTH, a lifetime ban on White House officials lobbying on behalf of a foreign government;

The same 5-year ban may be enough. We also need to be clear about what kind of lobbying for foreigners is already illegal. What law was used to charge Tokyo Rose?

* SIXTH, a complete ban on foreign lobbyists raising money for American elections.

Is this not already illegal? They will simply launder money through an intermediary as they already do. We need more prosecution of money laundering.


* FIRST, I will announce my intention to renegotiate NAFTA or withdraw from the deal under Article 2205

Good. This gives us a large amount of room to change our mind if we need to. A renegotiation may be all that is necessary.

* SECOND, I will announce our withdrawal from the Trans-Pacific Partnership

Good. That treaty was horrible.

* THIRD, I will direct my Secretary of the Treasury to label China a currency manipulator

I am unsure of the implications of this.

* FOURTH, I will direct the Secretary of Commerce and U.S. Trade Representative to identify all foreign trading abuses that unfairly impact American workers and direct them to use every tool under American and international law to end those abuses immediately

It's good to investigate and counteract such abuses, although a too-aggressive approach can cause diplomatic problems.

* FIFTH, I will lift the restrictions on the production of $50 trillion dollars' worth of job-producing American energy reserves, including shale, oil, natural gas and clean coal.
* SIXTH, lift the Obama-Clinton roadblocks and allow vital energy infrastructure projects, like the Keystone Pipeline, to move forward

Some of those restrictions are in place for a good reason. The industries will want you to lift everything that gets in the way of them making more money quicker, regardless of the risk. If something goes wrong, the cost is eaten by everybody else but them. The government has a duty to make sure they don't work so cheaply that it risks an environmental disaster.

Law and order

* FIRST, cancel every unconstitutional executive action, memorandum and order issued by President Obama

I assume that a list of such orders has already been drawn up. Otherwise this is campaign rhetoric masquerading as a policy.

* SECOND, begin the process of selecting a replacement for Justice Scalia from one of the 20 judges on my list, who will uphold and defend the Constitution of the United States

As expected.

* THIRD, cancel all federal funding to Sanctuary Cities

I can support this, but is it legal?

* FOURTH, begin removing the more than 2 million criminal illegal immigrants from the country and cancel visas to foreign countries that won't take them back

Letting ICE know that they are allowed to do their jobs will be a big step forward.

* FIFTH, suspend immigration from terror-prone regions where vetting cannot safely occur. All vetting of people coming into our country will be considered extreme vetting.

Yes, this was a campaign promise. We should also begin the process of developing a vetting system, which will require in-country humint willing to leave their hotels.

100 days measures

Middle Class Tax Relief And Simplification Act

Simplification is more important than tax relief, in my opinion. The middle class wants a smaller tax workbook and to cut a smaller check.

The bigger taxation problem is tax evasion by the wealthy moving money offshore and avoiding taxes. We need to close loopholes and give prosecutors a green light to investigate tax evasion.


My opinion on tariffs is that they should be kept low to open a window of market opportunity for domestic producers without wholly freezing out imports from people who may want them.

I also oppose tariffs on raw materials. Raising the cost of the basic building blocks of our industry will increase the costs of everything. Also, we can let other countries ruin their environments before we do.

We should consider a tariff based on labor conditions, where we task the State Department to see whether any country effectively enforces its own labor laws and send annual reports to Congress which has the final say on lifting or imposing the tariff. This could discourage slave labor practices by international industries, make outsourcing less competitive, and appeal to the foreign working poor which could have long-term diplomatic benefits.

American Energy & Infrastructure Act

This is too vague to have an opinion on, but I have some concern about what those "public-private partnerships" might be.

School Choice and Education

Parents want vouchers for private schools because the public schools stink. This cannot be fixed from Washington, but we can certainly make it worse if a reform plan goes wrong. We should keep an eye out for fraudulent abuse of the voucher system, like any other government program.

Common Core can be done away with. The "Commie Core" conspiracy theories turned out to be true, the data collection is dangerous, the new materials are notoriously poor. Free the school districts to keep whatever works and discard the rest.

Repeal and Replace Obamacare Act

The problem with American healthcare is that something is unnaturally driving up medical prices. Many problems go away if we can fix that. Some suggestions to begin to address the issue: enforce antitrust law, carefully reduce the volume of regulation, ask office clerks from the medical industry to send suggestions to HHS.

As for Obamacare, any centralized medical care system becomes inefficient due to the lack of competition and the inability to compare it to a neighboring system. The fact that there is a medical system is itself the problem. Single payer is the best system on paper. It works for one generation and then the inefficiencies of a sedentary industry start building up. We should distribute policymaking decisions out to the states to allow different ideas to succeed or fail.

End Illegal Immigration

I have no idea how Trump plans to get Mexico to agree to pay for the wall. Seizures of drug gang assets? That will require legal work.

We should punish businesses that knowingly encourage illegal immigration. There is a black market for labor. Some businesses hire illegals because they can screw them over and the workers cannot file suit.

The other side of the immigration coin is to encourage legal immigration. The process should be quicker and have less paperwork. Some form of the old Bracero program could be used to address the need for farm labor and add legal oversight so that workers' rights are not artificially suppressed by employers exploiting immigrants.

Restoring Community Safety Act

Some police training programs backfired and created the "shoot first" policy that has reduced trust in police. That's something the program administrator should be aware of.

In some areas there simply aren't enough people to deal with crime problems. In some areas morale is an issue. In others the gangs are inside the police force. It's a mess and I don't have answers.

Organized crime is probably a bigger problem than violent crime. A good educational policy will address both in time.

Restoring National Security Act
Clean up Corruption in Washington Act

Both descriptions are too general to criticize.

2016-10-10 05:31 pm
Entry tags:

Wait, whaaaat?

Turkey, Russia strike strategic Turkish Stream gas pipeline deal

Aren't they in a shooting war with each other? They're using proxies, but still.