letsthinkabout.us

technology, healthcare, people

A Real World Example of a Value Type vs a Reference Type

All C# types fall into the following categories:

  • Value types
  • Reference types
  • Generic type parameters
  • Pointer types
There is a fundamental difference between both value types and reference types in how they are represented in memory that is important to understanding how the C# language works.

Value types are most typically the built-in types-- int, double, char, bool, as well as structs and enums. 
Reference types are classes, arrays, delegates, interfaces and the built-in string type.

The content of a value type variable or constant is merely a value. Assignment of one value type to another copies the value. Here is an example of that.

Example 1:

public struct Point { public int X; public int Y; }
 
void Main()
{
    Point p1 = new Point();
    p1.= 100;
    p1.= 100;
 
    Point p2 = p1; //assignment of new Point p2
    p2.= 200//only changes X on p2, not p1
    p2.= 200//only change Y on p2, not p1
 
    Console.WriteLine("X: {0}, Y:{0}", p1.X, p1.Y); //X: 100, Y: 100
    Console.WriteLine("X: {0}, Y:{0}", p2.X, p2.Y); //X: 200, Y: 200
}

Another example that is just is applicable is value types as function arguments. In this case, the value is copied into the function and if not handled correctly, can do no noticeable work in your program. This goes to the statement that "mutable structs are evil."

Example 2:

public struct Point { public int X; public int Y; }
 
void Main()
{
    Point p1 = new Point();
    p1.= 100;
    p1.= 100;
    MultiplyByFactor(p1, 5);
    Console.WriteLine(p1.X); //100, not 500!
    Console.WriteLine(p1.Y); //100, not 500!
}
 
void MultiplyByFactor(Point p1, int factor) //p1 will be a copy of the Point passed in
{
    p1.*= factor;
    p1.*= factor;
}


A reference type in comparison has 2 parts: 1) a pointer to the variable and 2) the variable itself. The pointer to the variable is the variable name assigned by the programmer. The variable itself is allocated in memory and contains all the information (which could be value types!).  By changing the word "struct" to "class" as the keyword defining Point in Example 1, we see this happen:

Example 3 (formerly Example 1):

public class Point { public int X; public int Y; }
 
void Main()
{
    Point p1 = new Point(); //p1 is a pointer to a Point in memory
    p1.= 100;
    p1.= 100;
 
    Point p2 = p1; //p2 points to the same Point in memory as p1
    p2.= 200//p1.X is now 200
    p2.= 200//p1.Y is now 200
 
    Console.WriteLine("X: {0}, Y:{0}", p1.X, p1.Y); //X: 200, Y: 200
    Console.WriteLine("X: {0}, Y:{0}", p2.X, p2.Y); //X: 200, Y: 200
}


The reason you want this type of behavior is because if there are large objects, say a class with an array of 1,000,000 values, you don't want to copy it every time you create a new object-- it could be a potentially huge performance hit. If, for example, you had a method / function that took in this large object, you don't want to copy it for use in the function, you want to use the actual object in memory, referenced by a pointer. That is described in Example 4, which is Example 2, but now Point is a class.

Example 4 (formerly Example 2):

public class Point { public int X; public int Y; }
 
void Main()
{
    Point p1 = new Point();
    p1.= 100;
    p1.= 100;
    MultiplyByFactor(p1, 100);
    Console.WriteLine(p1.X); //now 10000
    Console.WriteLine(p1.Y); //now 10000
}
 
void MultiplyByFactor(Point p1, int factor) //p1 is only a name that references an actual Point object in memory
{
    p1.*= factor;
    p1.*= factor;
}



The easiest real-world analogy of a value type vs reference type is using an email attachment.

Grandma thinks email attachments are reference types


Email attachments are value types

If you email an attachment to someone, it is copied and then sent to the recipient. Now you kept your copy, and your recipient also has a copy. It is a value type. If your recipient wants to edit it, they can do so without you knowing what they did to it. If you want to see what they did, they must send it back to you (as another copy) for you to see the changes.


Links to files on DropBox or OneDrive are reference types

If you email a link of a file in your DropBox to someone, you are emailing them a reference to the actual file. Now the link and the file together is a reference type. If your recipient wants to edit it, they can do so and you will see exactly what changes they made, since it is physically the same file. There is no need for them to send anything back to you.

Think of email as a function call (the recipient is the inner workings of the function) and the attachments as function arguments. If you email an attachment, you are copying the function arguments for use by the recipient. If the files are large (gigabytes), you probably don't want to attach them since it will slow down your internet connection and clog your recipient's email storage. Sending a hyperlink in this case would be the easiest, thus for large objects and fast performance, you would want to use a reference type in a function call.

