Monday, November 26, 2012

Node Cookbook, Chapter 6 Making an express web application

Now the particular issue that I've run into with this example is implementation of Jade mixin s in this example.  One I would indicate that the mixin in Jade is simply a short hand java script function for the Jade scripting system (inspired incidentally by Haml for Node).  Unfortunately, the Jade script, Profiles.Jade file includes what should apparently be defined as two empty functions which it appears automatically generate an error, but handled by the index.js through the main body apps routes/index.js script...sort of circuitous silliness in my opinion :) ...umm...book example script appears in some ways to be a mess, but... 

Monday, November 19, 2012

Node JS and Express 3 example problem, Child express application called inside a Parent express application

 The problem that I've seen though Express with Node JS, is stable implementation examples keeping to framework versions.  For example, a Node cookbook seems to provide excellent examples say from Express 2, but unfortunately at the time of writing either owing to changes since then through version or for any other reasons, I've spent time studying and trying to re work examples for basic functionality.  I'd give the latest problem example:  This would include using a app.use() call on another express app embedded into a main express app.  Apparently while mount uri citation works, the uri is structurally not integrated into the main express apps router for some odd reason.  I'd indicate that I've been able to use app.use() with uri for mounting functions with resend and request calls implementing by default routing...by the way if you use a console.log(app.routes) call to see the uri as route, it won't show, but will if you alternately use app.get() for the same function.
     Why the big fuss over the call of one app to another?  Well according to the Node cookbook chapter 6 example, going from sub chapter to the next, implementation of previous application functionality can be done so (in a class/module oriented) way simply copying the contents of one application and embedding it in the parent application.  Apparently the very basics of this functionality is handled with a

app.use(uri, require('./myappname/app'));

No problem here at least initially.  The problem that seems to manifest, at least in the latest version of Express somewhere in the process of child apps sending and receiving request or sending response.  At least in my example case, I used on the child express app, using the following function:


  app.use(function(req, res, next){
    res.send('hello world');
    next();
  });


It appears the parent app neither provides request communications to child express apps, or the child express apps aren't communicating to the local host...minding I did set up a listener on the child express app


if (!module.parent) {
  app.listen(3000, function(){
    console.log("Express server listening on port %d in %s mode",   app.address().port, app.settings.env);
  });
}


Thus getting a response Cannot GET /childappuri/ when the uri    localhost:3000/childappuri/ is called

At this point stumped what were occurring here.  Set up the basic of examples here again...otherwise, the workaround were embedding much in the main app all of the process (a little more involved).  Hoping I could find a working example on the  most current express 3 version, but couldn't aside from already provided advice through common forums such as StackOverflow which were general enough, didn't see anything at the moment.


A solution:
Thanks to another posting in StackOverflow.  The simplest that I've found is simply exporting the app.
Thus I added after all configurations and routing adds the following in the body of child express app in the app.js file:

module.exports = app;

All references above in the parent app should be used, and make sure that the server instantiation in the child express app is removed while using a listener (hadn't checked to see if this were technically necessary).

Thursday, November 8, 2012

Node Cookbook, Chapter 6 implementation of sessions, site wide management

Okay reading Node Cookbook.  I am having difficulties with an example here, namely, Chapter 6, custom middle ware for site wide management, under initializing and using a session.  Here the problem encountered namely begins with the alternate use of the deprecated function dynamic helpers().  In this implementation the book calls for


app.locals.use( function (req, res) {
        res.locals.user = req.session.user;
    });
However this gives rise to error at least in my case, so a slight modification of this alternately is


app.use( function (req, res) {
        res.locals.user = req.session.user;
    });
which seems to resolve some issue here, but then I get an error in the views>login.jade file referencing user.

Okay some additional s here of notable mention.

In the views/login.jade  file I had to change the reference from

user

to

locals.user

or notably I received an error that user wasn't defined oddly enough.

Secondly I instantiated the function in the configures portion of the app in the following manner:


app.configure(function(){
  app.set('port', process.env.PORT || 3000);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.favicon());
  app.use(express.logger('dev'));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.cookieParser('kooBkooCedoN'));

  app.use(express.session());
  app.use(require('./login'));
  app.use( function (req, res, next) {
        console.log('hit func1');
        res.locals.user = req.session.user;
        next();
    });
  app.use(app.router);

  app.use(express.static(path.join(__dirname, 'public')));


});

Try moving this app.use() function with res.locals.user assignment just after the app.use(app.router); instantiation and you might as I did have problems with your function being called even though it were technically instantiated, or this is to say, I've found this function has to be called before the app.router instantiation but not before the require('./login') instantiation !!!  Obviously the assigning before the require(./login) assignment references res.locals.user before user has technically been assigned in the ./login module, or at least received an undefined assignment error here, and then it appears that app.router assignments causes disregard in express of any app.use() response, request, next functions needed to set res.local.user...so order of instantiation is very important here.

