CodeSOD: The Difficulties of Choice |
Its no easy task combing through the submissions and choosing the right code sample.
Ulysses knows my pain. He recently inherited a Python codebase with plenty of global variables, no convention around capitalizing identifiers, inconsistent levels of indentation, and an AngularJS front end.
He found this when investigating a bug:
candidateNum=4
if candidateNum == "4":
handleCandidate4()
return true
else:
handleCandidate3()
return true
Once upon a time, this code received candidateNum as an input, and made a decision. Sometime in the past, Ulyssess predecessor changed it according to a ticket: Only use the candidate4 settings. So, he hard-coded in candidateNum = 4 and released the change.
There was only one problem with that. Pythons == operator does strict comparisons. 4 != "4", and never will be. This leads us to think that perhaps the last person to touch this code knew JavaScript a little better than Python, since JavaScript has no type system to speak and happily coerces types silently.
Ulysses removed the conditional logic.
|
Метки: CodeSOD |
The EDI Fall Back |
Chris M. was a developer at Small Widget Manufacturing. He and his coworker Scott were, in theory, assigned only to developing their in-house ERP software. However, with just one person running the companys help desk, they often picked up anything considered software-related.
A ticket pinged Chriss inbox: EDI Running Slow. It was from a sales rep named Brett, and like most tickets from sales reps, was marged Urgent. Chris decided to play ball, since Scott was tied up with something else. He called Brett, asking if he could elaborate.
Normally, when I get an order from a customer, Brett said, I can just go into our ERP system and upload it, and itll get imported in fifteen minutes. If I get an error, I wait fifteen minutes and try again. That used to work, but now its taking longer than 45 minutes for it to upload.
Its probably just a scheduler thats misconfigured, Chris said. Ill look into it.
Small Widget Manufacturing used a custom-built EDI solution for transferring orders, blueprints, etc. between their customers and the plant. The whole thing had been delivered by some expensive third-party consultants just before Chris had started at Small Widget, after which the consultants vanished without a trace. They hadnt even left behind documentation for the EDI software.
Chris hadnt yet dug into the guts of the EDI software, so he asked Scott where it was housed. Dunno, he replied. Check with IT.
Fine. So Chris went to IT, talking to Cori, who headed that department. After half an hour of digging through paperwork, she led Chris to a desktop box in a corner, covered in dust. On its case was a badge: Windows 7 Home, it said.
EDI runs on that?
Cori nodded. The consultants didnt want to put it on some new hardware, so they dug this out of storage and installed their software on it. They didnt even bother to reformat it.
Back at his desk, Chris was able to remote desktop onto the Win7 machine and began digging around. He checked the hard drive first, noticing that there was very little space left. The default Windows task scheduler was terrible, so anything usable must be custom-built. He noticed an application running in the taskbar with a clock icon. He clicked on it, spawning a console window.
The highly-paid consultants EDI solution was little more than a long-running FTP app. Thinking that the app must be choking the disk with logs, Chris dug through the hard drive and found them.
[12] Sun 01Nov15 03:24:04 - (Task: SPS FTP) - Next scheduled execution on Sunday, November 01, 2015 04:39:00
That looked wrong. Brett said that his file transfers happened within 15 minutes. Why would the next task be scheduled for an hour and fifteen minutes in the future? Digging further back into the logs, he found this:
[12] Sat 31Oct15 23:39:02 - (Task: SPS FTP) - Next scheduled execution on Saturday, October 31, 2015 23:54:00
It was scheduling tasks correctly on October 31st, but not November 1st. So what happened on that date to cause the scheduler to bump up the interval by an hour? Frustrated, Chris stepped over to Scotts desk to bounce some ideas off of him. He asked what could possibly have happened on November 1st.
I dunno, Scott said. Daylight saving time?
As Scott said it, both he and Chris knew that was exactly what was wrong with the machine. It was running off its own scheduler, not Windows, so whatever solution the highly-paid consultants had given Small Widget, it didnt account for the end of daylight saving time.
After some further digging, Chris discovered a setting: the app used 09012015 as a start date for its scheduling timer. He changed this to 11022015, a day after the end of daylight saving time. He restarted the app in task manager, waited half an hour, and checked the logs.
It was once again running every 15 minutes.
He called Brett with the news, who was just happy that his file transfers didnt take over an hour to complete. Chris also added an item to his calendar: at the beginning of daylight saving time next year, he would change the date setting again. He didnt want to know what would happen if the scheduled task were set to run every 45 minutes.
|
Метки: Feature Articles |
Announcements: Code Offsets - Version 2.0 |
The Daily WTF exists to point out coding horrors, but a few years ago we also took a swing at trying to prevent bad code. Long time readers might remember our 2009 initiative, Code Offsets. We are pleased to announce that Code Offsets are back, redesigned, and ready for you to make a difference (or just to make fun of your coworkers).
Essentially, the idea is simple. Code Offsets are a novel way to offset your (or your co-workers') crap code. Like carbon offsets, which aim to reduce emissions of carbon dioxide/greenhouse gases to compensate, or offset emissions made elsewhere, our Code Offsets are used to offset the bad code that already exists.
When you purchase a pack of Code Offsets, the proceeds go to a featured nonprofit group that helps promote good code through education, donations, or open source software.
At launch that organization is TECH CORPS. They are an amazing nonprofit organization dedicated to ensuring K-12 students have equal access to technology programs, skills and resources that enhance early learning and prepare them for college and career.
The Code Offsets themselves are bills that feature some of the most notable characters from the history of computing, the founders of the discipline from Babbage to Hopper.
We’ve designed nine different bills, each offsetting a select amount of bad code. The bills available range from one line, all the way up to one thousand lines. They come in packs so you can keep a few for yourself, but still pass some out to any Paulas around the office.
Also to celebrate the release of the project, we printed up some stickers for the first 1000 orders! (Mainly because Alex loves stickers)
|
Метки: Announcements |
Coded Smorgasbord: Finding a Path |
Readers of TDWTF know all too well that dates are hard. Strings are also hard. You know what else is hard? File paths.
Like dates, and strings, most languages these days have libraries to simplify parsing filepaths. For example, in Python, you can use the os.path module to parse out the directory structure, the file, and its extension without too much effort.
As Chris discovered, though, some people like that effort. Why use things like os.path when youve got Pythons super-powered slice operator for splitting the string apart:
samp = file[file.find('intFiles')+9:].split("/")[0]
fName = file.split("/")[-1]
The second line is the one that pulls off the file name- split into an array, grab the last element- and itll work fine, if not efficiently.
By the same token, the preceding line isnt wrong, its just ugly. It finds the starting point of the string intFiles in the filename, jumps just past it, and then splits on slashes, grabbing the first item. And frankly, what would we have rather the original developer used? A built in function?
Its ugly, but not the worst sin. What if we started with a language that was already ugly? What about Objective-C? Objective-C, especially when used on MacOS or iOS, is an ugly beast that mixes high-level abstractions with low-level APIs, and stubbornly insists on using Smalltalk-style message passing for calling methods of objects.
Pauls team-mate needed to find the file name from the path. Theres a lovely built-in function called lastPathComponent that makes this easy, but again- Pauls team-mate wasnt interested in easy.
+ (__strong NSString*) getFilename: (NSString*) file
{
NSString* Result = @"";
@try
{
if ( [mbUtilis hasContent: file ] )
{
Result = file;
for ( NSInteger i = [file length] -1; i >= 0; i--)
{
UniChar c = [file characterAtIndex: i];
if ( c == '/' )
{
if ( i != [file length] -1 )
{
Result = [file substringFromIndex: i +1];
}
break;
}
}
}
}
@catch (NSException *e)
{
[mbApi logException: @"mbUtilis.getFilename" exception: e];
}
@finally
{
// TODO
}
return Result;
}
This, at least, does a reverse search, walking the string in reverse until it finds a slash. Then it chops off that portion of the string and stuffs it into result. The part that gets me isnt the path manipulation. Its why not just return the result from inside the for loop? Why a break? Why stuff return Result at the end of the function if youre not going to do anything with it?
Those two examples are both clear cases of ignorance-of-built-ins, and theyre a little sloppy and perhaps a bit more cryptic than necessary, but hey, at least theyre not using regular expressions.
Speaking of regular expressions, normally, we think of a persons name as an arbitrary string. There are too many edge cases, too many unexpected characters, too many cultural differences to have a simple rule that says, This is what a valid name looks like.
Stefans co-worker didnt like that line of thought. They wrote a set of regexes that gradually grew to account for more and more exceptions.
public final static Pattern Lastname = Pattern.compile("^[\\pL]+[\\.\\']?((\\-| )*[,\\pL]+[\\.]?)*$");
public final static Pattern Firstname = Pattern.compile("^[\\pL]+[\\.]?((\\-| )[\\pL]+[\\.]?)*$");
public final static Pattern AcademicTitle = Pattern.compile("^[\\pL]+[\\.]?((\\-| )[\\pL]+[\\.]?)*$");
These validations were used to process a bulk-upload of customer data. When a single record failed validation, it wouldnt be saved- and all of the following records would fail silently. This created a number of messes.
[Advertisement] Release!
is a light card game about software and the people who make it. Play with 2-5 people, or up to 10 with two copies - only $9.95 shipped!
|
Метки: Coded Smorgasbord |
That 70's Paper Mill |
The late Seventies was a lucrative time for Finnish-based Kirkniemi Paperi, a paper production powerhouse. Puoval had a great opportunity to cash in on the profits by helping to integrate a completely automated, computer-based production system. His degree in electronic engineering was finally going to pay off.
Thanks to the invention of the Intel 8085 microprocessor, it became possible to turn trees in to paper quicker than ever. Puoval had a mandate from Kirkniemi ownership to spare no expense with getting the system up and running since their biggest competitor implemented a similar system the year before. But if they had a bumpy rollout, it would be incredibly damaging to both the company and Puoval's livelihood.
/creativecommons.org/licenses/by-sa/3.0)], via Wikimedia Commons" href="https://commons.wikimedia.org/wiki/File%3APaper_making_at_Hahnem%C3%BChle.jpg">
The system would have to control paper machines more than a hundred meters long, capable of moving paper through them at 80 kiliometers per hour (which would make for one wicked paper cut). While they were literally well-oiled machines, a small problem with any part of the production would bring things to a halt due to everything being interconnected. When paper-making stops, moneymaking stops and the bosses get angry.
Despite the risk, Puoval was up to the task. He drooled over the hardware he was allowed to bring in to be the brains of the operation. He got to set up a whole army of blazing-fast 6 Mhz Intel 8085's, cages full of in-house built Eurocard logic boards, analog and digital sensors, kilobytes of tight machine code, the whole works. As a fail-safe, Puoval even set up a battery backup system, and line conditioning to prevent a power surge from frying his masterpiece.
It was a long and difficult setup process, but Puoval's brainchild sparked to life and, amazingly, worked as intended right away. The output of the paper mill increased 40% and Puoval's bank account increased 100%. For over a year, it hummed along flawlessly cranking out gloriously large rolls of paper. But then, this feel-good story got beat to a pulp.
Late one night around 11 PM, Puoval's phone rang. On the other end was the panicked 2nd shift manager of the mill. "Puoval! Are you still awake? GOOD! We need you in here ASAP! THE SYSTEM IS DOWN!"
"What do you mean it's down?" Puoval asked back through growing sleepiness.
"Well, the machines were running just fine, then out of nowhere, they just shut off and ground to a halt. Paper went flying off the rolls all over the place. It's like a gang of mummies exploded in here!"
"Ok, I'll get dressed and be in as soon as I can," Puoval sighed, unsure what to expect upon his arrival.
While the 2nd shift line technicians cleaned up the paper disaster, Puoval headed for his control system. He half expected to see it charred and smoking, but everything looked fine. He ran some system diagnostics and nothing looked out of the ordinary other than the sudden cutoff in the logs when everything stopped. He began the lengthy startup process of the system and machines and the mill was back in action.
When the bosses caught wind of the unexplained failure in the morning, Puoval was put on notice that it could not happen again. "Understood. I'm going to give everything a thorough inspection today, and stay late to make sure nothing weird is happening during 2nd shift," he assured the powers-that-be.
Midnight rolled around and everything was still humming along. Puoval decided to head home but made it clear to the manager to call him immediately if even the slightest thing went wrong. Fortunately nothing went wrong that night. Or the next night. Puoval was ready to chalk it up to a one-time freak occurrence. But the 3rd night his phone rang around 11 PM again. "PUOVAL! WE NEED YOU NOW!"
Puoval came in to find the same situation as three nights before. He got everything running again but in the morning the bosses demanded he work both 1st and 2nd shift every day until he had an answer. Two late nights came to pass without a hitch. But when the dreaded 3rd night arrived, he was on high alert. The clock ticked towards 11 PM and he began to sweat. Nothing could go wrong though, as he was watching his beloved system like a hawk.
Just as he was sure nothing would go wrong this day, an innocent-looking cleaning lady strolled up pushing a large commercial vacuum cleaner. He watched her ignore the multiple signs around the cage of his computers that said "DO NOT USE THESE OUTLETS, EVER!" and begin to plug in her vacuum. Puoval sprang at her, shouting to stop.
Not expecting his rapid advance, she had a look of dread come across her face. "But I need to clean?"
"Absolutely not! Not right here! You will bring this whole plant to its knees!" Puoval warned. Upon further explanation, the cleaning lady's behemoth vacuum was a new addition to the fleet. The smaller, economical one didn't draw enough juice to take Puoval's system down. Once this beast was plugged in to the forbidden outlet, which happened to be past the line conditioners, everything came crashing down. At least Puoval found his explanation, albeit a ridiculous one, so that he may retire from 2nd shift.
[Advertisement] Manage IT infrastructure as code across all environments with Puppet. Puppet Enterprise now offers more control and insight, with role-based access control, activity logging and all-new Puppet Apps. Start your free trial today!
|
Метки: Feature Articles |
Error'd: 2,147,483,647 Channels ...and Nothing's On |
"I think it's going to take me a while to catch up on my Radio 4 listening," writes Chris W.
Quentin G. wrote, "So, I need to answer some questions - no problem. Just reply to the no-reply email and...um..."
"Yeah! I can't wait to get my dividend of $N/A on $N/A," writes Aaron L.
Quentin G. also found this job posting that seems to be aimed at someone fluent in Latin. We at TDWTF wish Quentin the best in his job search.
"I'm not sure why TorrentFreak would need to say it so specifically - I'm pretty sure Netflix doesn't like them on any of the social media sites," wrote Manuel A.
Michael M. writes, "Hmmm...that's some tempting bait being dangled in front of my eyes."
"We've just traced the call...it's coming from inside your house!" wrote Tim B.
http://thedailywtf.com/articles/2-147-483-647-channels-and-nothing-s-on
|
Метки: Error'd |
CodeSOD: What A Load |
In the mid-2000s, Amani was contracted to refactor a legacy codebase. He enjoyed breathing new life into old garbage, until the fateful day he came upon something completely unexpected.
One of the webpages he tended to was making calls to a database. Amani couldn't figure out why at first, especially since there were no Ajax scripts on the page. But then he paid careful attention to the CSS details in the webpage's header:
The stylesheet was a PHP file?
Agape, Amani hunted down the file in question and unearthed the horror below:
/* snip */
.popup-yellow .popup-innerHtml {
background-color: #FFCC00;
}
.top-down {
font-size: 12px;
cursor: pointer;
text-align: left;
}
.grid-a {
cursor: pointer;
text-decoration: none;
color: #00C;
}
The progenitor of this hell-born abomination had written PHP to query a database, load the retrieved images in memory, assign them unique IDs, generate unique CSS style classes for each one, then throw them out—every single time the webpage was requested.
Amani replaced this with a single class of style attributes for all images to share, setting widths and heights to auto. He also removed the unnecessary position: relative; attribute, as nothing on the page was being anchored on the elements.
[Advertisement] Release!
is a light card game about software and the people who make it. Play with 2-5 people, or up to 10 with two copies - only $9.95 shipped!
|
Метки: CodeSOD |
Congraubullations |
Java and C# are kind of the same thing, right?
Josh was a Java developer, but his company was doing a big upgrade of some .NET applications written years earlier by a developer named Ray. Ray had left the company the previous year, and somebody needed to help port his .NET 2.5 code to .NET 4.0 and a new version of IIS. Josh was a team player, and also knew that newer versions of .NET were almost always backwards compatible, so he didnt expect it to create that much work for him.
Most of the applications transferred to the new servers without any issues. Most. Of course, the one that didnt transfer was the mission critical package. The ERP system didnt have all the tools the users wanted for manipulating data, so they wanted a tool that could export some records to Excel, where they could edit them, and then reimport the data. The import process was reporting that it was complete, but actually crashed and didnt finish the job (and for bonus points, left the database in an inconsistent state).
Ray hadnt implemented any logging, so Josh fired it up on his dev box and fed it an Excel file. The program cheerfully reported what it was up to at each step of the bulk loading process, displaying a message with a throbber image that turned into a check-mark when that step completed. Despite the crash, every message reported success.
Youre file is on its way!
We have recieved youre file and are procesing it right now!
Almoast done!
Tables are bieng added to teh system.
The system is reading teh table!
Youre procesing is almoast compleeted.
Congraubullations! Youre file has been procesed!
Ugh. Josh had minored in English, and just seeing those messages gave him a headache. He pushed his annoyance aside- this was cosmetic and not directly relevant to the problem at hand.
With a few breakpoints, it only took Josh a few minutes to identify the problem. Rays code was spawning a background thread using the new Thread() syntax, which was one of the few places where .NET 4.0 made some breaking changes with older versions. Josh whipped up a quick workaround and ran it again- everything worked.
With the real problem solved, Josh tracked down the messages. They were hardcoded strings. He touched up the spelling, checked in his changes, and then let QA know there was a fix they could test.
They replied back minutes later: The file gets uploaded now, but the screen hangs on the last step. The spinner just sits there.
Your file is on its way!
We have received your file and are processing it right now!
Almost done!
Tables are being added to the system.
The system is reading the table!
Your processing is almost completed.
Congratulations! Your file has been processed!
That was strange, since hed just seen the code run successfully. Well… before hed fixed the spelling. Could it be? Josh dug through the code that controlled the status display, and found the problem in a file called StatisUpdator.cs.
if (StatisMesages[i].Contains("Congraubullations"))
{
finished = true; //causes the throbber to turn into a check
}
At least Ray is consistent.
[Advertisement] Release!
is a light card game about software and the people who make it. Play with 2-5 people, or up to 10 with two copies - only $9.95 shipped!
|
Метки: Feature Articles |
CodeSOD: An Ant Pushes a Perl |
Its an old joke that Perl is a write only language. Despite some of its issues, back in the early 2000s, Perl was one of the best options out there for scripting languages and rapid-development automation.
Speaking of automation, build automation is really important. Back in the early 2000s, before Maven really caught on, your build automation tool for Java was Ant. Ant, like everything invented in the early 2000s, was driven by an XML scripting tool. Since it was tuned specifically for Java, it had some high-level operations to streamline tasks like generating proxy classes for calling web services based on a supplied WSDL file.
Actually, speaking of code generation, Carrie sends us this code block. Its a Perl script thats called from an Ant build. It runs after generating a class based off a WSDL. It parses Java code using Regular Expressions and injects a ListWrapper class which doesnt adhere to the List contract. But hey, it does have a use strict declaration, guaranteeing youll get errors if you access uninitialized variables.
use strict;
use warnings;
my $dir = $ARGV[0];
readDir($dir);
sub readDir {
my ($dir) = @_;
opendir my $dirHandle, $dir or die "Cannot open $dir.\n$!\n";
foreach my $file(readdir($dirHandle)) {
next if $file =~ m/^\./;
if(-d "$dir/$file") {
readDir("$dir/$file");
next;
}
my %seenFields;
my %multiples;
my $fileName = "$dir/$file";
open IN, "<$fileName" or die "Cannot open $fileName.\n$!\n";
my @methods;
my $file = "";
my $currentLine;
my $containsContent = 0;
while() {
if($_ =~ m/\@XmlElementRef\(name\s*=\s*"(.*?)".+namespace\s*=\s*"(.*?)".+type\s*=\s*(.*?.class)/) {
my $field = ucfirst($1);
my $namespace = $2;
my $class = $3;
$multiples{$1}++;
if($multiples{$field} > 1) {
$_ =~ s/name\s*=\s*"$1"/name = "$1$multiples{$1}"/gis;
$field = $1 . $multiples{$1};
}
my $fieldlc = lc($field);
my $retObject = substr($class, 0, length($class) - 6);
die if not defined $retObject;
my $methodName = $field;
unless(defined $seenFields{$methodName}) {
$seenFields{$methodName} = 1;
my $method = < 4) {
className = className.substring(0, className.length() - 4);
if(className.equalsIgnoreCase("$fieldlc")) {
good = true;
}
}
}
if(good) {
retVal.addWrapped(current);
}
}
return retVal;
}
EOF
push(@methods, $method);
}
} elsif ($_ =~ m/getContent\(\)/) {
$containsContent = 1;
}
$currentLine = $_;
$file .= $currentLine if defined $currentLine;
}
close IN;
if($containsContent) {
print "$fileName\n";
for my $method(@methods) {
$file .= $method;
}
$file .= < extends ArrayList {
private List contentsList;
public ListWrapper(List contents) {
super();
contentsList = contents;
}
public boolean addWrapped(T toAdd) {
return super.add(toAdd);
}
\@Override
public boolean add(T toAdd) {
return contentsList.add(toAdd);
}
\@Override
public boolean addAll(java.util.Collection
|
Метки: CodeSOD |
Mercy the Mercenary in… a Heated Argument |
Last time, Mercy found out the political campaign she was working for didn't have a candidate that was in his best health- but they were pushing him into the governor's mansion anyway. In today's finale, she confronts a hacker and a harsh reality…
Mercy cringed as Ellis waved her over to his laptop. She left her usual workspace next to the hamilton server and headed to where Ellis had holed up. On his laptop she saw a YouTube video, playing one of Rockwoods stump speeches. “We can’t have the YouTube logo on here anymore,” he said, indicating the “Righteous Rants” design. The red and white logo clashed loudly with the Thomas Kinkade-inspired backgrounds Ellis had picked at random from a stock photo site. “Can you make it go away? We can’t be seen to endorse a company like that.”
Mercy could see the bags under his eyes.
“We can’t,” she said. “It’s against the terms of service to hide the YouTube logo from the embedded player. There is a third-party video player that streams YouTube videos, which you can customize all you want, but it only works on browsers with Flash installed.”
“Most people have Flash, don’t they?”
“Not on iOS or Android,” she said. “Just about all of our volunteers use smartphones for voter canvassing and campaign communications. If you switch to Flash only, they won’t be able to watch videos on their phones.”
“So they can just watch TV, then.”
“What about 1824 year olds, all those young people that Rockwood wants to cover their college tuition? They rarely use desktop computers now. If they can’t watch Rockwood’s speeches, it’ll look like we’re purposefully ignoring them.”
At the bare mention of a demographic, Sullivan’s ears perked up and she came over. Mercy again explained the Flash situation.
“Come on, Ellis,” Sullivan said, “the logo doesn’t look that bad. And it’s only for a few more days.”
Ellis’s eyes narrowed, but he soon rubbed them and turned back to his laptop. “I guess you have much more important things to do.”
Mercy felt Sullivan’s fingernails in her shoulder as the campaign manager pulled her away from Ellis. “Just let him be, Mercy. I told you what he’s going through with the boss.”
“He gets away with a lot because of that,” she said. “Fine. I’ll just keep our servers up and running until after the polls close.”
“I hope you’ll stay on after that,” Sullivan said. “Imagine if you were part of our staff in Tallahassee. You’d be invaluable.”
“I need to think about it,” Mercy said, meaning not just the job offer but Rockwood’s diagnosis. Did she really want to work for a governor who was suffering from dementia?
She found her way back to hamilton. On the screen was a black-cloaked, hooded figure, with skeletal arms, floating above a lakeside castle.
“Okay, who put up the Dementor?” Mercy shouted to the volunteers. No one was brave enough to come forward. She closed the image, then checked the logs on the load balancer. hamilton was unresponsive, likely a memory leak, so she triggered a reboot.
But hamilton didn’t boot back up. And Mercy smelled burning plastic.
“hamilton and jay are both out of commission,” Mercy said. Sullivan sat beside her, trying her best to keep up with Mercy’s explanation. “hamilton was the first. I noticed something was off when the load balancer reported that it wasn’t responding to requests. I figured a reboot would fix that. But then it didn’t come back. Just after that, jay did the same thing.”
It was well after hours. The phone operators had left, as no one wanted to hear a campaign call at 10PM. Ellis had escorted Rockwood home. It wasn’t a good day for their candidate, as he had stared listlessly at a wall for several hours, out of sight of their volunteer corps. Although Rockwood was out of it, the campaign was doing gangbusters, inching ahead of Packard in the polls.
But that all could change if their hub went down just a few days before election day.
“I decided to swap out hamilton’s hard drive, as that’s a common point of failure. I opened him up to replace the drive and I saw this.” Mercy spun hamilton around, showing Sullivan the server’s internals. She pointed to a gummy piece of plastic underneath a heat sink. “I smelled burning plastic earlier. That’s the CPU. We don’t overclock it, so that heat sink and the fans should have kept it cool.”
Mercy closed hamilton’s case. “I checked jay, too. Same thing. I thought there might be a recall on those boxes we got. We didn’t exactly buy top-of-the-line rack servers. So I called the manufacturer. There wasn’t any recall, but these CPUs do have a flaw. It’s called a ‘halt-and-catch-fire’ sequence. It’s a manufacturing flaw, a set of instructions that can cause the CPU to overheat.”
“We didn’t accidentally make the CPU do that, did we?”
“No. It’s all instructions that happen in kernel space — the operating system, I mean. Normal software shouldn’t even be able to execute it. Then I remembered something. Earlier today I was working on hamilton when Ellis asked about the YouTube logo. I stepped away for a second. When I came back, there was a picture of a Dementor open in the browser.”
“What’s a Dementor?”
“It’s a Harry Potter thing. I thought maybe one of the volunteers was playing a prank, since I forgot to lock my screen. But I don’t think I did. I think someone used hamilton to plant an exploit on our servers.”
“Well, why did it affect one of the other servers if it was just on that one?”
“I think the exploit copied itself onto the other servers. It specifically targeted our buildout. It used a defect in how Chromium opens images to inject malicious code into kernel space, which copied itself onto the other web servers, that affect only the kinds of computers we bought. So they all have it.” Mercy sighed. “We need to hire some people. I’m really stretched thin on this.”
“We need to keep this quiet, Mercy.” Sullivan frowned.
“Barbie, I can’t fix this on my own.” Mercy hadn’t used Sullivan’s first name since she had begun working on the campaign. She sighed. “I can’t fix this.”
Sullivan took her hand. “You know, with all the staff we have coming and going, I thought it might be prudent to place some security cameras in headquarters.” She pointed to a poster of Rockwood in a corner; one of his eyes had a pencil-sized hole in the pupil, where a small camera could be placed. “If you remember when you saw this demented or whatnot, we could get the footage.”
It didn’t take long to find the culprit on the security footage. A man that neither Mercy nor Sullivan recognized had walked into headquarters, with black hair and black eyeliner. He wore a “Rockwood for Governor” shirt bought from the campaign store, not one issued to volunteers. He wandered through the crowd, grabbed a soda, then sat at the computer for about two minutes while Mercy was talking to Ellis. The footage was low-res, but to Mercy it looked like his fingernails were painted in alternating black and green. He inserted a USB drive into the front of the computer, opened the image of the Dementor, and left just before she got back to the computer.
“God, that’s quick,” Mercy said. “He had to know how we operate.”
“It’s too low quality,” Sullivan said. “We can’t make out his face.”
Mercy had an idea. “Hey, I wonder if he parked in the shopping center.”
“I have a camera pointing outside.” Sullivan switched feeds. This one was pointed through the glass storefront. The glare from the Orlando sun was intense, but they could make out the man walking to a black and green domestic car. She could make out three letters from the car’s license plate.
“I think that’s enough to find him,” Mercy said.
“I’ll call the county sheriff.”
“No, wait. You said we should keep this quiet. If the cops show up, Ellis will know what’s going on, and the media could pick up on it. I don’t know how long it could take for the other servers to, well, melt down. You need to get Ellis to put our code up on Seashell Hosting, like we discussed a while ago. We can’t keep managing it here, and this is proof. But I’m going to track him down myself.”
Sullivan guffawed. “What, are you a bounty hunter or something?”
“I have some good friends,” Mercy replied.
Mercy called an ex-girlfriend who worked at the Orange County Sheriff’s Office, who was more than willing to help. She gave Mercy the culprit’s address. He lived in a white stucco apartment complex in Kissimmee. The walls of his apartment building were stained brown from rusty sprinkler water. She found his apartment number, banged on the corrugated metal door.
He answered. His hair was nearly black, he was wearing black eyeliner, and he wore a Slytherin t-shirt and boxers.
“I know you did it,” she said.
A flash of recognition showed on the man’s face. He hid it with a fake smile. “I have no idea what you’re talking about,” he responded, in an affected British accent.
“Ever heard of surveillance? Stupid Slytherin, 10 points to Ravenclaw. Let me in and I won’t call the cops.”
The false bravado left his face, and he opened the door for her. She stepped inside, noting that he was more than just a casual fan of the Harry Potter books. From the movie posters on the walls, to the many collector’s copies of books on his shelves, to a framed photo of Helena Bonham Carter by his bed.
“A Dementor?” Mercy asked. “Seems pretty obvious.”
“It’s a calling card.” The man sat at his computer desk, squirming.
“Are you working alone?”
“I’ve been paid for my discretion.”
Mercy pulled out her phone. “Is it enough to cover bail?”
The man held up his hands. “Fine, it’s Packard.”
Mercy pocketed her phone. “Okay. What’s the fix?”
He giggled. “There isn’t one. I mean, maybe if it weren’t some web developer like you. Yeah, I looked you up on LinkedIn before I stopped by your headquarters. You put together that little cheap server farm yourself, I’ll bet. No, there’s no fix. Shutting down the hardware triggers the HACF sequence. Packard didn’t want everything down at once, because you people would know something was wrong and start digging. But I figure you’d apply rolling updates to each server, rebooting each time. Each one would fail, and you wouldn’t be able to guess why.”
“No fix? I don’t have time to talk to you, then.”
“Hey, could I get your number—“ the man said, the clanging of his front door drowning out his voice.
“We’re done for,” Mercy said, getting back to headquarters an hour later. She explained the situation to Sullivan, who was at headquarters, and Ellis, who was out with Rockwood on speakerphone. The servers would need to run flawlessly until election day. If they didn’t — if they required a software update or a memory leak forced Mercy to turn any of them off — they’d melt. “We need hosting. I mean it.”
“Absolutely not,” Ellis said. “The boss is adamant.”
“You have no idea what’s going to happen if”
“I have work to do.” Ellis hung up.
“Mercy, please.” Sullivan rubbed her temples. “Just & do what you can to keep the servers going. It’s only for a few days.”
Mercy considered her options. One: she could do her best to keep the servers up, and watch as they failed one by one, until election day came and there was nothing else that could be done. Two: she could buy more servers as others failed, but that could get expensive, not to mention tedious. Three: she could migrate everything onto Seashell’s safe hardware tonight, and risk Ellis’s wrath.
In the end, Rockwood, a man who couldn’t remember a conversation he had five minutes ago, wasn’t worth it.
“I’m moving the code to Seashell,” Mercy said. Her stomach felt heavy. “I’m leaving the campaign as soon as it’s done.”
Sullivan sunk into her chair. “I won’t stop you. I won’t stop you moving the code, and I won’t stop you leaving. I know it’s your choice.” She smiled wanly. “And Ellis won’t have any idea how to get the code back onto those servers, so it’ll stay running until after the election’s over.”
Mercy made the call to Seashell Hosting. Despite the late hour, they were excited about hosting Rockwood’s campaign and offered affordable rates. In a few hours she had transferred everything to their servers: the database, the code, their internal files. After that, she asked a technician to restart their virtual server, in case some rack-mounted unit suddenly melted. Nothing happened.
After she grabbed her things, she shook Sullivan’s hand. “I’ll keep in touch,” the older woman said.
Mercy drove home.
At her apartment, she turned on her laptop. She played the stump speech Rockwood gave in Stoneford, the one responsible for his meteoric rise and her own time with the campaign, one that would soon see him in the governor’s mansion in Tallahassee. She didn’t pay attention to the words this time. All she could see was a scared old man, desperately improvising to hide the fact that he couldn’t remember what he was doing. In the beginning, Mercy thought he was brilliant. But in the end, he simply had been making it up the whole time.
http://thedailywtf.com/articles/mercy-the-mercenary-in-a-heated-argument
|
Метки: Feature Articles |
Error'd: What Happens in Massachusetts... |
"I came across this while submitting to a background check for a new job," writes Jay S., "Good to know that felonious behavior in Boston is perfectly acceptable."
"You know, I'm fairly sure that wasn't my friend Christine's last name," wrote Vivia.
"Deliveroo seems to think a couple of burgers are not really adding up to the minimum order," writes Joao M..
"I got an email stating that it was time to upgrade my work computer and had to fill out an online form stating if I approved or rejected the planned upgrade," writes Angela A., "When I submitted the form, this was the response."
"Obviously a problem with one browser means you need a different login link with totally different credentials for a different browser!" wrote Jeffrey.
"Home Depot's self checkout is still wary about accepting any credit cards," Jared wrote, "Too bad I left my dynamic linked libraries in my other pants."
"This was seen on the high street in Bury St. Edmunds," writes Gary, "Normally, I wouldn't care but it's been stuck like this for a fortnight!"
http://thedailywtf.com/articles/what-happens-in-massachusetts
|
Метки: Error'd |
CodeSOD: Interned Sort |
Caleb scored his first intership at a small, family-owned print-shop. Much to his surprise, the day before he started, their primary web-developer left for a bigger, more lucrative job. His predecssor was an experienced programmer, but came at solving problems in his own unique way. This meant no comments, no functions, no classes, SQL injection vulnerabilities everywere, and cryptic 500-character one-liners stuffed into the value attribute of an input tag.
Caleb spent his first day just trying to get the code running on his dev machine. On the second day, he sat down with a more experienced co-worker to try and understand some of the queries. For example, there was one query that needed to return product details sorted in some meaningful fashion- like by name. Weirdly, though, the page wasnt sorting them by name, except when it was- no one who used the product search understood the sort order.
Cabel dug in, expecting to see some variation on this:
SELECT `id`, `name`, `description`
FROM products
WHERE `name` LIKE '%{$keyword}% '
ORDER BY `name`;
Instead, he saw this:
# $keyword is a PHP variable that was interpolated into the concatenated PHP string.
# It is the search term the user entered, preserved here for clarity.
SELECT T1.product.id AS product_id, T1.slug, T1.name, description, details, T2.media_id, url, T1.order
FROM (
SELECT product.id AS product_id, slug, name, description, product.details, text
CASE
WHEN name LIKE '$keyword' THEN 0
WHEN name LIKE '$keyword%' THEN 1
WHEN name LIKE '%$keyword' THEN 2
WHEN name LIKE '%$keyword%' THEN 3
WHEN product.details LIKE '%$keyword%' THEN 4
WHEN description LIKE '%$keyword% ' THEN 5
WHEN text LIKE '$keyword' THEN 6
WHEN text LIKE '$keyword%' THEN 7
WHEN text LIKE '%$keyword' THEN 8
WHEN text LIKE '%$keyword%' THEN 9
ELSE 10 END
AS `order`
FROM `product_option`, `product`
WHERE `product_option`.`product_id` = `product`.`id` AND product.parent_id=0 AND (
name LIKE '%$keyword%' OR
description LIKE '%$keyword%' OR
product.details LIKE '%$keyword%' OR text LIKE '%$keyword%'
)
ORDER BY `order`, name
) AS T1 LEFT JOIN (
SELECT * FROM product_media WHERE product_media.order = 1) AS
T2 ON T1.product_id=T2.product_id LEFT JOIN media ON T2.media_id=media_id
)
He sat down with a more experienced developer, trying to understand what on Earth this was supposed to do. In the end, they couldnt figure it out, so they just replaced it with the straightforward ORDER BY name, and left some TODO comments confessing they dont know what they just replaced.
Calebs boss stopped by after they released this change, complimenting him on how much better the product search page worked.
[Advertisement] Release!
is a light card game about software and the people who make it. Play with 2-5 people, or up to 10 with two copies - only $9.95 shipped!
|
Метки: CodeSOD |
Twisted Branches |
David pulled his headphones off when he heard a loud harrumph behind him. One of his project managers loomed in the doorway, and had obviously been standing there for some time, trying to get Davids attention.
You pulled from Staging-Core branch into the Version2 branch and broke Liams changes, the PM said.
David wracked his brain, trying to remember this particular PMs name. Hed met so many during his short time at this company that he couldnt keep them straight. Uhh… we just had a release, right? Since I was working in Version2, I pulled the latest version in. I thought I was the only one in there on this project right now…
The PM shook his head. I dont know how you did things at your old job, but here weve got policies and procedures. This isnt some tiny startup- weve got a dozen developers in this office, fifty more in India, another dozen in Mexico, and nearly a hundred testers. Ill send you a meeting invite so we can discuss…
The PM wandered off, mid-sentence, but was instantly replaced by another. This one David recognized- Lisa or Linda or Lindsey or something. Liam tells me youre breaking branches in our code control system, she said. Im not sure how things worked at your old job, but this isnt some tiny startup. Our codebase is over 1.2 million lines of code. Ill send you a meeting invite so we can discuss…
Over the next quarter of an hour, David was visited by the ghosts of project management past, present and future, each with dire comments about Davids ability to follow policy and the promise of a follow-up meeting. By mid-afternoon, his calendar for the next week was filled with meetings.
A normal organization might do work in individual feature branches and when a feature was complete, theyd migrate those changes back to the root or trunk branch for release. People working in other feature branches should, at some point, pull those changes down into those branches. When and exactly how that happened was a possible topic of debate, but Davids new workplace wasnt interested in a debate.
You simply dont pull changes down into lower branches. Ever.
David sat at a conference table, surrounded by project managers he didnt recognize.
Thats why we have a Changes Under Merge team, one of the PMs explained. Its for safety. Changes made by developers stay in one branch, and the Changes Under Merge team move them back up the tree, following the Change and Release Approach Policy.
If David needed changes synced between branches, he needed to work with the Changes Under Merge team, which was a four-person group who understood how the 20+ branches in their codebase related to each other. If, for example, David needed a feature merged in, hed need to look up all of the changesets that were used to create that feature. Hed then send them- as an Excel spreadsheet- to the Changes Under Merge team. Someone from that team would then cherry-pick just those changes and use TFSs baseless merge tool to pull those changes into his branch.
Conversely, when he had a feature ready to go, he wouldnt merge it up the tree. Hed compile a list of changesets and pass them off to the Changes Under Merge team, which would then pull the changes from his branch into Integ-Core, for integration testing by QA (there were no automated tests, because, as one of the PMs put it, Automated tests only test your automation. You need real humans for real tests.). Once the feature passed Integ-Core, the QA folks would request that the changes get merged into Strategic-CombRes, using the same cherry-pick and baseless merge approach. From there, the finished feature entered a twisty labyrinth of project management processes that David didnt need to worry about. His feature would hop around the various Strategic Branches for awhile, and someday, maybe, make it back up into the Production branch.
David took his scoldings, did his best not to roll his eyes, and got back to work when the project management machine decided that hed been punished enough. For the next six months, he basically ignored everything he knew about branches, and just rigorously tracked his changesets so that he could pass them off to the Changes Under Merge team. Eventually, he started to hear whispers- a major release was coming, and everyoned need to put in some extra time to make sure it went off without a hitch.
Lisa/Linda/Lindsey descended on his cube on the eve of the release. Now, since this is your first major milestone, she said, I wanted to stop by and review whats going to happen. Youre going to get a list of changesets from the Changes Under Merge team. You need to look at the latest version of the Production branch and verify that all of your changes are in there. And no, you cant just look and see if the changeset IDs are in there, because sometimes changes get overwritten by later changes. Youll need to manually verify every line youve written. Youve got two hours.
This was six months worth of work. David didnt even know where to begin with verifying every line hed written. And in only two hours? It was impossible. Instead, he focused on spot-checking the release while wishing hed been allowed to write some automated tests around his features. So far as he could tell, everything looked okay, so he signed off on the release.
The release crashed and burned. Since the company didnt have a backout plan, and since their branching structure was convoluted, they couldnt simply pull the previous version out of source control and redeploy it. Instead, every developer pulled the latest version of the Production branch and worked until 2AM trying to patch all of the problems in it.
There were a lot, and when the blamestorming session finally came around, several project managers were pointing their fingers at him. You said all of your changes were in the final product, but it looks like Liams changes overwrote some of your changes. We need people that are going to follow policy. We need people who show real diligence. We dont think this organization is the right fit for you.
It wasnt until he was 45 minutes into the meeting that David realized he was being fired. He wasnt entirely certain that all of the PMs realized it either, because a few of them kept the meeting running. Obviously, one of them said, while David was at fault, this problem is also a management problem. We need to expand the management team so that we can avoid these problems in the future. And since our headcount just shrank…
|
Метки: Feature Articles |
CodeSOD: See You Last Saturday |
One of the more difficult things for beginning programmers to pick up is computer-minded thinking. Sure, if you're reading this, it's probably easy for you to look at a system and plot out how to get the outputs you want in one area out of the information you have in another. For someone who's been programming for years, it's practically second nature. When mentoring interns or teaching beginners, however, it can readily become apparent just how strange this mindset can be to newcomers.
We don't know this date-parsing code was written by a newbie ... but we have our suspicions:
/**
*
* @param date
* @return
* @throws Exception
*/
public static Date getPreviousSaturDay(Date date) throws Exception {
Calendar calendar = Calendar.getInstance();
Date saturday = null;
if (date != null) {
calendar.setTime(date);
int day = calendar.get(Calendar.DAY_OF_WEEK);
if (day == Calendar.SATURDAY) {
calendar.add(Calendar.DATE, 0);
} else if (day == Calendar.SUNDAY) {
calendar.add(Calendar.DATE, -1);
} else if (day == Calendar.MONDAY) {
calendar.add(Calendar.DATE, -2);
} else if (day == Calendar.TUESDAY) {
calendar.add(Calendar.DATE, -3);
} else if (day == Calendar.WEDNESDAY) {
calendar.add(Calendar.DATE, -4);
} else if (day == Calendar.THURSDAY) {
calendar.add(Calendar.DATE, -5);
} else if (day == Calendar.FRIDAY) {
calendar.add(Calendar.DATE, -6);
}
SimpleDateFormat simpledateformat = new SimpleDateFormat(
DateUtil.MM_DD_YYYY_DATE_PATTERN);
saturday = simpledateformat.parse(simpledateformat.format(calendar
.getTime()));
}
return saturday;
}
No javadoc other than a placeholder the IDE probably generated? Bizzarely-cased method name? Throwing a generic Exception? These are all signs of someone without a firm grasp on the language, but possibly not a total newcomer to programming. After all, someone who's only done hobby work in loosely typed languages could make all the above mistakes. The real hallmark is the strange, twisty path the method takes to get from point A to point B.
Starting with a Date, the method aims to return a Date that represents the previous Saturday. With JodaTime (or Java 8's new Time library, which is essentially the same), this is a simple task: date.withDayOfWeek(DateTimeConstants.SATURDAY) will get you the nearest Saturday, and from there it's a simple comparison to see if you need to subtract a week. But this uses the famously terrible Calendar library that has plagued Java for decades, which means you have to have a firm grasp on what you're doing in order to work with it successfully.
Still, the mistakes made aren't related to the date library, but to a fundamental lack of understanding of the task at hand. Stating with a Date, they turn it into a Calendar and get the day of the week the input represented. They then use an if-ladder to manipulate the Calendar, subtracting the right number of days. Then, at a loss for how to turn the Calendar back into a Date, they extract the Date from the Calendar, run it through a formatter to turn it into a string, then run that string through a parser to get a Date.
What?
Unfortunately, this wasn't a school project or some other learning exercise. This was found in production code.
|
Метки: CodeSOD |
Mercy the Mercenary in… The App Store |
We return with the penultimate installment of the tale of Mercy, the Mercenary Developer. Last time, she implemented a countdown clock- but nobody told her what it was counting down to, because nobody knew.
It was standing-room only at Rockwood for Governor campaign headquarters. All the tables had been pushed to the walls or folded and stowed away; most of the chairs were stacked. Volunteers milled about, eating delivery pizza, wings, and (probably spiked) soda.
Mercy and Sullivan, two of the few people who got chairs, sat close to the widescreen TV set up near the phone banks. It was tuned to a local network, broadcasting a feed from USF, a couple hours down I4 from headquarters.
The first Florida gubernatorial debate had started merely five minutes ago, and already things were testy.
“This is a question from Facebook,” said Carson Cooper, the moderator. “It says: ‘I am concerned that Florida will keep municipal broadband and Google Fiber from taking root in the state, while big cable interests operate without competition. How would you address the need for better practices in the cable industry?’ Packard, we’ll start with you.”
Packard gave his response. “I think we ought to protect the interests of American companies, Carson. And that means standing behind our friends in the telecom industry, and keeping government out of the internet business!”
“Rockwood, your response?”
“We briefed him on this,” Sullivan whispered to Mercy. “He just has to say his lines.”
Their candidate gave his most confident smile. “I don’t know if Packard has ever had to look at a cable bill in his life.” Laughter from the volunteers. “My real-estate clients have all told me how expensive it is to get cable, to get internet. The gigs are too much, Carson, too much.”
“Oh, no,” Sullivan whispered. “It was ‘the fees,’ not the ‘gigs.’ He sounds like a roadie.”
Mercy cringed. “He should have just said cable internet is too expensive.”
The democrat, Hewlett, waffled through a non-response. After he finished, Packard focused his attention on Rockwood. “For a real estate developer who’s made his living flipping houses, you suddenly know a whole lot about how the telecom industry works.” The TV audience laughed, but the boos from the volunteers drowned it out. “Tell me one thing, Mr. Rockwood. What is one forward-looking innovation that you, your company, or your campaign has launched? Because I can name at least a dozen at the pharmaceutical firm I founded.”
“I agree,” said Hewlett, hoping to get any kind of airtime between Rockwood and Packard.
Rockwood got that glassy look in his eye again, which Mercy had noticed more often since the “countdown clock” incident a few weeks ago. There was something off about Rockwood whenever he got that look. It lasted three whole seconds; next to her, Sullivan had balled her hands into fists.
“Rockwood, your response?” Carson Cooper said.
Rockwood snapped out of it. “I’ll tell you something, Packard. Now I’m sure you’ve made some big improvements to whatever diet pills you manufacture in big pharma, but here’s something that will affect all Floridians. You know how hard it is to understand tax code? I don’t know if you’ve ever seen a return in your life, I mean with your own eyes. Well, our campaign has laid out a revised tax code for Floridians. Lower sales taxes for everyday goods. Fair and proportional property taxes. And a non-income profit tax that only affects the wealthiest Floridians & which includes you, I’m not sorry to say. Tomorrow, we’re launching a new mobile application that tells you exactly how much more you’ll owe. And for most Floridians, that number will be zero.”
The volunteers applauded, drowning out Carson Cooper’s voice. Meanwhile, Mercy’s stomach did a somersault. “A tax code app? Tomorrow?”
“I do believe that’s the first time he’s mentioned it,” Sullivan replied.
“Did he just make that up on the spot?”
“Well, it can’t be that hard, can it? Just like building a website.” Sullivan faked a gracious smile.
“You have no idea.”
“This is how hard it is to launch a new mobile app in a day,” Mercy said. She, Ellis, and Sullivan had gathered after the debate in the conference room. Rockwood was off to St. Petersburg and Tampa for some barnstorming after his performance, which the media had characterized as “fresh” and “unpredictable,” not terms they used in a complimentary fashion. “I could do it in a week. I can’t do it in 24 hours.”
“We don’t have a week,” Ellis said. “John said we’d have it up in 24 hours. That’s what we have to do.”
“You know what, Ellis, Sullivan snapped, Maybe you should let the one who’s actually going to build the mobile app tell us how it can be done.”
“Well, I’ll go get Rockwood as soon as his stump speech is done and I’ll tell him. You’ll see how he likes that kind of news.”
“Look,” Mercy held up her hands, “do you want to hear what I have to say or not?”
Ellis and Sullivan quit squabbling.
“Here’s what has to happen. I need to build it first. I can use PhoneGap — it’s a framework that uses HTML, so it’s like a web page inside an application. I’ll need the campaigns tax reform policy written up.”
“Uh, we don’t have that yet,” Ellis said.
“Do you need it?” Sullivan asked. “Could you just build the application and put it in later?”
“It’s a tax policy application,” Mercy said, her voice cracking. “There’s no application without knowing how the new taxes will work. That’s the whole point.”
“I’ll get something tomorrow morning,” Ellis conceded.
“I can build most of it out tonight,” Mercy said. She reminded herself to buy some energy drinks on the way back to her apartment. “Tomorrow I’ll make changes to the algorithm based on our new tax policy. We won’t have much time for testing, so I’ll get some volunteers to help.”
“Great, we can get it built by tomorrow afternoon,” Ellis said. “It’ll be done in 24 hours.”
“No, it’ll be built in 24 hours,” Mercy said. “It won’t be live in 24 hours. It still has to get on the Apple store and Google Play.”
“So, can’t we just make an account and put it up?” Sullivan asked.
“Apple takes at least a week to approve an app. If youre lucky, and we’ll be a new publisher with no prior releases. They’ll drag their feet.”
“Okay, so we make some phone calls,” Ellis said. “Can’t be that hard.”
“Have you ever tried to call Apple? I mean, not just tech support.”
“Look.” Ellis steepled his hands on the table. “It’s going to happen. You’re going to find a way to do it. End of story.” Without even a dismissal, Ellis left the room.
“What’s his deal? Was it the debate?” Mercy cracked her knuckles. Her wrists already hurt from the arduous typing they’d endure tonight.
“I can’t talk about that, honey,” Sullivan said, leaving the conference room.
By 4AM she had a working prototype of the application. It took a user’s gross income, property values, etc., and spit out a dollar amount, based on what she knew about Florida tax law. Mercy figured the campaign’s tax policy wouldn’t be very complicated, either adjusting individual percentages on specific values, fiddling with the base percentage, or some combination thereof. She headed back to the office to be ready for when Ellis could get her their tax policy platform language. She took a nap, sitting next to the web server hamilton.
Around 8AM, a hand shook her shoulder. It was Ellis. He shoved a piece of paper in front of her. “Here’s what we came up with a few weeks ago.”
It was a 17-circle Venn diagram. Arrows were drawn from circle to circle around the circumference, making it look like a giant recycling symbol. Houses, boats, and other property icons dotted the diagram. There were no numbers anywhere on it.
Mercy said as much to Ellis.
“Look,” Ellis said, “The actual property rates and percentages won’t actually change. Just the way they’re calculated. Just make it look like it’s saving our constituents money. The actual tax laws will get worked out in the legislature after Rockwood’s elected.”
Mercy rubbed her eyes. She started redrawing the Venn chain link into an algorithm flow chart, then crumpled that up, adjusted a few values in her own algorithm, and prepped for QA.
Mercy was struggling to keep awake as two volunteers, a brother and sister attending UCF, tested on an iPhone and an Android tablet respectively.
“Whoa, hey, those boxes showed up again,” the brother said. He handed Mercy his iPhone.
“It’s the stupid glyphicon font. I must have moved the files by mistake.” Mercy dug through her codebase, double-checked the font locations and her font-face CSS declarations, and recompiled. She pushed the new package to cato, the intranet server for the campaign, and brother and sister re-installed their apps respectively.
“Looks good on mine,” the sister said. The brother nodded in agreement.
“Okay, thanks.” Mercy yawned. The app was mostly bug-free — or as bug-free as she could make it in just over 12 hours — and ready to ship. While she had been finishing the app, Sullivan had set up accounts on Google Play and the Apple Store. Mercy logged into the Google Play account, uploaded the Android installer, and hit Publish. That would be the easy part.
But getting Apple to play along would be harder.
She put the iOS installer into the campaign account, then tagged it for review. An email came back, with just what she expected: it would take nearly a week for Apple to respond.
Meanwhile, Rockwood was coming back from his barnstorming in Tampa and St. Petersburg, and would want to see the app in action when he arrived around 6PM. Six hours left.
Against her better nature, Mercy scoured her LinkedIn connections. She had made numerous contacts at local conferences. Surely someone worked at Apple, someone who could pull a few strings in the review process. As she searched, her eyes began to close. She felt as though she were falling out of her chair, and she jolted awake.
There wouldn’t be anyone she knew, and besides, she didn’t have the money to bribe anyone to speed up the process. She headed for the conference room. “Wake me in a couple hours,” she told Sullivan. Inside, she rolled up a sweater for a pillow, locked the door, shut off the light, and went to sleep.
Sullivan’s knocking woke Mercy. She checked her phone. It was 5PM.
“When’s he getting here?” she said, her voice muffled.
“He’s on his way from the airport,” she replied. “Ellis has already called and said you couldn’t get the app finished.”
Mercy groaned. “It’s done, it’s just not on the Apple Store—“
Mercy realized it didn’t need to be. A few iPhone and iPad owners unlocked their devices, allowing third-party apps to run on them. She could just put a “beta” of the application for download on their site. Only jailbroken devices could run it, but she could say she released the app in the 24-hour window Rockwood wanted.
She dragged herself out of the conference room, head pounding from an enormous caffeine withdrawal. She slumped in front of hamilton, logged onto the campaign blog, and wrote a post. “Download Rockwood’s Tax Code App Here!” the post said. At the bottom was a link to the iOS installer, which she had copied to the public servers. She made it clear it was a beta release, and that as soon as it hit the iOS store it would no longer be available. But it was published, and just in time.
Sullivan met Rockwood as he came in the door, before Ellis could get a chance to talk to him. “The tax app is up on the web!” she said. “We got it done.”
“Taxes? I released my tax returns months ago,” he said, chuckling.
Ellis sandwiched himself between Sullivan and Rockwood. “Let’s get you situated,” he said, ushering the candidate through a few loitering volunteers. Rockwood put on his best smile, but seemed like he didn’t know where he was.
“I’m gonna sleep for three days,” Mercy said to Sullivan, as she left headquarters. But Sullivan followed her out to the parking lot.
Sullivan began, “I should really tell you“
Mercy said, her voice short, “I don’t have time“
“John has non-Alzheimer’s dementia.” Sullivan’s usual southern tea-sweet tone was gone. “He was diagnosed just after he announced his campaign. I first noticed the symptoms a couple years ago. He’s lucid most of the time, but he’s having a lot more episodes recently. Ellis and I are basically running things until John gets better. You’re the third person to find out.”
“After you and Ellis?”
Sullivan nodded. “Please keep this to yourself. It’ll kill his chances if—“
“I can’t deal with this right now,” Mercy said. “I’m taking the next few days off.” She got in her old Honda and drove home. When she got there, she turned off her phone, covered herself in three blankets, curled up, and slept.
[Advertisement]
Otter, ProGet, BuildMaster – robust, powerful, scalable, and reliable additions to your existing DevOps toolchain.
http://thedailywtf.com/articles/mercy-the-mercenary-in-the-app-store
|
Метки: Feature Articles |
Error'd: Paula Lives |
"While poking around on my brand new Galaxy S7, I was tempted to pick one ringtone in particular," writes Ronon D..
Jerry L. wrote, "Well, using 'comment' solves half the problem."
"Does this guy really show up at anything non-Hillary, or is this just the result of WaPo photo staff budget cuts?" asks Mark R.
Scott S. writes, "Is Microsoft trying to warn me that I won't get 'Jacked' up on this iced coffee? Or that the 'chikn' is a bit fowl?"
"Java may still have its little problems and misconceptions, but for this job, the duties are pretty low impact," wrote Billy B.
"While trying to register on Honeywell's support site, I came across an interesting conflict of abbreviations that is apparently driven by unique keys not being applied across multiple columns of the database," Phil S. writes, "But my registration was successful anyway?!"
"I hear it's just as good as the brand that inspired its name," Ergin writes, "In fact, it's got quite a kick! (just make sure you have your 'safe word' handy)"
|
Метки: Error'd |
Coded Smorgasbord: Mysterious Mysteries of Strange Mystery |
Code is a window into the programmers mind. Our thought processes are laid bare, exposed and cemented for all eternity in keywords and symbols. Its left there, waiting for another programmer to come by and wonder: What were they thinking?
Thats exactly what seebs was wondering, when he found this PHP code.
function startsWith($haystack, $needle) {
// search backwards starting from haystack length characters from the end
return $needle === "" || strrpos($haystack, $needle, -strlen($haystack)) !== FALSE;
}
function endsWith($haystack, $needle) {
// search forward starting from end minus needle length characters
return $needle === "" || strpos($haystack, $needle, strlen($haystack) - strlen($needle)) !== FALSE;
}
Now, the normal solution here would be to look at the length of your needle and chop off that many characters from the haystack using substr, then compare the two strings. Using strpos and strrpos is odd, but not half so odd as comparing the result to FALSE instead of zero.
While I was checking on PHP starts/ends-with functions, I did figure out where this code came from. Its the most popular answer on StackOverflow, showing us another case of programming by copy paste.
Etta overheard some co-workers talking about issues with the Entity class. That was exciting, since their business objects were a mess, and Etta was excited about the thought that they might build some classes that were business objects that represented a single entity, which would be a change of pace.
Instead, Etta found a 4,000 line Entity class that was actually a God Object with every feature and function crammed into it. But it was even worse than that.
public class Entity
{
// 4000 lines and 3 inner classes later
public string getFirstOpenApptHtml(final CSREntity csr) throws Exception
{
final StringBuilder sb = new StringBuilder();
sb.append("Appt.: ");
// add 300 more lines of stuff to the string builder
return sb.toString();
}
}
There are a few fun things about this method. First, theres the obvious: it uses a StringBuilder to construct HTML, JavaScript and CSS to inject into the page body. Thats pretty ugly. Do you see that input parameter, CSREntity? Thats actually a class that inherits from Entity- yes, this method is written to accept a parameter of its own time, and in fact, its usually called by running csr.getFirstOpenApptHtml(csr);
Finally, Jess was wondering, What if I needed to sort a list of integers? Could I use the built in functionality, or is there a better way?
Actually, Jess wasnt wondering that at all. But a co-worker apparently was.
namespace MyCompany.Utilities
{
using System;
[Serializable]
public class Integer : IComparable
{
private int _value;
public Integer(int value)
{
_value = value;
}
public int Value
{
get
{
return _value;
}
set
{
_value = value;
}
}
public int CompareTo(object obj)
{
if (obj is Integer)
{
Integer integer = (Integer)obj;
return _value.CompareTo(integer._value);
}
else
{
throw new ArgumentException("Object is not of type Integer");
}
}
}
}
For the unfamiliar, C# and all the .NET languages autobox primitives, and integers already implement the IComparable interface, making this code 100% redundant. The code was also 100% unused, and had never been used- despite being the first check-in to the codebase.
http://thedailywtf.com/articles/mysterious-mysteries-of-strange-mystery
|
Метки: Coded Smorgasbord |
Enterprise Automation |
Rex had just been hired on with a large retailer as a Puppet Automation Engineer, tasked with using Puppet Labs to automate deployments of some SAP-py, enterprisey software. He was paired up with another Puppet Automation Engineer, Alexi. Alexi was the expert, and he was in charge of automating the companys Sarbanes-Oxley (SOX) auditing.
Alexei was a firm believer that the Customer Is Always Wrong, and Alexei Knows Best. As a consequence, he thought that any requirements he didnt like could be changed to arbitrary ones he did like. If the customer wanted a report that provided some summarized sales numbers for the year and he thought that was stupid, hed instead give them a report showing their top products Line-Of-Code count divided by the Dow Jones Industrial Average for the month. If they wanted to slice-and-dice their customer database by demographics, he would code up a line graph relating the number of characters in their last name to the average nightly lows on their date of birth.
This caused huge problems with the SOX auditing. As he worked on the requirements-not generated by users, but dictated by US law- Alexei replaced stupid ones with his own expert ones. After a chain of angry emails, angrier phone calls, and downright apocalyptic meetings, management finally got Alexi to deal with the actual requirements. Exactly as written.
Exactly. As. Written.
From what Rex could see, much of ALexis implementation was deliberate malicious obedience. For example, many rules were given the same name, causing their auditing engine (which ran through the rules in alphabetic order) to give varying and nondeterministic results as the rules were run in a different order each time, often overwriting each others output.
What really amazed Rex was the incident that finally convinced his coworker to leave. Alexei was automating another piece of enterprisey software deployments- Initechs SalesManagerPoint- with Puppet, using an existing (and broken, unsupported and officially deprecated) module designed specifically for their case. When the module didnt work, Alexei doubled-down and tried to fix it, adding layer upon layer of expert complexity, meanwhile ignoring key requirements because The module doesnt support that!
Frustrated, management brought in a Highly-Paid Consultant, named Harry. Harry was intimately familiar with Puppet Labs, and within a few days, proved the point by fixing many of their automation-pain-points. Everything was great, until Harry discovered Alexeis work. Harry was also familiar with Initechs SalesManagerPoint. Thats a very tricky one. I can take a quick glance at it, but we normally will not touch that without a minimum six-month contract.
As soon as the words were out of his mouth, Rex stopped paying attention to his work, and started paying attention to Harry and Alexi. Their disagreement escalated into a hilarious shouting match. Harry tried to tell Alexi he was using Puppet, the module, and SalesManagerPoint all the wrong way, to which Alexei would respond with screams of But your so-called right way is stupid! My way is better!
Alexei was angry enough to quit on the spot and Rex inherited his work. Harry refused to go anywhere near anything Alexi had touched without renegotiating the contract. After reviewing Alexis work, Rex decided on ignoring it completely and built up a new system from scratch. Several months later Rex had a working Puppet automation that actually met all the customers requirements, without using Alexeis work and without using the broken Puppet module. No expert required.
|
Метки: Feature Articles |
CodeSOD: And It's Collated |
As anyone whos ever written a c-style char * string knows, strings are much more complicated than they look. This is even more true in this modern era of Unicode and character encodings and multilingual applications. How does "a compare to a or 'a?
John Moores company sent some code to a contracting firm. They needed to strip off any diacritics and unusual characters when they were comparing strings, so that "a and a were treated as the same character when searching- a not uncommon problem. In Java, theres a special family of classes inheriting from Collator which can be used to solve exactly that problem. Now, most developers arent deeply familiar with these, so seeing a contractor that turns in a more home brewed approach is hardly surprising.
This approach goes above and beyond. It starts out bad, but not horrible: convert the string to their character codes, and then look at each one. What follows is a textbook example of why you dont write gigantic if-blocks using magic numbers as boundary conditions, including this gem:
if (index == 292 && index == 294) {
resultCharacterIndexes.add(68);//H
}
Yes, they only convert to a 68 (the letter H) when the index character is both 292 and 294, which may
|
Метки: CodeSOD |
Mercy the Mercenary in… The (not so) Final Countdown |
In the continuing saga of Mercy the Mercenary, she continues to struggle with a political campaign- Rockwood for Governor- and its backwards approach to IT. Last time, she had an uphill battle getting the kit to keep their website up.
The request seemed so simple, Mercy knew. Embed a video inside an email message.
“I’m not saying it’s hard,” she said. “I’m saying it’s impossible.”
“The boss wants it to happen,” Ellis said. “And that means—“
“That means we trust her judgment,” Sullivan interrupted. “But why don’t you try telling us why it can’t happen, Mercy? You can use kindergarten terms so Ellis can understand.”
Mercy sighed. “The HTML in email messages gets scrubbed by the client. What that means is anything the email client thinks is suspicious, such as a script tag or an iframe, gets taken out. The stuff that gets left in is just text formatting and images. Even if you got some embedded video code into a message somehow, email clients don’t have the Flash plugin available to load it.”
Ellis clicked on his trackpad, then spun his laptop around to show Mercy his screen. “Packard got it in somehow.”
Mercy examined the browser window. A message was displayed in Gmail from the Packard for Governor campaign. Just above the fold was what looked like a screenshot with a play button in the center. Just like a video player.
“It’s just an image.” Mercy clicked on it, and the browser spawned a YouTube page in a new tab, a Packard for Governor campaign ad playing at full volume. Ellis hit pause halfway into the sentence “I’m Harold Packard and I approve this message.”
“Look,” Sullivan said, "Rockwoods really stuck on getting this in. Is there any workaround?”
“It won’t be a real video & but we can embed a .gif image.” Mercy, on her own laptop, found the Packard ad and ran it through an online .gif converter. It produced the first three seconds of the ad. “I can add a caption at the bottom, put a big play button in the center, make it look exactly like a video player. There’s no sound, but who wants sound to play when they open an email message?”
“Don’t mention that to Rockwood, Sullivan said. He’ll want sound playing on every email message we send.”
Mercy downloaded the .gif, noticing the size of the file. “Hey, we don’t want to embed a 3MB image in each email message. We should put this on our CDN server and link to it from there.”
“Won’t there be that little X icon if we do that?” Ellis asked. “I hate it when Gmail does it to our messages.”
“Most subscribers have our newsletter added to their whitelist, so they won’t all see that,” Mercy said. “We attach the template images to the email message, but theyre only a few kilobytes. We can’t send 3MB messages to all of our subscribers.”
“Our email provider’s giving us a discount this month, Sullivan said, and I know if Rockwood’s going to want to see the video in the email as soon as it’s out. And if he sees that X icon, he won’t be happy about it.”
Mercy shrugged. “Well, what’s 3MB when people have a TB of storage for email nowadays? I’ll get it done.”
“That’s the kind of motivation I like to see.”
Mercy turned to see Rockwood in the doorway of the conference room. She wasn’t sure when he’d walked in.
“Oh, I’ll make sure that video gets sent out,” Ellis said, with a straight face.
“Ellis, if I was appointed Emperor of Florida tomorrow, you’d say it was all because of you.” Rockwood winked at the man as he sat in an empty chair. Mercy rolled her eyes.
“Now, don’t give me that,” Rockwood said, addressing Mercy. “I have a task just for you. See, I need a countdown clock. You know, like the one in Mission: Impossible, the bomb timer.”
“John,” Sullivan asked, “when is this & bomb set to go off?”
“August 1st, one second after midnight. Think you can do that?”
“Uh, sure,” Mercy said. “What happens when it gets to zero?”
“I’ll let you know.” With that, Rockwood left the conference room.
“Well,” Sullivan said, “I’m sure he’ll let us know just what he wants in due time. So, can you make a countdown timer, Mercy?”
“Sure can.”
Cloistered away in her apartment, far from the squawking of the volunteers on the phone lines, Mercy built a countdown clock. Javascript programming didn’t lend itself well precision timing, but coding timers was easier than in other languages due to the setTimeout()/setInterval() methods and functions as first-class objects. In fact, Mercy had written countdown clocks for several past clients. She grabbed a recent copy of that code and modified it for Rockwood’s clock.
$(function(){
var launchTime = Date.parse(‘2016-08-01 00:00:01 EDT’);
var $clockTextDays = $(‘#countdown-days’);
var $clockTextHours = $(‘#countdown-hours’);
var $clockTextMinutes = $(‘#countdown-minutes’);
var $clockTextSeconds = $(‘#countdown-seconds’);
window.setInterval(function(){
var delta = launchTime - (new Date()).getTime();
if (delta <= 0) {
// TODO: ASK SULLIVAN WHAT SHOULD HAPPEN
}
else {
var remainder = delta;
var deltaDays = Math.floor(delta / 86400000);
remainder -= deltaDays * 86400000;
var deltaHours = Math.floor(remainder / 3600000);
remainder -= deltaHours * 3600000;
var deltaMinutes = Math.floor(remainder / 60000);
remainder -= deltaMinutes * 60000;
var deltaSeconds = Math.floor(remainder / 1000);
$clockTextDays.text(deltaDays + ‘ days’);
$clockTextHours.text(deltaHours + ‘ hours’);
$clockTextMinutes.text(deltaMinutes + ‘ minutes’);
$clockTextSeconds.text(deltaSeconds + ‘ seconds’);
}
}, 100);
})
She put together a quick concept image in Photoshop and emailed it to Sullivan for her approval (she had learned not to run anything past Ellis unless she wanted him to sabotage it in some way).
Sullivan’s response was quick: Good, but less jaggies. -Barbie
Mercy re-examined the concept image in Photoshop to see if she had left a filter on, then realized that Sullivan was viewing her 1200-pixel wide image on a 700 pixel laptop screen. With Sullivan’s implied approval, she coded the styles for the clock, using an LCD-style font for the digits and placing the entire timer inside a velvet-lined briefcase.
The exercise took less than a couple hours, most of it adjusting the styles for cross-browser compatibility. She pushed the code up to the web server hamilton, which replicated it to the others.
The thought of that TODO comment drifted out of the back of her mind as she went to sleep that night.
WE’RE ON TV! -Barbie
The notification on her phone woke Mercy at 7AM. She wondered which channel Sullivan was referring to, but a Google Alert in her inbox told her. Fox News, taking an interest in the iconoclastic Rockwood facing off against their chosen favorite Harold Packard, had Mercy’s briefcase-framed countdown clock displayed behind the hosts of the morning news, with the headline “Rockwood Campaign About To Explode?” in the ticker below the talking heads.
Back at headquarters later that morning, Mercy checked the logs of the founding father servers. Fox News, Drudge Report, Breitbart, HuffPo, and Politico had all linked to the timer. The common thread of speculation between all of them was exactly what John Rockwood’s timer was counting down to. Mercy brought this up to Sullivan, but she brushed it off.
“This is the best kind of publicity,” she said. “We’re the belle at the ball and every man wants to dance.”
“More like Cinderella,” Mercy said, “and that pumpkin carriage turns back into a pumpkin at midnight. All that timer does is count down to a date. When the date comes and goes, it won’t actually do anything unless we tell it to.”
“The boss will know what to do then,” Sullivan said, as if it were no concern at all. “Anyway, you have approval to begin building our new blogging platform. Just make sure it looks like Ellis’s template.”
Mercy sighed at coding another one of Ellis’s ugly concepts, putting the timer out of her mind.
The morning of August 1, Mercy’s phone buzzed with another Google Alert. This one was from Drudge Report: ROCKWOOD’S BOMB FIZZLES.
Mercy tried to remember in which of Rockwood’s speeches he had mentioned a bomb going off. She couldn’t, so she went back to sleep.
The phone buzzed again. This time, it was Sullivan calling her.
“That countdown clock is counting in the negative!” Sullivan was breathless. “It’s just going negative one, negative two, negative three&”
Mercy remembered. “You never told me what it should do.”
“I thought we told you when we gave you the assignment.”
“No, I asked, and no one would give me a straight answer.”
Mercy dressed and drove to headquarters. Ellis spotted her as she came in, his eyes widening like a shark’s as it smelled blood. “Your countdown clock is broken!”
“Okay, Ellis.” Mercy’s teeth ground together. “What was it supposed to do?”
Ellis waved his hand dismissively. “I’m sure it goes to a press release or something. You should check your email.”
Mercy pulled out her phone. She entered the phrase “countdown clock” in her email client. The only search results were the brief exchange between Sullivan and herself approving the concept image.
In the back hallway leading to the conference room, she saw Sullivan talking to Rockwood. The candidate looked a bit listless. Sullivan was throwing her hands up in frustration. She rubbed his back, said something she couldn’t make out, and made her way to where she and Ellis were standing.
“Funny, Sullivan said, John doesn’t actually remember telling you to do the countdown clock. I reminded him, but it didn’t jog his memory. He’s such a busy man, I’m sure it slipped his mind.”
Ellis nodded vigorously. “You should have written it down,” he said again to Mercy.
“In fact,” Sullivan added, “I recall the conversation exactly. He said he would tell us later, and wouldn’t you know, he never did. Not his fault, he’s just been so busy!” Her voice sounded flustered. “But I know what it should link to. It’ll go to our first blog post from the campaign! Can you do that?”
Mercy nodded. “The page won’t actually redirect to it unless they refresh the page.”
“I’m surprised you couldn’t have guessed that,” Ellis said, baring a toothy grin. “I mean, anyone—“
“Harry,” Sullivan said, leaning in so close her face was an inch from Ellis’s, “not everyone here is as close to John as you are. In fact, he could really use your help right now. Why don’t you see to it.”
Mercy’s blood ran cold as Ellis shuffled back to see to Rockwood.
Mercy stared listlessly at the landing page of the Rockwood for Governor campaign blog, titled “Righteous Rants,” picked by consensus from the volunteers.
Ellis had spent the entire day in the conference room with Rockwood. He only came out once to talk to Mercy, complaining that the mobile view of the blog template didn’t use his hover menus. Mercy explained as best she could that hover menus don’t work on mobile because you can’t actually hover a cursor on a touchscreen. He seemed much more complacent than he had been earlier when he confronted her about the countdown clock.
She was watching a video of one of Rockwood’s stump speeches, filled with his typical long pauses, when the candidate himself emerged from the back. His shirt was rumpled and untucked, but his personality was fresh and cheerful. After greeting some of the volunteers (and fixing his shirt), he came over to Mercy. “I appreciate how much work you put into that little countdown,” he said, shaking her hand. “Wish I would have thought of that! Barbie tells me our page impressions are through the roof!” He whispered, in a conspiratorial tone, “I don’t know what kinds of impressions she’s talking about, but I hope they’re good ones!” He slapped Mercy’s shoulder and left for other matter, Ellis trailing behind. Mercy smiled, remembering the man she saw back in that high school gym several months ago.
Mercy decided that the dropdown menus would open on click at mobile sizes, hover at typical desktop resolutions. They hadn’t fired her for building a countdown clock that did nothing after counting down. Surely she had some executive power when it came to building CSS menus.
But deep down, she realized something was very wrong with Rockwood, and only Ellis and Sullivan knew what that could be.
http://thedailywtf.com/articles/mercy-the-mercenary-in-the-not-so-final-countdown
|
Метки: Feature Articles |