fuckyeahterminals
fuckyeahterminals
fuckyeahterminals
789 posts
Don't wanna be here? Send us removal request.
fuckyeahterminals · 6 years ago
Text
Utility of Unions in C
“Why are unions in c useful?” I was actually driven to write this post because I couldn’t find any compelling examples of the utility of the union keyword in C. There were a lot of great examples of reference material breaking down the differences between struct and union and the mechanics of union, but not a lot depicting what I felt was a compelling example of how union could be powerful. I only found one that I felt was exemplary but it dealt with it at the byte level, which is great if you’re doing embedded programming, but not relatable all if you’re coming from a different background. So I’ll give a short direct explanation for how I was able to wrap my brain around union and why I think this mental model is better than a lot of the explanations on the internet. I think of union as a way of declaring members in a group that overlap one another in the same area of memory. That immediately clarifies the behavior of union and why things need to be accessed “one at a time”. Really what it means is you’re referencing the same block of memory. disclaimer: I don’t know if that’s actually how it works but I went ahead and wrote a program to see if I could validate my mental model, and lo and behold it worked. So here’s an example I would call useful. Consider this: you’re writing code for a business that sells books at scale, you need it to be performant, or maybe it’s a really old system - at any rate you have to write it in C. You sell physical books and are extending the system to sell eBooks, so naturally you think to yourself “it’d be great if I could just write the extension and leave most of the existing code alone.” Let’s see some sample code, contemplate the following snippet as part of your existing code
struct Paperback { char bookId[25]; char bookTitle[200]; char author[200]; }; void printPaperbackInfo(struct Paperback pb) { printf( "This is a book with ID %s and Title of %s written by %s.\n", pb.bookId, pb.bookTitle, pb.author ); } int main(int argc, char* argv[]) { struct Paperback theFall; strcpy(theFall.bookId, "PHY255ACTF"); strcpy(theFall.bookTitle, "The Fall"); strcpy(theFall.author, "Albert Camus"); printf("Okay so far we have...\n"); printPaperbackInfo(theFall); }
You think to yourself, “Okay, well I need to add some concepts about eBook so I’d probably create an eBook specific stuff and use it as I need it.” So that’s what you do:
struct ElectronicBook { char bookId[25]; char bookTitle[200]; char author[200]; char format[10]; char DRMS[50]; }; void printElectronicBookInfo(struct ElectronicBook eb) { printf( "This is a book with ID %s and Title of %s written by %s.\n", eb.bookId, eb.bookTitle, eb.author ); printf( "This book is in format %s signed with %s.\n", eb.format, eb.DRMS ); }
Well now you notice you have duplicated code. There also seems to be a lot ElectronicBook and Paperback share in common. Either way you’re left wondering something to the effect of “I guess I could re-use void printPaperbackInfo(struct Paperback pb) and just cast my structs everytime I want to use it, but either way I have two distinct structs I’d be using and really I wish I had the one.” Enter union. So at this point I would say, “Hey I want a union of these two data structures, because they’re basically the same thing in memory with some added stuff, and I don’t want to be casting stuff all the time and having to deal with compiler errors” so your code would evolve to look like this
struct Paperback { char bookId[25]; char bookTitle[200]; char author[200]; }; struct ElectronicBook { char bookId[25]; char bookTitle[200]; char author[200]; char format[10]; char DRMS[50]; }; union Book { struct Paperback pb; struct ElectronicBook eb; }; void printPaperbackInfo(struct Paperback pb) { printf( "This is a book with ID %s and Title of %s written by %s.\n", pb.bookId, pb.bookTitle, pb.author ); } void printElectronicBookInfo(struct ElectronicBook eb) { printf( "This book is in format %s signed with %s.\n", eb.format, eb.DRMS ); }
okay well now we have some definitions, this seems strictly better than the previous duplicated code we had, let’s see where this goes Its usage might look something like:
int main(int argc, char* argv[]) { union Book theFall; strcpy(theFall.pb.bookId, "PHY255ACTF"); strcpy(theFall.pb.bookTitle, "The Fall"); strcpy(theFall.pb.author, "Albert Camus"); printf("Okay so far we have...\n"); printPaperbackInfo(theFall.pb); // but wait maybe we reach out to some part of our system // and discover this is available as an eBook and we // want to treat it as such now printf("We're assigning ebook data\n"); strcpy(theFall.eb.format, "kindle"); strcpy(theFall.eb.DRMS, "Digital Rights Management Signature"); printf("That's cool the paperback code is still happy...\n"); printPaperbackInfo(theFall.pb); printf("But so is the eBook code...\n"); printElectronicBookInfo(theFall.eb); return 0; }
So, I don’t know about you but I’m feeling pretty confident in this mental model. In summary, unions allow us to manipulate the same area of memory in code for the “overlapping” members (aka a union of the members). This is useful (as I’ve shown above) because we’re able to define a union with label Book and then use that union in parts of the code where the code only knows about Paperback and where the code only knows about ElectronicBook by passing around pb and eb respectively. I think this is a sound analysis on my part, that or maybe I’m getting lucky that the references to pb are still there in memory because of deallocation that hasn’t happened. However, this example is congruent with the expected behavior from the accepted StackOverflow answer referenced above so that seems unlikely. Hopefully this helps people out. If it backfires on you horribly, I’d also like to hear about that so I’m not misinforming people.
2 notes · View notes
fuckyeahterminals · 9 years ago
Text
An Open Letter To Ad-Block Blockers
This is to all those sites who will “physically” not load content onto a page because there’s an ad-blocker running on my machine, essentially “blocking” my ad-blocker. 
I don’t care enough about your content to make a change in my habits.
And my suspicion is, those that care enough to install an ad-blocker probably feel the same way. You’re effectively lowering your user-base and increasing into your opportunity cost. I will literally without hesitation or remorse navigate away and let the article and it’s contents die and escape any previous interest I’ve might’ve originally had.
The real cost to you. Diffusion of material to those that don’t have that turned on. You’re truncating the graph or tree outgrowth of the diffusion of information to those nodes that really dislike advertisement, because really, what do I care about whatever your shitty ad-server is going to try and sell me?
That behavior on your part, is a reflection of how disconnected you are with the times, peoples’s sharing habits, and people’s spending habits. It is a failure of all three.
1 note · View note
fuckyeahterminals · 9 years ago
Text
Controller Concerns in Rails 4
If you setup a Rails 4 app, you’ll notice the app/models/concerns and app/controllers/concerns directories.  Concerns are modules that can be mixed into your models and controllers to share code between them.   Some developers falsely classify mixins as composition when they are actually a form of inheritance.  When you include a module in a class, that module’s methods are added to the inheritance chain just like a parent class’ methods are added to a subclass.  So, don’t think you’ve solved the problem of inheritance by simply splitting your inherited code into separate files! That being said, mixins can be a valuable tool to share code between classes that are otherwise unrelated. Here’s an example of how I chose to use it recently. I am adding admin reporting features to an app I’m hoping to launch soon.  I have an admin controller with a simple before filter to redirect if the current user is not an administrator.
class AdminController < ApplicationController before_filter :check_admin_user private def check_admin_user unless current_user.admin flash[:alert] = "You can't be here!" redirect_to root_path end end end
I need two admin reports that allow filtering by month.  To stick with my routing scheme, I want a separate controller for each report.  Both controllers need to load months from the database, build a list of months, get the selected month from the query string or month list, and find records where a specific date field falls within the given month/year.  The only difference is how those records are processed before being used in the views. These are the only two admin features so far.  So, I started by putting the month filtering code in the AdminController so it could easily be shared by both.  However, it’s likely that more admin features will be added later that don’t need month filters.  More importantly, month filtering isn’t intrinsic to   the admin section of the site.  The purpose of the AdminController is to prevent non-admins from accessing the actions.  That’s it.  The month filtering code doesn’t really belong there.  Where should I put it?  How about in a concern?
# app/controllers/concerns/month_filtering_for_contests.rb module MonthFilteringForContests extend ActiveSupport::Concern included do attr_reader :month, :contests before_filter :build_month_lists before_filter :set_current_month before_filter :load_contests_for_current_month end def build_month_lists @months = Contest.months_with_ended_contests @month_list = @months.map { |date| [date.strftime("%B %Y"), date.strftime("%Y-%m")] } end def set_current_month @month = if params[:month] Date.new(*params[:month].split(/-/).map {|part| part.to_i}) else @months.first end end def load_contests_for_current_month @contests = Contest.ended_during(@month) end end
Now, my AdminController can remain clean and the month filtering module can be included in each report controller.
class Admin::SampleReportController < AdminController include MonthFilteringForContests def show @totals = contests.each_with_object({}) { |contest, hash| # code to process reporting data here } end end
Now that I look at it, one can argue that everything in AdminController can be moved into it’s own concern and the class can be removed completely.  However, it’s 3:02am on Christmas Eve. So, that decision can wait.
18 notes · View notes
fuckyeahterminals · 9 years ago
Quote
You don’t send messages because you have objects, you have objects because you send messages.
Sandi Metz
0 notes
fuckyeahterminals · 9 years ago
Link
Downright coldblooded.
I would do something more subtle like:
alias ls="ls -alh | head"
It would take forever to find out what the fuck is going on.
3 notes · View notes
fuckyeahterminals · 9 years ago
Link
anyone asks me this question i’m gonna forward them this link.
4 notes · View notes
fuckyeahterminals · 9 years ago
Link
the best thing I’ve seen all day
*edit: just so there's no misunderstanding by "best" I mean funniest thing - of course the first time we expose an AI to the "world" we get a mirror for the worst in humanity.
0 notes
fuckyeahterminals · 9 years ago
Link
I feel oddly vindicated.
3 notes · View notes
fuckyeahterminals · 9 years ago
Link
class support now comes on by default on Chrome following this 49 release. So basically if you’re dev-ing for chrome you can use classes in your javascript now. 
fuckyess, Hopefully this mean that front-end .js code will be less of a clusterfuck now.
It's basically the difference between this bullshit:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Using_a_constructor_function 
to:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes 
Let's say you'd never written a single line of code in Javascript, even at a cursory glance it's the difference of "what in the fuck?" to "oh that makes sense"
2 notes · View notes
fuckyeahterminals · 9 years ago
Text
Euler Project
I totally forgot I had this laying around. Someone asked me for it the other day. here you go.
https://github.com/lvalencia/EulerProject
may the next brave soul get further than I did.
1 note · View note
fuckyeahterminals · 9 years ago
Text
Legal standalone statement in javascript w/jQuery.
I could hear an evil laugh going off in my head as I wrote this.
($el.is('i')) ? $el = $el.parents('h4') : '' ;
you know technically I can assign this statement to a variable that wont presist.
[].useless = ($el.is('i')) ? $el = $el.parents('h4') : '' ;
Just 'cuz.
Edit* I literally just didn't feel like writing an if statement at that exact moment in time, and that's the first statement that fell onto the keyboard from my lifeless hands.
3 notes · View notes
fuckyeahterminals · 9 years ago
Text
This is why I don’t like PHP
By virtue of the language I end up writting stuff like this.
public function getLatestScoreForExam($exam) { $scores = array(); for ($i = 1, $score = "N/A"; !empty($score); $i++) { array_push($scores, $score); $score = $exam->getData('attempt_'.$i); } return array_pop($scores); }
What's worse some people will think this is "good" or "clever".
I look at this and just see dirty-ass code.
2 notes · View notes
fuckyeahterminals · 10 years ago
Text
quick summation
cat expenses | awk -F'$' '{print $NF}' | paste -sd+ - | bc
when you wanna sum something quick but feel too lazy to use a calculator.
0 notes
fuckyeahterminals · 10 years ago
Link
Hit the Terminal Motherload
3 notes · View notes
fuckyeahterminals · 10 years ago
Text
A path to enlightenment in Programming Language Theory
http://steshaw.org/plt/
0 notes
fuckyeahterminals · 10 years ago
Photo
Tumblr media
Re-reading some classics. And a new book. I'll admit I was surprised when I saw how thick Wolfram's book is, but already I'm enthralled.
4 notes · View notes
fuckyeahterminals · 10 years ago
Text
Confused.
I don’t usually ask questions, but I’m watching the Keynote for Polymer because I was really intrigued with Google Material Design (so I was reading their manifesto and ended up clicking out) -- and, how is Polymer and Web Components any different (conceptually) than XAML?
I mean XAML is deeply integrated with the Microsoft Workflow, so contextually I understand that that is a major distinction, i.e. at this point in time you cant use XAML unless you’re developing using the Microsoft Ecosystem.
But if we strip that out, then it’s essentially the same concept, except it plays nicely with everything. I mean don’t get me wrong, I like what I’m hearing them say.
But they’ve stayed that “[it] isn’t simply a better version of something else out there, it’s not like things that came before” and that they’re “... [doing] something totally new, and build on something revolutionary and dramatically change web development. So get right out right on the bleeding edge of standards, and start pushing and vetting new concepts”
but this isn't conceptually new or at least it doesn’t seem to be the case...did I miss something?
0 notes