Since I am a noob when working with express here, it is worth noting that that app.get() function that conflict with app.use() functions on response and requests basis neither coupled may with next(); generate un desired results, or at least I've run into these sorts of problems especially as pertaining to GET page routing.

Tuesday, November 6, 2012

Electoral outcomes python script


The following python scripts computes a permutation of outcomes for electoral success if Obama holds leaning blue states.  I computed a total of 18 distinct electoral outcomes which lead to success, this actually could be reduced a bit, since there maybe set overlap if not including the state of Florida which automatically provides Obama a win if Obama holds every other projected state and leaning states are included.  Just run script in Idle then type 'perms' or you could modify script for a list print

mapdict = {'va': 13, 'nh': 4, 'oh': 18, 'wi': 10, 'ia': 6, 'co': 9}

def checkset(pickmap, mappicks):
    mpcheck = True
    checkcont = 0
    for mappick in mappicks:
        checkcont = 0
        for pick in pickmap:
            if pick in mappick:
                checkcont += 1
            if checkcont == len(mappick):
                return True
 

def checkmap(inmap, score):
    mappicks = {}
    mappick = []
    newscore = score
    for state in inmap:
        newscore = score
        newscore += mapdict[state]
     
        mapcopy = inmap.copy()
        del mapcopy[state]
        if newscore < 27:
            #print(state, len(mapcopy))
            returnpicks = checkmap(mapcopy, newscore)
         
            for pick in returnpicks:
                #print (state, pick)
                if returnpicks[pick] > 26:
                    cpick = list(pick)
                    rpick = cpick[0:len(cpick)]
                    rpick.append(state)
                    rtuppick = tuple(rpick)
                    if not checkset(rtuppick, mappicks):
                        mappicks[rtuppick] = returnpicks[pick]
         
        else:
            mappicks[tuple([state])] = newscore
    return mappicks


perms = checkmap(mapdict, 0)

Friday, October 26, 2012

Windows 8 Pro upgrade experience.

    Fortunately for my Lenovo laptop, upgrade integration went smoothly and nicer then I had expected.  I were able to do the upgrade even preserving previous side by side installations and master boot records with an existing Linux distro.  The value for the operating system excellent likewise.  The Windows 8 user interface may take some time for me to get used to but in fairness the same difficulties could have been much the same for Ubuntu's Unity.  Its seems the interface reminds of the integration of a tablet or alternate peripherals culture.  Here relative the browser based interfaces, laptop and desktops such users might seem to benefit less from the start menus window 8 integration messaging, email, and peoples apps, for instance, but in comparison it seems even on the Linux side of distribution, umbrella messaging app integration s appears to be a trend.  Honestly, in the some many years of staying away from facebook or twitter, I succumbed and signed up for accounts, alongside some others not withstanding Tumblr.  I am too poor, of course, to work extensively with peripherals: smartphones, tablets and anything else that could serve to benefit greater here, but for the value I couldn't complain.  Aside from the start menu and other Ubnutu"lensing" like aspects offered here, the overall desktop experience isn't so much a stretch from the windows 7 interface.  Pulling up applications by the way is a bit different...or at least I determined this indirectly using a pull the start menu > right mouse button > hit all apps combination to do the trick of finding apps not immediately listed in start menu.  Likewise if you manage to pull the search tab from the right side bar.  Here there is a locus trick with the mouse pointer that I hadn't figured out...if there were more of a tablet or surface like touch elegance found with the mouse pointer, I might be more dazzled by this otherwise.  If you were expecting for elation here with the desktop, or laptop that hadn't resembled a tablet, the value I think brings more here relative the upgrade from windows 7 to 8 that seems more so and so for a really new experience.  Generally speaking I hadn't lost anything to my recollection in the transfer of data and applications, and there again these days now with ever increasing use of web based applications and online storage filling the role of computing needs, I've found less hassle in moving to a new operating system, and otherwise, mostly I was prepared to lose my Linux distro for the hassle of a new side by side attempted installation, this time windows seemed a little more friendly to the alternate operating system presiding on my laptop.
     Lastly, this brings a theory to mind and why some users absolutely disliked the Unity interface and jumped ship from Ubuntu to Mint which retains some of the more traditional and conservative desktop UI.  It would seem windows 8 parses between a new design philosophy and the tradition having been the mainstay which were the desktop itself, I actually liked the new windows 8 start interface, the old desktop still reminds that something of previous cultural traditions are hard to die, or at least something of a resistance to the idea that the larger screens would vacate old desktop models completely.  The application switcher (pull this by toggling the thumb start link then on the same vertical axis hoover the mouse to the north of this location) might have hinted at possibilities here: forgoing all sorts of potential application screen clutter and thumb tabs that scarcely remain to be understood...okay more likely with the added tab too many in the browser.  Honestly I would have been even happier if my windows 8 seemed more then ever like an elegant tablet, however having the mouse peripheral driving the interface in some manner.  Maybe a bit much for many users vested in conservative traditions, but then the traditional desktop has been there and if windows 8 looked looked so much like its pre cursor what could one say of the next desktop generation?  