Now, if your email attachment is small, and you just want to send an FYI to your recipient, then attaching it is no problem. This would be analogous to sending an int, bool, char or struct inside the function call. I hope this helps your understanding of value types vs reference types.

2014 FDA Drug Approvals

A Record Year


2014 is currently a local maximum for USFDA new drug entity approvals. At 41 new entities, 17 of which are first-in-class therapies, and as 17 orphan drugs (for diseases that affect <= 200,000 patients per year), this past year in the approval aspect was certainly a pleasant melding of a central regulatory gatekeeper and private enterprise.

The previous record for FDA drug approvals was in 1996, where a record 53 drugs were approved. This was the pivotal year of a class of antiviral drugs known as protease inhibitors, which essentially changed HIV from a death sentence to a manageable chronic disease. The data speaks for itself. The number of AIDS deaths were halved in a 2 year period following the approval of the first protease inhibitor, saquinavir.



This year, new Hepatitis C virus therapies such as Gilead's Harvoni and AbbVie's Viekira Pak are set to break third-party payers' pharmacy budgets, while saving long term costs and clinically curing patients. New cancer therapies, Merck's Keytruda and Bristol-Myers-Squibb's Opdivo are novel new therapies, with Merck obtaining (conditional) FDA approval for melanoma just 3 years following Keytruda's first-in-man study. 

A record 5 new antibiotics were approved this year and 2 antifungals. New indications were obtained for the novel oral anticoagulants, dabigatran and apixaban. Castleman's disease, multiple sclerosis and visceral / cutaneous leshmaniasis all now have new therapies.


Check out more details in this presentation I gave:


iOS Game of Life

iOS Game of Life

The live demo for this can be seen here: 


Game of Life is a cellular automaton created in 1970 by mathematician John Conway. There are only 4 rules of the game:

  1. An alive cell with 0 or 1 alive neighbors dies in the next generation (underpopulation)
  2. An alive cell with 2 or 3 alive neighbors lives in the next generation
  3. An alive cell with > 3 alive neighbors dies in the next generation (overpopulation)
  4. A dead cell with exactly 3 neighbors comes to life in the next generation.


The implementation here uses a 2D boolean array that serves as the "board." Using a standard model of states, we iterate over the entire array in each generation to determine which cells will be alive or dead in the next generation.  If you are interested in the code, see the implementation in the GitHub project here


Runge Kutta in C++

Continuing on my series for Runge Kutta in multiple languages, today's topic is C++. The other implementations can be found here:


So again, Runge Kutta is a numerical evaluation of an ordinary differential equation. It is more generalized than Euler method in that 2nd order Runge Kutta = Euler method. Here, we use the very common 4th order method, which is simple to program and very accurate for appropriate time-steps.
 



Given the differential equation and initial bounds:


What is y( 1 )?

ps: this equation solves to y = exp(x)


Let's implement the Runge Kutta equations in a method returning double named rk4( ... ):

const double sixth = 1.0 / 6.0;
double rk4(double x, double y, double dx, double(*f)(double, double)) {
	double halfdx = 0.5 * x;
	double k1 = dx * f(x, y);
	double k2 = dx * f(x + halfdx, y + k1 * halfdx);
	double k3 = dx * f(x + halfdx, y + k2 * halfdx);
	double k4 = dx * f(x + dx, y + k3 * dx);
	return (y + sixth * (k1 + 2 * k2 + 2 * k3 + k4));
}
The very last argument of the rk4 method is a pointer to a function which is called 'f' in the scope of rk4. 'f' takes 2 arguments of type double.


Next, we'll create an Equation object, that contains the x, y, dx and target variables. I use a C++ struct to let all methods and fields/properties default to public accessor.
struct Equation {
	double x, y, dx, target;
	static double dy_dt(double x, double y){ return y; }
	void Run(){
		while (x < target){
			y = rk4(x, y, dx, dy_dt);
			x += dx;
		}
		std::cout << "x=" << x << "\n" << "y=" << y << "\n";
	}
	Equation(double x_arg, double y_arg, double dx_arg, double target_arg){
		x = x_arg;
		y = y_arg;
		dx = dx_arg;
		target = target_arg;
	}
};
The method dy_dt is marked static because in C++ you cannot pass a member function as a function pointer. There is a nice writeup about why:

[33.2] How do I pass a pointer-to-member-function to a signal handler, X event callback, system call that starts a thread/task, etc?
Don't.
Because a member function is meaningless without an object to invoke it on, you can't do this directly (if The X Window System was rewritten in C++, it would probably pass references to objects around, not just pointers to functions; naturally the objects would embody the required function and probably a whole lot more).