Wednesday, October 24, 2012

Rails 3 problems encountered so far

Working on Rails 3 application with Devise.  The problems that I have encountered thus far or opinions concerning Rails from what I have seen in the entry level context:

-  Database, Controller, and Views outside pre fabricated structures have posed as increasingly difficult with respect to the database object associations (many to one, one to many).  I've for instance managed to easily create controller and views in the path of one to many  (e.g., mapping from users any number of posts isn't so hard), but I've had a difficult time mapping views of the many objects in one fell swoop (e.g., mapping all posts from the set of users...sort of has and hasn't worked for me).  In other words, digging deeper into customization with Rails hasn't appeared as easy beyond the first glances of generate and scaffold commands.  

- Problems with controller to view and route interpretations.  I set a route_to view_path link in a given rails html file and the interpreter seems to think the page makes action call to controller method isn't a redirect to another page handling the call to the actual controller action but seems to think it is the page request handling data passing to the actual controller action.  Alongside the task handling of user sessions verification in Devise with a customized controller function embedded in say something like a Posts controller, management appears neither so quick and easy on the customization end.
  
I'd lastly mention, I don't know as a noob that I am such a fan of controller architecture in the view models...one it seems that queries to database objects themselves could be more independent of the views themselves or why each and every page should have some compartmental controller structure that makes routing for database access so difficult when simpler security layers could be embedded into the framework alternately, and data inquiry could be opened up...tempts me to try and construct my own framework relative to something like this, or at least alternately outside of .net there's Django...

Thursday, October 11, 2012

Rails 3 layout customization and gems stuff

Some interesting and possibly useful Rails Gems for website development that I've found thus far:
   -Authenticators/ user session login handling:  Devise
   -File uploader handling:  Carrierwave
   -E commerce system: Active Merchant 

File Streaming and downloading:  see Action Controller Overview

Contributing to this list as I go...

Wednesday, October 10, 2012

Some Rails 3 layout customization notes from a beginner

While starter tutorial is definitely helpful.  A few nuts and bolts that I've picked up thus far for layout customization aside from the more advanced assets pipeline guide.

  For general application wide style layout, the application.css is available.  However, if you need to reference asset data inside such css.  It may be important to change your style sheet from .css to .css.erb .  Assets pipeline guide indicates rails call where this applies (inside your html.erb file).  For this I'd cite the following applied examples:

@font-face { font-family: Yanone Kaffeesatz; src: src: url(<%= stylesheet_link_tag "YanoneKaffeesatz-Regular.ttf" %>); }

noting here the ruby url call is

<%= stylesheet_link_tag "YanoneKaffeesatz-Regular.ttf" %>

in this example.

Similarly,


header {
  background: #323534 url(<%= asset_path 'back.png' %>) repeat-x;
  height: 153px;
}

using the asset_path at least in the rails call inside your style sheet requires the .css.erb file path extension here for proper Rails execution of this line inside such stylesheet.

-I've used the public/assets folder for containing collections of image data in my site construction which links also to the 'asset_path' pipeline.

-In a given default Rails 3 application, by default the reference to, for instance, the application.css.erb style sheet will be found in the application.html.erb file

<%= stylesheet_link_tag    "application", :media => "all" %>

One would note the stylesheet_link_tag also controlling the link in the case to either .css or .css.erb stylesheets.



Setting up Devise with your Rails 3 application

The following tutorial provides probably the easier and simplest method for setting up a rail 3 web app using Devise authentication that I've seen. However, I'd additionally add that under your app setting up at config/routes.rb the following:
 default_url_options :host => "localhost:3000"

 or at least you'd want to set your default_url_option to something initially valid. Otherwise, you'd get a routing error.

Monday, September 10, 2012

A personal self philosophy


Inspired at the moment to the previous post.  Generally I tend to remain topically silent much on the matters of a self philosophy or anything relating to spiritual matters.  I would have to admit at times that I am far from perfect from a given self philosophy on the matters of personal choice.  Whether pertaining to things such as caffeine or nicotine, or other matters, and I could certainly work at times perhaps much to improve myself in terms of thinking and mindset.  I'd caution I don't consider myself a great spiritual adviser, and my training s with respect to theological matters are limited.  Although I've found myself interested at times in reading, or in other words, I would be simply a professed lay reader.

But given this, I found myself curious to the matter of the spiritual and any corresponding self philosophy.  I'd offer at least I believe many may have some spiritual belief or self philosophy in life as to the ways they 'get by' in life.

Here are some things to be considered:

1.  Self contradiction.   Have you ever said that you would commit yourself to living in one way, and then having found yourself doing just the opposite?  It seems there is a mindfulness with respect to the commitments made in one's life.  When I were younger, I might have been inclined to in my thinking more 'austere' commitments whether impractically working towards a set of goals that I've found little patience in pursuing in the long haul.  Learning patience it seems to me is a wisdom gained in life as is commitment.

2.  Learning to love the days that you have.  How often I could recall being so immersed in the idiosyncrasies of a day, or having been a day dreamer thinking I would exist anywhere but in the world that were here and now.  No doubt day dreaming could be the genesis of much inspiration and creative force, but it seems if you hadn't done much to change your environment and dwelling elsewhere, is it always constructive?  From my limited perspective it would be one thing if another had little choice, its another thing when you are empowered to make the changes that are afforded to you.

3.  Too much television or media.  When is enough, enough?  If you find yourself drawn into heated discussions constantly where you believed so much in the causes that were being framed for you to believe, were you living for others or yourself?  If you have the responsibility for others in speaking the truth of what you know with certainty with respect to cause and condition, there isn't neglect for this, but where often I wonder we learn the most of others could be found in our personal contact and experience with others, some of which could be neglected in media and televised presentations.  If you find your blood pressure rising watching another segment of what were supposedly an issue, the personal question of pertinence maybe in order.  How am I directly effected by such an issue?  How carefully does one judge a given world?  Is it upon the reliance of so many others in saying?  Is it formed solely by the consensus of selective channels and presentations, or is it based upon the direct contact and testimony of individuals that could attest their condition personally?  Maybe if having been angry too much at things that were going on hundreds if not thousands of miles away in another world, and having only precluded contact and little personal experience and wisdom, there is wisdom found in better judging one's immediate personal circumstance and condition?  Your spiritual wisdom and guidance is not a television?  Certainly if you find yourself being guided to the condition of loving less and being more hateful towards others, could one say that one were the better in the spiritual sense and lived a healthy life for it?  Honestly I find myself, personally attracted to the sobriety and objective interests of sciences, arts, philosophies, religion, sociology and what not.  I tend to be attracted more these days to objectivity rather then opinion pieces...granted this is an opinion piece in its own right at the moment. I am not so interested in being angry at what others do or don't believe, in as much as being attracted and shaping the social environment in which I interact.  I have to admit I am selective.  I am biased on this point. I've found as of recently.  I turn off the laptop and read, or make quieter space both literally and mentally in mind.  I selectively limit my television viewing.  I've refrained from playing video games which have drawn attention from much else in life.  I actually feel better mentally.  My mind seems a bit clearer.  I have decent focus and concentration.  I sleep more with a natural circadian rhythm these days.

4.  Constructive time use.  If you're work in life were a guidance here, I've found avoiding dwelling on things which go beyond my control and time.  It seems to me organization and structure in life helps a lot.  Whether in sense of creative expression, art, or as I've read from others, hopefully, one paradoxically lives neither in a present life but in thought of some vicarious idea of what life should be later down the road which may never come to be.  If worry is there to serve change, then change, so that worry comes to pass, but if it serves no purpose legitimately in one's life as expressed in a warranted condition, then perhaps analysis of worry should be made?  Is it legitimate, is it right to the conditions of one's life?  Or is it an excuse for dwelling in thought?  It seems if one were to harbor worry so much to the detriment of personal health, and nothing of eventual change is made of a given environment, something must change with respect to worry?  Secondly I'd mention on the part of cognitive behavioral patterns, if your life is structured around the idea of dwelling negatively in some manner, the conditioning of patterns in thought are self reinforcing?  In other words, it should seem the mind is conditioned to structure some routine in daily life whether deliberated more thoughtfully or not.  If one finds oneself into positive mindful habits with that required so much less momentum and effort on our part, maybe it is easier to engage in such pattern of behavior without so much effort and thought in successive applications of retraining the mind, and finding the wisdom of an order and discpline.  Personally I am not into rigorous physical training regimens, or self punishments, nor seeking of disciplines that could be so austere as to be dropped with respect to the everyday practical conditions that one faces.  Locomotively, maybe walking could be preferable to running, or at least over the years, I've learned to slow my pace down, and neither produce so much lactic acid.  I've read so much to the balance and baseline of energy levels.  I've had my up and down days in the past, but my energy seems more balanced.  Eating adequately seems important, as does being well rested.  I am not so much into being over stimulated like I were when I were a kid.  This isn't to say that at times I weren't perfect in this sense of being or seeking at times.

5.  Admittedly a self pro crastinator at times.  Maybe this isn't so good all the time, but then I found a philosophy professors statement on this issue compelling.  Think of the positive accomplishments that you have made, and dwell less on what hasn't been accomplished.  It seems the antipathy of structure and order at times, but at least I'd offer if there were an analog in nature, nature may not always serve to be the most efficient or 'productive' in the engineered sense.  If we learn to find ways of managing ourselves in the sense of finding structure and productivity in the balanced sense, we are also neither machines that struggle minds and bodies to the artificial structures that we might have created for our place and sense in life.  Learning to find relaxation and rest are important.  Admittedly 5 seems in contradiction to 1, and that it seems is part of the mystery of human nature.  We aren't entirely logically driven, nor without sense of emotion and something at times irrational, but at least it seems there is something of a happy medium here?