Finally, our entry point creates a local variable of type Equation using the defined constructor, and we call Run( ) on it:
int main(int argc, const char * argv[]) {
	Equation eq(0.0, 1.0, 0.000001, 1.0);
	eq.Run();
	return 0;
}

Result:

y = 2.71828

which is close to the value of e = 2.7182818284590452353602874713527


Here's the full code:

#include <iostream>
const double sixth = 1.0 / 6.0;
double rk4(double x, double y, double dx, double(*f)(double, double)) {
	double halfdx = 0.5 * x;
	double k1 = dx * f(x, y);
	double k2 = dx * f(x + halfdx, y + k1 * halfdx);
	double k3 = dx * f(x + halfdx, y + k2 * halfdx);
	double k4 = dx * f(x + dx, y + k3 * dx);
	return (y + sixth * (k1 + 2 * k2 + 2 * k3 + k4));
}
struct Equation {
	double x, y, dx, target;
	static double dy_dt(double x, double y){ return y; }
	void Run(){
		while (x < target){
			y = rk4(x, y, dx, dy_dt);
			x += dx;
		}
		std::cout << "x=" << x << "\n" << "y=" << y << "\n";
	}
	Equation(double x_arg, double y_arg, double dx_arg, double target_arg){
		x = x_arg;
		y = y_arg;
		dx = dx_arg;
		target = target_arg;
	}
};
int main(int argc, const char * argv[]) {
	Equation eq(0.0, 1.0, 0.000001, 1.0);
	eq.Run();
	return 0;
}

4 Life Lessons from Powerlifting

From 2007 to 2011, I was a competitive powerlifter. I squatted 625 lbs, benched 460 lbs, and deadlifted 551 lbs at my best. I also lost 60 pounds going from 220 to 160 in 16 weeks from Jan - May 2009. I hired (now pro) bodybuilder Shelby Starnes.



During this time, I learned about the more fanatical ends of myself. I was willing to sacrifice personal time, friends, and family time just so I could train.  Almost anything was secondary to progression of myself. Not an optimal approach to life. I did pick up some things along the way when I reflect back:


1. You push back hardest when resistance is greatest

I learned this early on. While doing some warm-up sets on squat, I found that I simply could not push the weight as hard when it was light. For example, I would warm up with 135 lbs for a set of 10, but each individual rep had maybe a force worth 185 lbs behind it. When the weight was 185 lbs, I was able to apply 225 lbs worth of force behind it. It wasn't until 315 lbs that I was able to apply 365 lbs worth of force to the weight.

This was the first concept to click in my mind when it came to the parallels of life and powerlifting. You can simply drift at what you do, go through the motions without ever fully applying yourself. However, once the stakes are high, the pressure is on, then you are able to perform at the best of your abilities.


2. Scheduled time-off = big gains

Both in and off-season, I trained using a 4 week cycle. It looked like this:

Week 1 - 3:
  4 Days / week
  2 Days Bench movements
  2 Days Squat / Deadlift

Week 4 (deload):
  3 Days -> Weights not more than 25-30% of week 3 maxes

I would string together these 4 week periods into a coherent 16 week training cycle, where intensity would increase for 3 week waves, with 1 week down. This would lead to week 11 being the absolute heaviest of the training cycle. Week 12 would be a deload, and 13-15 would be a decrease in intensity. 

The span from week 11 to competition day following week 16 is known as delayed transformation. You are actually getting stronger from the decrease in intensity between week 12-16 because you peaked at week 11 and your body is adapting to the training in delayed fashion. These principles are outlined in Mel Siff's Supertraining, a book I highly recommend.

In my experience, this principle of scheduled time-off holds true for other abilities, such as learning, cognition and manual dexterity. In essence, you get better at things when you take the appropriate time-off. But this is provided you followed lesson #1.

3. Do what you suck at

A chain is only as strong as its weakest link. To be a better chain, you have to strengthen that link.

Case in point: in late 2007, my bench stagnated in the high 200's. Whenever I tried anything above 275, I'd lose it completely about 3/4 the way up. My triceps were weak and I couldn't drive the weight any further, no matter the speed coming off my chest. For 2 months, I decided that I would heavily train the top part of the motion. This meant heavy (300 lbs +) board presses, adding bands, and more tricep work. By January 2008, I managed to increase my bench > 40 pounds and with my first 315 lbs bench press.

It's often difficult to identify what exactly are your weak points. Once you do identify them, it's sometimes difficult to accept that you have these deficiencies. But you get it done, and you'll be better off.

4. You can't succeed alone

In powerlifting, you need support. Support when you're training in the form of spotters and partners. Support in your friends who will show up to your meets. Support in your family, who will put up with your lifestyle. And as much as you receive this support, you are also expected to reciprocate this support in appropriate ways. No one made it to the top without a little help from some friends.