6.  Peers and friendship.  Wisdom comes in chosing friends wisely.  Many probably are already well aware of this.  If someone has something of constructive criticism to offer, and this is neither meant simply to serve for some purpose of personal dislike, or any opinion that could likely never change could be reflective of the environment one chooses to live in.  Those that dwell in the experience of so much fixations in life to the detriment of relationships and all else, providing little time for others are probably not great friends.  There could be much added to this list.  Enough said.

7.  Dating and relationships.  Not much of an expert here sorry.

8.  Violence.  I see this from the perspective of human evolution.  Those that suffer in violence in the long term sense probably don't fare well, and this is probably for good reason.  When violence cropped up so long ago, likely it seems it were neither driven in the artificial sense to wars extending decades, centuries or extended lengths of time.  Likely when relating to internal conflicts, maybe these were likely to end as quickly having begun.  Certainly if the human mind were resilient to violence and conflict in the short term sense, evolution would be less of aid to those subjected in the long term sense to violence in the social organizational sense.  While some could claim it is part of human nature, civilizations has at times made something unnatural at times by violence...through the power of technology and industries themselves which aren't exactly natural I believe to human physiology and psychology.  We believe we adapt to the weapons that we have fashioned, but where clearly have we adapted?  What inhibition to violence should exist as it might have once existed in more natural orders with respect to the wisdom and strength of elders in a given community to correct any of violent behavior (a natural equalizer) lost with respect to the kid that could pull the trigger of a handgun without so physical reprecussions that might have once existed?  The modern weapon is too easy a faciliatator of violence.  Much of the natural world is dictated by the reprecussion of violence in animal behavior that neither exists given the artificial structures of the modern human world.  I believe this is the great imbalance of our western civilization.  A bruised eye, cuts that can heal, and someone having retributive fear of engaging in such violence are much different then tools that potentially facilitate violence to obscene levels without so much fear.  This aside we are intelligent beings, if it should seem that violence is unnecessary with respect to resolving differences, it is that our societies should have so much to say with respect to law, ethics, and our spiritual beliefs.  What remains of the natural order of human nature pertaining to violence, when peoples could be mobilized by mechanized transport, armed, sold to artificial propagandas promoting violence.  How natural is this relative to the ancient human colonies once having existed and limited so much on foot in communicating through natural alliances of neighbors to promote some level of violence that should pale by comparison.  Is the actions of human nature so unnatural in propensity to violence, or is its modulation profoundly induced by the artificial structures and technologies of civilization which again has promoted this to obscene levels unparalleled in evolutionary history.  The tools of communication, logistic transports, weapons, all reflect the great imbalance of civilization with respect to human nature itself when employed in such a way.  If we are taught to listen through selective channels to hate without question, taught to kill or be killed, to be armed or die, then what choices do we perceive otherwise in life?  If we see only the normative condtion and being in others around us and we fear questioning, how are we to change otherwise?   Thus referring to another post on the subject matter, why violence (and political violence here in America ranks the highest in most past wartime situation excepting the Korean war) should occurs likely has come from the propaganda and the artifical constructions of a given society itself in promoting this in the systemic sense, has it not?  Does this reflect some other imbalance of a given civilization.  I am not here to say that human nature is necessarily so different then it ever has been with respect to some basic condition, but I would say that are social environments themselves could be conducive to the promotions of artificial levels of violence that have little to do with human nature.  Our spiritual imbalances occur when we are not right in the mind to see through what we are told to believe.

At times it seems much more courage could exist for a person to speak to enemy with the intent of non violence, so much better in my opinion for a non violent man or woman of courage if such virtue should exist.  


And some of the very basics of a personal philosophy...

Make a self environment of peace.  Make a loving environment for self and family.  Those closest to you, whom love, trust, and respect you are part of your home.  Avoid dwelling in hate, fear, and worry.  Be willing to learn and see beyond immediate differences.  

Monday, August 20, 2012

The relation the cosine angle between vectors and their inner product
















This shows the plane triangle with vectors x, y, and y-x where the coordinate axis are defined in terms of the plane of vector x, or in three dimensions, the vector x on the relative plane of such coordinate axis can be thought as having x1 = relative x component, x2 = relative y component. Noticing that the direction y3 a relative z component is perpendicular to component plane of x1 and x2.

First, I'll address why the inner product must be zero for two perpendicular vectors.

For two given vectors x = (x1,x2, …, xn) and y = (y1, y2, …, yn), it should be noted that two vectors are perpendicular if







This results from the Pythagorean formula where the magnitude (distances) of each side length of the vectors on the left side of the equation squared and summed equal the magnitude (distance) of of the vector x-y on the right side of the equation.  One would note the relation of vectors above with application to the Pythagorean formula, while the figure above demonstrates relations here in three dimensions, this application extends to n dimensions likewise.


Expanding the right side of the equation (1) we have







we'd note that expansion of the left side of equation (1) leads to cancellations of the terms


  





Thus we are left with the requirement for the given equality that the central group of terms in equation (2) are equal to zero, or the “dot product” (or inner product) of vectors x and y are orthogonal if








Now getting to the relation of the cosine angle between two vectors x and y.



















We'll demonstrate the relation of the inner product using the figure above which is shown in two dimensions. Note this could be extended to n dimensions but for now we'll focus on two dimensions in deriving the relation between the cosine angle of two given vectors and an inner product.

From the figure above one can note the following relations,




  






Now using the relation θ = β - α and using the known trigonometric sum/difference identity and substituting the relations above we have









This can be generalized to any vectors of n dimensions such that









Sources compiled from Linear Algebra and Applications, Strang, 1988.


Friday, August 17, 2012

Prime natural as evidenced in biological life

Watching 'Through the Wormhole with Morgan Freeman' which discussed alien communication through prime numbers which discussed the possibility through genomics.  Interestingly enough I would suggest the gestation cycle of the Magicicada which is found to be in prime number cycles 13 and 17 years.  It were theorized natural selection produced such variation on the basis of survival advantages relative to predators whose gestation maximums were non prime variants.  Interestingly enough while this sort of gestation cycle I would guess is extremely rare, it does give natural advantages in terms of evolution.

Building simple mathematical diagrams with free software on the quick

Some methods in constructing formulas and diagrams on the quick here.   There may be some decent software out there for free which does much the same, or otherwise pay for software that can construct the same.  Aside from free math plotters which abound on the internet, and especially free software for python (if you program in this language) like scipy, matlibplot, gnuplot, and the like.  If you were wanting to set up diagrams really fast, you could use programs like Trimble Sketchup (used to be Google sketchup) which I've found to be the quickest and easiest in setting up plot points and setting up perpendicular angles on arbitrary axis.  Generally with graph construction, I make sure the camera is set to a top view, and then plot any number of given points.  Sketchup is nice in providing a fill for a given set of inter connected points, like lines, squares, arcs, and so forth which makes for much more graphical aid constructions in math modeling in some respects, albeit for more complex curvatures and shapes, you'd probably resort to other methods, or learn, if the interface is still available, using Ruby interface which is sort of python like but different. Once having constructed your graph and having appropriated your view perspective to the appropriate level from such perspective you can obtain a 2d rendering by simply hitting the print screen.  If you are running on windows, keep in mind you'd have to open up a graphics program (like Microsoft Paint which is provided for free) and then click the paste button in Windows 7 to paste the bit map photo into your program from Window's clipboard, or alternately if you are running SketchUp from wine on a linux distro, the print screen method (in Linux Mint and Ubuntu) are the same, the output print screen goes to your home folders Pictures folder generally speaking.  Here, generally you can do some simple photo cropping and the graph is ready for import into any desired text editor or alternate drawing program.  In this case if I want to add formulation into the graph, I've used the LibreOffice Drawing application.  This is nice since you can provide graphical formulation overlays to a given imported photo, and customization in terms of the typesetting of formulation text relative the photo (or in this case the graph) can be situated generally as desired although I haven't figured out how to rotate formula object text overlays in this case.  Once the given graphics are as desired you can either export to a desired imaging format, or as I've done I simply snapshot the perspective view again, and crop the photo in a given free image editing software (Gimp in Linux, or Shotwell does the trick).  Keep in mind if you hadn't like the standard gray imaging fill textures native to drawn mesh objects in SketchUp you could import any desired texture for filling the surface if you hadn't like the graphical diagrams object textures.  Just need to add this in Sketchup before rendering your snapshot, and then follow the steps as desired for adding formula objects to the given text.  Generally speaking this works well for simple mathematical diagrams especially when dealing with those requiring models designed with orthogonal (perpendicular) lines and simple curvatures.  

Exploration of the Bézier curve


Special case of the Bézier curve is as follows.

As pre requisite recommend reading about the Bézier curve and De_Casteljau's algorithm which provides geometric interpretation to curve construction here.

Where a curvature in a local coordinate system has no inflection points and can be described by one local maximum where this is defined in terms of a local y position where a relative coordinate system defined by the plane between points P0 and P3), and given two points P1 and P2 such that the relative positions y1r and y2r on such plane are equidistant from the tangent of the line P0 and P3. A local y_r maximum is given by








where and θP0,P3 represents the angle of the tangent between the segment (P0,P3)


Proof:
We can rotate and translate the given coordinate axis such that such that the P1 represents a given origin 0,0 on a relative coordinate system, and furthermore we can ensure that rotation of the coordinate plane also matches the tangent line of line P0, P3, so that y0, and y3 are zero while x0 and x3 are not equal. By assumptions above
y1 and y2 are equal and remain so under coordinate changes so that are Bézier equation becomes for the y relative in the parametric form  








where yr(t) is the parametric form of the Bézier equation in our rotated and translated coordinate plane. Keep in mind that the parametric form on the rotated plane preserve the magnitude and the relative positions of P0, P1, P2, and P3.

taking the derivative with respect to t we have








as long as xr(t) is not simultaneously 0 at t, the derivative dyr/ dxr takes the form dyr / dt / dxr / dt
setting this equal to zero means that we are concerned with the zero in the numerator,

so we solve for yr '(t) = 0

In this case a maximum slope on the relative coordinate system is found at

t = 1/2

Substituting t = 1/2 into the equation yr (t) means







or








we need rotate our coordinate P1 to relative coordinate along side providing a translation of such coordinates as this provides a sense of scale in the rotated coordinate system on the relative coordinate system relative to original coordinate positions, or this is to say, expressing the local y in terms of control point P1.

A translation can be defined with an affine transformation.


In order to express P0 as a point of origin on our given transformed coordinate system.

or in the case of our coordinate P0 this is written  










while a rotation in coordinates is defined by


  








Thus we can see that P0 is zero under the series of transforms with




  






where this resultant vector (0,0,1) time the rotation matrix is also zero.

We can see that P3 is zero on the transformed y relative under the series of transforms with the affine translation.


rt*tr*P3  

for the affine transform










and for rotation











Here examining the y relative component of the transformed P3 position we should notice that y relative coordinate component is









geometrically one can see this from the following graph showing the rotation axis and original axis

The graph will demonstrates points are already affine translated




















Here where θ in the graph equals the given rotation angle defined above we can see the y' components cancel when subtracted which results from the rotation matrix transform and the point P3 - P0 lay on the zero axis of the new rotated coordinate system.



Similarly under transformation y1r can be expressed in terms of P1 as





Thus for any coordinate point we have a transform which is



  

  




substituting eq. (2) into (1) we have


  





We can check that the t = 1/2 doesn't simultaneously equal to zero here, for xr'(t).

If we wanted to find the original positions x(t), y(t) for t = 1/2 we can either re transform coordinates
using the inverse of the transform matrix above, or we could compute the Bézier curve for t = 1/2
which should remain relatively invariant in so far as the arrangement of points overall for the given
curvature. In other words, rotation and translation only changes the position of all points equally not the relative arrangement of points for such curvature. Why is this?

The Bézier curve geometrically computes on the basis of the relative arrangement of points in determining the shape of the curve, the relative arrangement of control points control the shape of the curvature, but this remains invariant (unchanged) under rotation and translation.

In other words, if the relative angles remain the same between control points alongside preservation of magnitude, these will determine the points on the curve which should be relatively the same irrespective of choice in coordinate plane. Geometrically speaking the points of the polygon formed initially by the control points are the same relatively speaking in so far as distance magnitudes, and the t parameterization on the relative coordinate systems trace the same relative distance when constructing a solution on the basis of relative spatial subdivisions. In the case of the cubic, a triangle is formed irrespective axis at point t0 on any axis consisting of the same side lengths, and this in turn leads to a line subdivision of the same magnitude line in length irrespective of axis at t0 which determines the point on the Bézier curve. The points themselves are variant under rotation and translation but not the shape of the curve.
It would be worth noting that in the original coordinate system the relative maximum computed t = 1/2 may not the maximum of the curve, or a given slope = 0 at such point, but the relative coordinate

Monday, August 13, 2012

Gauss' Quadrature (Integration) – Formal


Covered chapter 19.3 from Numerical Methods for Scientists and Engineers, Hamming.


If having followed the previous post, which introduced the formulation by way of sample points as parameters technique, one will now have some understanding with respect to the ideas presented on this next topic. The ideas are really the same except generalized a bit more. Prerequisites here are also the same. There will be use of series summations included in this topic. As a refresher to series summation, I'd present the following series here and define a sequence alongside this.

Firstly, let's consider a simple sequence like  

a = {1, 2, 3, 4 , 5, 6, 7}

Here the series of a is written









or we can also express sequence of a as









where the sequence {ai}is written







Now introducing Gauss quadrature integration. Let N points exist such that



  





where both the weights and the sample points are regarded as parameters.


For all wk and xk we have a total of N wk xk terms which means there are N+N = 2N parameters in total.

The defining equations in this case like the previous example posting are generalized with 2N defining equations:














 As in the previous posting we use a polynomial only it is composed of N factors as opposed to 2 meaning this is a polynomial of Nth degree








Remember before when we had a polynomial of 2nd degree, we had 2 coefficients c0 and c1, in this case we have N coefficients c0, c1, …, cN-1. Notice the sequence case pattern here?

Procedurally we'd do much the same as we did in the previous postings which were to multiply each of the N coefficients c0, c1, …, cN-1 respectively times each of the defining equations above, or in the generalized form, we multiply the j th equations by cj and sum these equations which takes the form









noting here that xk is a factor (or zero) in the polynomial π (x) and zeros the polynomial.

In the previous posting it were more or less demonstrated that the added cj multiplied mjth equations plus mN th equations would lead to grouping of terms leading to a given wk π(xk) series. See the previous posting example for the case N = 2. As it turns out the same as generally true for all cases of N.

Procedurally like the previous posting, we shift the multipliers cj down one line and repeat the process to get











Thus we have 2 equations of this form so far. We need a total of N equations of this form so we repeat the process of shifting our multipliers down to the k th case so that which results in N total equations of this form. Where the final equation in such equation generating sequence is


  







At the moment, will for go providing an example here, but it suffices to say we can use the same methods found solving the set of N linear equations for all coefficients c0, c1, …, cN-1. You could apply solution techniques found in linear algebra to accomplish this.  Once having coefficients for the given N the degree polynomial one would have to determine factorization here.  Fortunately, there are methods for doing this, but this extends beyond typical high school and college algebra.  Here is a link to some factorization techniques however.  Probably wise to have a computer or computational aids to do much of this since much of this may require number crunching and extends beyond what one might want to do by hand in this case of higher degree polynomials.  Having this, we then reapply the same techniques to solve the the N generated equations for our given weights w0, w1, …, wN-1.

Also we can apply this form of integration with respect to any function f(x).  Here we did so where f(x) = 1.












Saturday, August 11, 2012

Formulas using sample points as parameters.


Providing some added information to the examples chapter of the book Numerical Methods for Scientists and Engineers (19.2)

The problem is estimating the following integral from two samples:








The parameters here are w_1, w_2, x_1, and x_2. Just as in the previous posting we use four defining equations. Why four and why not three or less? As it turns our for each parameter we need to construct a set of unique linear equations to solve all of the given parameters...this follows from Linear algebra regarding a problem of 4 unknowns, so we'd need for four sets of unique linearly independent equations to solve each such parameter.

Thus we start using exact equations for f(x) in successive powers of xn where n = 0, 1, 2, and 3 in this case.

So the defining equations are :












Keep in mind the book actually evaluates these integrals, and I'll provide some brief explanation on evaluation techniques here.

For equation (1), we'd need to evaluate the definite integral on the left side of the equation. This could otherwise be rewritten as








Remember that while ex approaches a infinitely large number the inverse of this approaches zero. Also remember e0 = 1, from basic natural logarithmic identities (college level algebra).

I'll cover integration techniques given by integration by parts for equation (2), and then we'll rely on a handy integration tables formula which is








this formula can be seen more clearly in our given methods found in evaluating the integral from the left side of equation (2). Namely integration by parts in successive application occur here.

Also I'd mention at this point, we can also use another handy rule known as L'Hopital's rule which goes as follows:











Thus, for instance,









is in indeterminate form, so we can apply L'hopitals rule. Noting e-x = 1 / ex.

Thus we take the first derivatives of f(x) = x and g(x) = ex which yields









We can apply successive nth derivative applications of L'Hopital's Rule in the case of a nth power of x for the indeterminate case successively occurring so noting the factorial in the numerator after successive derivatives is a constant in the evaluation of such limit and thus is fixed 










By the way a factorial if you had forgotten is n! = n*(n-1)*...(2)*1
Thus, 3! = 3*2*1 for instance.
Let's go ahead and evaluate the integral of equation (2) on the left side

Using integration by parts, we have

















For the integral in eq.(3) on the left side, we'll use our handy integration formula eq.(5a) to evaluate (which is basically an integration by parts formula) here. We'll use the results of eq.(7) to further evaluate this integral.











Finally we'll evaluate the integral in eq.(4) on the left side, we'll use our handy integration formula eq.(5a) , and we'll use the results of eq.(8) to further evaluate this integral.











The defining equations (1), (2), (3), and (4) can now be rewritten using equations (6), (7), (8), and (9) as













To the right of the defining equations are coefficients c0, c1, and 1.
These are to applied to a polynomial that will be used for defining our sample points.

The polynomial we use is a second degree 








multiply eq. (10) by c0, eq. (11) by c1, and eq. (12) by 1, and the add these equations together so










Using the second multiplier column to the right of the first column on eq. (10), (11), (12), and (13),
we reapply the same process again as in (14) to get









We then have from eq. (14) and (15) two pairs of linear equations 









The solution to this is c1 = -4, and c0 = 2

These are the coefficients of eq. (13a), so we have






The quadratic equation solves this providing samples points 









Applying these sample points to the defining equations (10), and (11) gives


 




 
Again we solve these linear equations for w1 and w2
which yields










Our formula above becomes









indicated “exact for cubics using only two samples of the integrand”.

“How did we know that the weights we found from the first two defining equations would satisfy the last two equations? The answer is simple; we choose the xi so that the last two equations were linear combinations (with coefficients c0, c1, and 1) of the first two equations; hence the wi automatically satisfied the last two equations.”

Numerical Methods for Scientists and Engineers, Dover, pg.319.







Oblivion

 Between the fascination of an upcoming pandemic ridden college football season, Taylor Swift, and Kim Kardashian, wildfires, crazier weathe...