Sunday, April 29, 2012

Irony ... one wonders with too much desire comes room that must be made for much else.

CNN show on sugar

Apples ancestors The wild ancestors of Malus domestica are Malus sieversii, found growing wild in the mountains of Central Asia in southern Kazakhstan, Kyrgyzstan, Tajikistan, and Xinjiang, China,[3] and possibly also Malus sylvestris.[4]

One question about this particular fruit, how long on average might this ancestral fruit have lasted in a natural setting without human intervened processes. In these regions while micro climatological conditions might vary, generally speaking, very mountainous, and desert like, is it possible that nature itself could allow for the preservation of any fruit of this species for months on end, not unlike storage and distribution ends found today in our market systems? The reason that I suggest this is that it may be a misnomer to think that sweetners and fruits and found in nature have a very limited context in diet from crop fruition to longevity of the fruit severed from its life giving preserving mechanisms (in truth this actually might persist for a time even after a fruit has dropped from its tree?), and that nature itself in some context might have naturally facilitated something of graduated caloric access to these types of fruits. However, likely these natural conditions could be limited enough and one is to wonder the extent of biological influence here, both in eventual crop cultivation and in its ancestral wild origins. If the model of adaptation and survival were true, the view of human evolution and diet could be one I imagined constructed from feast and famine cycles, bounty at times, and dwindling food supplies at other times. Sugar the exact culprit here, no...I think calories could be part of this equation as well. The aspect of evolution from the standpoint of smaller windows of time are such that: humans may have likely evolved in ways not unlike many other animals, such to be non discriminating in so far as calories provided, the human body however, likely hadn't evolved to discriminate as well and likely culprits of a calorie source beyond the immediacy of biological survival and with respect to biological sexual reproductive fruition. This means if the sugar kept you alive to your sexual reproductive years, it served its purpose, however, genetically you probably wouldn't have weeded out problems like type 2 diabetes that might ensue in later years. Refinement and extraction of fruit sugars it seems could be very problematic to the natural prevalence of calories of this type, and it seems links to early manifestations of health problems in a growing youth segment of population could be something of chronicle to this. In terms of diet, however, I would wonder whether sugars are to be vilified completely. This is to say maybe not all sweets are the same...if given a choice between a candy bar and a piece of fruit, the fruit should win out any day right?! I mean the fruit could likely be packed not only with any number of micro nutrients that a highly processed candy bar might not provide, a source of hydration, that a candy bar even loaded with desiccated pieces of fruit meats wouldn't provide, and generally speaking sparing more fiber aiding in the slower metabolisation of sugars present here. The problem isn't sugar alone, its how sugar is used and consumed in diets generally speaking. Personally I have heard some talk about sugar being all too offensive regardless in diets and refusing to grab a piece a fruit in claims of health, but then turn right around and grab an alcoholic beverage, and/or something laden with sugars, far less healthy in my opinion neither aiding their health condition. Maybe the debate shouldn't be on eliminating sugars completely, but learning to gravitate towards healthier sweet alternatives that aid moderation in consumptive practices?

I say this somewhat cautiously in some manner here, I think distinctly there maybe any number of variations of dietary practices found worldwide, neither providing exacting formulations for better 'diets' here.  If you had significant ancestral lineage in the polar artic regions, you might be better suited to certain high fat, high protein diets, so optimal diet could be varied and diverse depending on your genetic ancestry...This being said, something established by evolution, if you are likely well adapted to consume just about any food you like in the short haul like any other human (allergies and what not permitting), but in the long haul you might adapted in different ways relative to others in so far as the type of food stuff you are putting in your body.

As to diet types, eliminating wheat..hmm..interesting diet, although I would suggest it may be a misnomer to think that grain consumption was altogether non existing in hunting gathering societies...depends on what society and where you are talking about.  In the polar or southern areas, yes, probably likely no access to grain, in mid latitudes, more likely...examining ancient American and Central American  prehistory cultures , throughout Asia, Mediterranean areas, and likely one would find evidence of limited grain use in some subsistence based form.  So to say that grain consumption and use were unnatural to human biology in the endemic fashion that we find today relative evolutionary history, may not be an altogether correct assertion.

Sunday, April 22, 2012

Small computer $25.00

Raspberry Pi

Very small computer, just need to find a small touch screen monitor say 10" or so with video connection touch peripherals connections, ensure the OS has touch screen gestures packages enabled, and you'd be on your way to having a custom tablet.


Problem, big screens appear to be cheaper then small ones, and small ones are generally packaged as all in one integrated systems.  :)

But still interesting little computer.

Amazon Kindle

   I were a bit reluctant at first to give much notice this to this device, happenstance bought for another person in the household, but after tinkering with the device here, a lot better then I had expected-.  One, while having something proprietary such as the Amazon name attached to it, and potentially anything else that might go with this, such as a locked format for file importation and additionally locks on files for transfer say from one device to another, it seems fears weren't entirely correct here.  Actually I would suggest, for instance, an application such as Calibre which could convert from any range of file formats to an existing reader format.  You find a wiki book online in .pdf just use Calibre to transfer it to a kindle (.mobi) format, and the same could apply to other information found at any other sites, provided you could get this in some conversion compatible format.  Likewise, it seems if you wanted, outside of access to any current bestseller's publication, access to say classic books, you could find publications at Gutenberg which provides access to any number of books for free.  I would hope Amazon and friends come up with something compatible to existing library infrastructure in so far as loan and lending commonly found in our public library system.  There is always the option, through Amazon's site to Amazon prime subscription which provides limited loan access (appears to be limited to either one loan per month, or one concurrent loan at any time during the month for a particular book that can be loaned out).  At present, for a monthly subscription relative to existing public library infrastructure, a public library in so far as loan potential could seem in many ways much better in terms of options (library permitting), but it seems public libraries themselves may be growing in number potentially offering public electronic reader users the same type of access that might be had of printed media.  The advantages, however, between print and electronic media it seems in theory are that, one hadn't need deal with late fees, lost or books in dis repair that need be replaced.  Here, for example, once a books loan term expires.  The royalty paid for book copy need not be returned physically, simply its existence on a user'-s reader just need be removed, and accounting placed into the circulation system for update where a copy download could resume for any interested loan user.  Of course, prime subscription provides limited access to any other multi media outside of publications, which could seem reasonable, as to buying a copy of published media prior to reading or seeing this, I would offer that the loan option for many households would seem more reasonable, and if someone felt more compelled to have it for permanent use in a library collection, its purchase could be just as likely had.  Of course, added to this it seems not only bestsellers or any range of popular publications are less costing here, but also academic textbooks themselves, lacking the added cost of printed paper media, tend to be less expensive, and sparing trees in the process.

All in all it seems book library loan options on the web, could improve more so, to make this device that much better, but I would still at least rate the device fairly high in providing users the ability to create custom libraries and neither have to do so purchasing every bit of information that exists on the web or elsewhere.

Codebreaker death

Never knew there was a MI6

Spy found sealed in his own holdall (called a giant 'dufflebag' if you are American), or could be Turing de ja vu?


Friday, April 20, 2012

Blender fun today
















Marble texture on 'candle holder' object a bit off towards upper stem half.  Didn't feel like remapping uv s on the vase object to the right so I did a normal map, sort of weird, but I liked the effect, and then placed on a flat plane the same texture, set higher reflectivity values here, textures on this are a bit blurred likewise.
















Blender source file for picture above













Some notes on design above, using scaled extrusion to create
windows, this is 'E + S + Shift Y' in this instance,
which creates an extruded resized face inside an existing face depending on how much value you provide.  Then translating the inside face by a desired amount on its perpendicular 'normal' axis (in this case on the y axis). 


Blender source file for this picture













Blender source file

Linked lists in python necessary?!

I know in a previous post suggested a linked list...why would you use a linked list?!

Well, it seems if you needed an ordered set of data in any manner of typical type ordered construction, dictionaries, list, sets, or any manner of typical python would be just as practical.  However, it seems in terms of organisation of data itself, the linked list could have purpose here in python.  Consider a bulk list of custom class objects that needed to be stored in a list ordered fashion here, if you hadn't wanted to use say a dictionary to store such objects using say a key string value or some sort of key code, with linked list structures you could instead define attribute data as a key instead.  Thus instead of a reference to class object

ordereddictionary['key']

to such object, with a linked list you could instead redefine a given key as

orderedlinkedlist.key


Here's a very simple linked list class structure with method for writing to

class Storeobj:
    def __init__(self, a = None, n = None):
        self.val = a
        self.n = n

cr = range(0, 5)
b = ''
collect = []
for x in cr:

    a = Storeobj(a = x)
    if not type(b) == str:
        b.n = a
        collect.append(b)
    b = a
collect.append(a)

x = collect[0]    
while not (x == None):
    print(x.val)
    x = x.n
           
for col in collect:
    print(col.val) 
 
Explaining some aspects of code above, aside from examples of a similar sort provided on this topic implementation in writing to linked lists are another matter.   In the loop,
 
for x in cr:

    a = Storeobj(a = x)
    if not type(b) == str:
        b.n = a
        collect.append(b)
    b = a

one Storeobj is linked to the next in the assignment of Storeobj.n = previous Storeobj(a = x) noting that the previous store obj in the loop were at the assignment call b = a.

. In this case, for the linked list, we hadn't need use a collect list object but we could still use this, illustrating the purpose of python's list container in so far as use as an ordered list likewise here.


Technically in terms of the ordered list it seems on the while loop is slightly less compact, however, given other possibilities depending on the extent of a linked list object's attribute structure could provide some differences here?!

In other programming languages I had imagined where type restrictions on container objects themselves offered difficulties in the re implementation of extensive data structures and class objects themselves when any particular number of distinct instances of these need exist simultaneously, the linked list proves of help here.  In python, however, flexibilities in type storage allows for custom data types to, however, be stored in python's natively defined data container structures.  This means, that the list (like the array in other languages) could easily be constructed as an ordered list like the link list, only using array like code conventions here serving the same purpose and sparing some effort here, if your ordered list is simple enough.

While avoiding linked list at all costs could be very pythonic in terms of code structure, I'd also mention in terms of larger more extensive data structures, reading clarity might be aided here using linked lists in python and possibly aiding in translation to other programming languages.

Wednesday, April 18, 2012

Crossword generation algorithm revision

Remove fixed set perpedicular dictionaries prior to puzzle construction.  Use a single set dictionary instead, to pick words from and assign as needed words in crossword from this single set.


2.  Implement backtracker, however, record processed data  up to all potential backtrack points, to avoid recomputations.

3. remove existing ranking system, instead implement additional
ranking system that measures word/letter density (over iteration cycle).

4.  Remove squarness test, as word/letter density metric may compensate, or implement squareness test
over larger iteration cycles...there may be overlap bettween this an density ranking?

method: We start with two cycle iteration, for example, from horizontal, fill verticals, then fill horizontal, then rank, then repeat steps on all 1rst cycle matches from the fill verticals step, reiterating next cycle, rerank, and repeat as necessary until constructing all match variations from the first cycle and all possible match variations on the second cycle.  Pick the highest density rank, measure squareness, then picking edge work a new starting edge cell line to balance for squareness, and repeat this process all over, and so forth until have removed either all or a ranged target of words from such set.

positives here:  again avoiding fixed boundary conditions for puzzle generation, but implementing weights on puzzle generation growth measures, this increases probable growth favouring higher word/letter to space density arrangements (more likely leading to more densely filled rectangles or square fill patterns), and then attempting to weight growth in favour of squareness by picking new 'cell' edges along a desired growth line.  While this does some hard number crunching for picking variation of matched words on the fill pattern.  Once a subset fill pattern has been chosen, I avoid hard back track fill re computation of such space...hmm, one way of thinking of this is building many crosswords inside a crossword.  Once building a crossword a decent subset density crossword, build another high density crossword subset, and so forth, until filling using all desired words, or a given range of words, keeping the total fill pattern arranged as square as desired, and weighted inside a target total side length range.

4/19

backtrack: 
   definition:
     iteration cycle: for the context of this program this refers to the cycling through of all work queued words on a particular fixed dimension of the crossword.  For example,  three words, ('cat', 'dog', 'iguana') are added to the work queue, these are worked on the HORIZONTAL axis,
     Finding all vertical word matches for these words in turn represents one iteration cycle.
    
   Data records:  1) All data gathered at iteration snapshot, key cycle iterations.
   Construct an adequate key for iteration cycles. Hmm...since for any seed word  on a 2 cycle iteration, there should exist for such seed a key of length, len(seed_word), we could use a key tuple value for this in our tracker.
  
   After all 2 cycle iterations of a word are complete (in terms of all permutations of matched words to such word), then a highest density ranked crossword sub group (sub crossword) is selected  positions are recorded and all data records are discarded.
  
revision: will revise squareness test at the moment, to measure and record alongside picked sub group data attributes -coordinates, words, letters, and word orientation, the length, width attributes for the respective subgroup.


method revision:  2 cycle iteration permuation groups determine a subgroup for a selected word, repeat this process of the set of all words until having sufficiently exhausted all such words and having constructed, a family of subgroups.  Then with attribute data of subgroups, proceed to build,
a larger group representing our crossword.  I'd leave the possibility of rotational matrix transformations open so as to provide additional fit possibilities as necessary.  This means we hadn't need position a seed selection word for the base of such subgroup in any particular oriented fashion firstly, to meet fit
criteria latter, since we can rotate this subgroup as necessary.

So the one thing to be added here, it appears that removing weight ranking selection at every pick and instead opting for trying out permutations for a given 2 cycle iterations leads to on first cycle for a seed word,
number of letters  = len(seed_word), and for each letter len(of word matches).

This is total of  a[0]*a[1]...a[n] represents n letters and a[n] represents the length of word matches on the nth letter, permutations, the next set grows even larger for each set of picks in a[0] thru a[n] where each word match leads to its own similarly expanded set of letter to word association groups.  Something of a computation suggestion here.  The more words left in your dictionary has the potential to create nicer more dense looking crossword structures ( I would guess here), but computation time spent could increase dramatically here even with 2 iteration cycle caps.

I created an ordered linked list on the permutation set here for keying computation data at least for structuring letter to word associated keys.  

Tuesday, April 17, 2012

Copyright on language

Possible copyright on languages

in a way done for centuries...just waiting for forced cultural assimilation practices here.


Sunday, April 15, 2012

TED talks neurological experience

TED talks episode, somewhere seems that I remember reading an article about the neuroscientist whom had the stroke.

Oddly had the funny experience years ago resembling something of right/left brain activities imbalance here, disassociation, environmental stimulus sensitivities, although never so much felt described in the heightened sense as in her descriptions.  Nonetheless illustrating so much of what we take for granted that our brains provide in feedback to our environment.

Typically it seems for me what I could sense as trance probably comes closest to what one could describe as possible free disassociation but quite different in the sense of loss in personal mental control over experience without adaptation to sense here, interesting that 'self' is born of left hemispherical dominance here.  :) 

Human ingenuity

Essay... Hmm...thought about the benefits of self replicating, utility bots that would manage to not only learn in time from its environment (by way of evolution), but also the ability to impact to aid a particular civilisation. Seems, of course, one of many abundant much talked about dangers here...lifting a bit from another science fiction writer, supposing greater dependencies on robots to do the sorts of works that become more and more physically, intellectually challenging, what should happen if systemic technological collapse ensues. It seems already something of threshold has been imagined. Significant electro magnetic disruptions, for instance, in nature could cause enough catastrophe if globalized here...and we aren't talking just in the sense of disruptions to transport and communications networks but likewise, chemical/nuclear/biological/what not industries management collapse leading to significant environmental catastrophes, but if technological collapse is self evident in some manner where recovery is to too long in coming what should result of peoples that scarcely know how to do much for themselves without some manner of technology aiding them?! In a way while I grimace at the idea of having to reinvent the wheel, perhaps, at times there is something fruitful of this experience when and where ever it is provided as something of life lesson. The idea of furthered emancipation in never having to repeat something learned could certainly have its pitfalls, civilisations it seems in history were born in areas not where environment perfectly provided for every human need without need of creative drive to invent or intellectual ingenuity, but neither in restricting so harshly the tools that could be used in design for survival. While the potential aid of robotics could be of aid, one wonders as to the nature of future social philosophy. Certainly it seems if landed alone on a planet, I could scarcely imagine alone being resourceful enough to be able to handle and harvest in the same collective capacity resources and materials and manufacture goods in the highest orders that we think of today even, but in the future technological design will be permitting of this, and maybe even one shouldn't ignorantly act at the behest of intelligent machinery that aids in providing here...how should human comprehension and intelligence exist when bounded by rudiments at a base level described mostly on sheer survival with nothing of profit made otherwise generally speaking. The concept of advancement it seems in historical analysis is such that survival alone may not lead to conditions of technological ingenuity when survival decision pathways themselves lead not to the conditions necessary for enough exploration, curiosity...this is to say a polar bear may make a wonderful living doing what it does in culmination to many attributes coexisting in relation to environment, but this hadn't necessarily meant that the bear need be so much smarter then next generation round to survive, especially when decision possibilities are more narrow and restricted with respect to survival odds regarding such pathways. At present then one finds given the extent of possible knowledge base that exists, conceptually 'master of none', or 'master of somethings' could apply but in the least it would be harder to affirm 'master of much'. Landing on this barren planet, a human find him/herself in such likely position in the future. He/She alone might through technological aids be able to resourcefully find basic materials, could possibly replicate machinery (again with technological aids already in tote), but if having absolutely nothing but a few matches and a knife...well, it would be back to the stone ages, until information and technological recovery, or rescue could be had.


Playing around with OpenGL, and game engine stuff today

Fiddling around with Ogre yet again in Ubuntu, seemed to install fine, did a custom program build using cmake method.  All appeared to generally work but some textures and mesh objects by way of tutorials hadn't loaded properly (e.g., ninja and brick textures :) )....  PyOgre, python bindings of Ogre is a bit outdated at the moment running older versions of ogre though.  No attempts made in this language.   Hmm, sort of led me to something of inspirations.  Seems like it would be nice if something of a textures/mesh object theme libraries could be developed for designers, sort of not necessarily new idea (you can find design kits packaged with applications) but would be nice generically speaking for any particular rendering design application.  Played around with freeGlut (framework for OpenGL), interesting stuff, also found gtk openGL context creation interface GdkGLext.

Saturday, April 14, 2012

Reading about Etruscan art

Found myself reading about

Etruscan Art.  What compelled me to read about Etruscan art, a statue of a human figure wearing a big sombrero-like hat, really strange looking hat. 

Pygtk 3+ gui app using pango for character rendering



imported basically the entire unicode library, albeit haven't worked the details on languages with large character sets (Chinese and other eastern languages).  Someday maybe everything will get rendered automatically, but for now event with correct utf-8 or unicode code set for characters you may have difficulty without appropriate font set loaded in your os to render sets.

4/16 -

Okay some updates on this modified code, on existing keyboard pop ups to create movable/resizable keyboard windows.  Also modified from earlier pop up window type, window so that it is no longer destroyed either by out of focus event or by key or button events sending write back returns on respective drawing area widget.  Based on open source Sudoku code, to make better use of more permanent keyboard windows decided to instantiate this outside of drawing area widget, and instead on the top level window, with function call back which sends character string information to the class instantiated aspect frame first, and this in turn finds the last focused drawing area widget for character write.  The effect of this allows for multiple keyboard windows to be instantiated with different character sets.  I've included for each window the ability to instance any number of language sets at once.  I also created a move to top position for keyboard window instancing, this allows for quicker movement between windows.  Studying on changing some style aspects of keyboard windows namely, to avoid Active versus Normal states, however, it appears .get_style() functions on a widget are generally deprecated in gtk3+, while function appears here, attempting to change or modify style appears to do nothing...supposed to use Gtk.StyleContext instead here.  Also when working with multiple windows active (or at least 'normal') concurrently for a running application, if you want to provide toggle automations between windows (with users initiation), you can use the Wnck module...first accessing the screen (X11) using a get screen, then iterating windows on screen object, you can filter search for your window by name, and then using this modules window functions, activate() the given window.




Qa crossword source code here

if you want to run code, may have to install Ubuntu's quickly package to get source to work, free for any to use.

-4/18 - Presently constructing crossword generating algorithm

 Okay so this is a routine that I have thought of at the moment
1. Pick word from list.
2.  From its allocation (horizontal or vetical), determine matched tokens on its length running perpendicular, and pick words having least rank where rank is determined from the absolute value of all character distance summed relative to crossword grid center.
3.  Configure grid, subtract all matched words from dicitionary pools.
4.  Then work all previously matched words on the opposite axis of such grid, repeating step 2.
5.  Repeat step 3.

6.  Assess Squareness.
   i.What are the width, height characteristics of the crossword of 1-5.
   ii.  Depending on variance of relative measures to one another, decision
        is made to seed a word on the axis to compensate for differences
        of one measure relative the other.
7. From word determined on step 6, repeat steps 2-5.  Then repeat step 6.   


Added to this somewhere in iteration when dictionary pool is close to some determined threshold, boundary restrictions are placed on any added words which define boundary thresholds of the crossword grid.  Once either fixed iteration cycles (program specified) or dictionary pool are exhausted, then the crossword is ranked overall for squareness and word densities relative size.

Then having implemented tracking on picks (step 1), one can rerun steps2-7 with permutation of picks at step 1 and step 6.

Once a sufficiently well enough ranked crossword has been found, the generator can terminate, and the selected crossword coordinate system can be re normalized for typical table inputs (i.e., first quadrant in the cartesian system). 

Unicode character set importer for Python

import os
import os
import shelve

class Keycachedata:

    def deleteKey(self, key):
     self.key = key
     self.__checkreadFile()
     if self.__verifyKey():
            del self.cachedatafile[self.key]
        #print('key data saved.')
        self.keydatafile.close()

    def savekey(self, key, keydata):
        self.key = key
        self.__checkreadFile()
        #print('cachefile prior to keydata mod:',self.keydatafile)
        if self.__verifykey():
            print('Key verified.')
            self.keydatafile[self.key] = keydata
        print('key data saved.')
        #print(self.keydatafile)
        self.keydatafile.close()

    def savekeydata(self, keydata):
     self.__checkreadFile()
        #self.keydatafile[self.key] = keydata
        if self.__verifykey():
            self.keydatafile[self.key] = keydata
            print('key data saved.')
        self.keydatafile.close()

    def addkey(self, key):
        self.key = key
        self.__checkreadFile()
        keycheck = self.__verifykey()
        if not keycheck:
            self.keydatafile[self.key] = {}
            print('key added.')
        else:
            print('key already exists.')
        return keycheck
        self.keydatafile.close()
            
    def retrievekey(self, key):
        self.key = key
        self.__checkreadFile()
        self.keydata = {}
        if self.__verifykey():
            self.keydata = self.keydatafile[self.key]
        self.keydatafile.close()
        return self.keydata

    def retrievekeyname(self):
        return self.key

    def retrievekeylist(self):
        keylist = []
        self.__checkreadFile()
        for key in self.keydatafile:
           keylist.append(key) 
        self.keydatafile.close()
        return keylist

    def iskeydatempty(self):
        check = False
        self.__checkreadFile()
        if len(self.keydatafile) == 0:
            check = True
        self.keydatafile.close()
        return check

    def returnFirstkey(self):
        self.__checkreadFile()
        keylist = list(self.keydatafile.keys())
        firstkeykey = keylist[0]
        self.keydatafile.close()
        return [firstkeykey, self.keydatafile[firstkeykey]]
            
    def __verifykey(self):
        check = False
        if self.key in self.keydatafile:
            check = True
        return check
        
    def verifykey(self, keyname):
        check = False
        self.__checkreadFile()
        if keyname in self.keydatafile:
            check = True
        self.keydatafile.close()
        return check        
        
    def __readFile(self):
     print('hitting read shelve file on keycachedata class.')
        self.keydatafile = shelve.open(self.pathfile, 'w')


    def __createFile(self):
     print('hitting create shelve file on keycachedata class.')
        self.keydatafile = shelve.open(self.pathfile, 'n')
      
        

        
    def __checkreadFile(self):
        file = ''
        if os.name == 'nt':
            file = '\\qacrossworddata'
        elif os.name == 'posix':
            file = '/qacrossworddata'
        self.pathfile = self.path+ file
        if os.access(self.pathfile, os.F_OK):
                if os.access(self.pathfile, os.R_OK):
                    if os.access(self.pathfile, os.W_OK):
                        self.__readFile()
                    else:
                        self.__createFile()
                else:
                    self.__createFile()
        else:
            self.__createFile()
    
##    def checkkey(self):
##        
##        self.__checkreadFile()
##        self.__verifykey()
        
    def __init__(self):
        self.path = os.getcwd()
        self.key = ''
        #self.__checkreadFile()

KEYSPOP = 15
KEYSPOPALT = 14 #alternate keys detection

#the following site provide unicode tables that can be used with this
#importer
#http://www.utf8-chartable.de


#Haven't included try exceptions in this program, so every file
#should be consistently valid and of the same format for this
#to work.  i.e. any table written with more then 4 tab separated keys
# and less then 3 tab separated keys
# will not work in this file reader.  If so, you'll need to restructure
#tables or code differently, as I've structured reader around
#website tables mentioned above.



def startendwhitespaceremove(stringline):
        retstring = ''
        stringarray = stringline.split()
        if len(stringarray) == 1:
            retstring = stringarray[0]
        elif len(stringarray) > 1:
            retstring = stringarray[0]
            for string in stringarray[1:len(stringarray)]:
                retstring += ' ' + string
        return retstring

def preappendunicodedata(filename = '', quickfinddict={}):


    def bisectionsearch(intval, keyset):
                returnval = []
        
                lkeyset = keyset[0: len(keyset)/2]
                ukeyset = keyset[len(keyset)/2: len(keyset)]
        
                minlkey = lkeyset[0][0]
                maxlkeyrange = lkeyset[len(lkeyset)-1]
                maxlkey = maxlkeyrange[len(maxlkeyrange)-1]
                minukey = ukeyset[0][0]
                maxukeyrange = ukeyset[len(ukeyset)-1]
                maxukey = maxukeyrange[len(maxukeyrange)-1]
                if not intval < minlkey and not intval > maxlkey:
                        if not len(lkeyset) == 1:
                               returnval = bisectionsearch(intval, lkeyset)
                        else:
                               return lkeyset
                elif not intval < minukey and not intval > maxukey:
                        if not len(ukeyset) == 1:
                               returnval = bisectionsearch(intval, ukeyset)
                        else:
                               return ukeyset

                return returnval        
                            
    
    #here we set data up in a dictionary for referencing,
    #making one pass through the data set for key value
    #pairing.  Here we set up a 2 dimension tuple which
    #records the name for the unicode character and its
    #indexing in set of keys...this index will aid us
    #quickly setting up block address searching later.
    a = open(filename)
    dicta = {}
    blocksdict ={}

    name = ''
    uc = '' #this is unicode character point representation
    #this will still needed to be converted into a form
    #recognizable by python after read parsing unicode tables.
    
    count = 0
    for line in a:

        if len(line.split(';')) == KEYSPOP:
           unilist = line.split(';')
           uc, name, case = unilist[0], unilist[1], unilist[2]
           #This import design is structured for
           #present unicode data format information
           #please consult tables to verify for correct
           #importation.
           
        elif len(line.split(';')) == KEYSPOPALT:
            
           unilist = line.split(';')
           uc, name, case = unilist[0], unilist[1], unilist[2]
        if not len(name) == 0:
           
           intval = int('0x'+uc,0)

           rangekey = bisectionsearch(intval,sorted(quickfinddict))

           if len(rangekey) == 1:
                   if rangekey[0] in quickfinddict:
                           blockident, blockname = quickfinddict[rangekey[0]]
                           dicta[uc] = (name, count, case, blockident)
       
                           blockident = tuple(blockident)
                           if blockident in blocksdict:
                                   blockdict = blocksdict[blockident]
                                   blockdict[uc] = name
                           else:
                                   blocksdict[blockident] = {}
                                   blockdict = blocksdict[blockident]
                                   blockdict[uc] = name
                   
        count += 1
    return (dicta,blocksdict)

def readunicodefile(lname = 'LATIN', unicodedat = {}, blocksdict = {},
                    block = (0,0)):

    def findnearest(blockpos, minmaxswitch):
            
        #convert hex to decimal
        blockposa = '0x'+blockpos
        print('blockpos ', blockposa)
##        print(blockposa)
        blockposadec = int(blockposa, 0)
        find = False
        print(minmaxswitch)
        while not find:
            if minmaxswitch:
                blockposadec -= 1
            else:
                blockposadec += 1
            blockposahexstring = hex(blockposadec)
            blockposa = blockposahexstring[2:len(blockposahexstring)]
            if 'x' in blockposa:
               blockposa = blockposa.split('x')[1]
            elif 'X' in blockposa:
               blockposa = blockposa.split('X')[1]
            blockposa = blockposa.upper()
            
            if blockposa in unicodedat:
                find = True
                
##            print('Find status: ', blockposa)
        return blockposa
   
    #a = open(filename)
    dicta = {}
    dicta[lname+'_LOWER'] = {}
    dicta[lname+'_UPPER'] = {}
    dicta[lname+'_OTHER'] = {}
##    dicta[lname+'_LOWER_REV'] = {}
##    dicta(lname+'_UPPER_REV'] = {}
    name = ''
    uc = '' #this is unicode character point representation
    #this will still needed to be converted into a form
    #recognizable by python after read parsing unicode tables.
    #code blocks table doesn't necessarily garauntee existence in
    #table for a given range a respective table element, so we may
    #may need in appropriate blocks range find nearest minimal
    #maximal element

    blockdict = blocksdict[tuple(block)]
    for uc in blockdict:
            

        name = unicodedat[uc][0]
        case = unicodedat[uc][2]
        
        LCLstring = lname + ' CAPITAL LETTER'
        LSLstring = lname + ' SMALL LETTER'
        Lstring = lname
        if not len(name) == 0:
            if 'Lu' in case:

                chardict = dicta[lname+'_UPPER']
                ucconv = '0x'+uc
                ucconv = eval('unichr('+ucconv+')')
                ucconv = ucconv.encode('utf-8')
                chardict[len(chardict)+1] = ucconv
            elif 'Ll' in case:        

                chardict = dicta[lname+'_LOWER']
                ucconv = '0x'+uc
                ucconv = eval('unichr('+ucconv+')')
                ucconv = ucconv.encode('utf-8')
                chardict[len(chardict)+1] = ucconv
            elif 'Lo' in case:
                chardict = dicta[lname+'_OTHER']
                ucconv = '0x'+uc
                ucconv = eval('unichr('+ucconv+')')
                ucconv = ucconv.encode('utf-8')
                chardict[len(chardict)+1] = ucconv

    
    return dicta

def createkeyboardrows(dicta, lname):
    kblangpack = {}
    kblangpack['LOWER'] = {}
    kblangpack['UPPER'] = {}
    #Idea here is to restructure dictionaries into
    #rowdictionaries that can easily be passed in a 2 dimensional
    #array type form
    #First several rows are designated to non variant lower or upper
    #case letter forms, variant forms are those of the base character
    #plus accenting, hooks, and so forth.

    #First collect pop data which will determine row dict creation pops
    def countpop():
        count = 0
        for chardict in dicta:
            count += len(dicta[chardict])
        return count

    #next create row dictionaries based upon pops
    #allocating 10 column spacing here

    def createkbrowdicts():

        #  hmmm...above may not be necessary
        #start building on lower base dict
        def lowerupperkey(keyswitch):
            chardict = {}
            base_keyswitchdict = dicta[lname+'_'+keyswitch]
            for charkey in base_keyswitchdict:
                if not len(chardict) < 11:
                    lowerdict = kblangpack[keyswitch]
                    lowerdict[len(lowerdict)+1] = chardict
                    kblangpack[keyswitch] = lowerdict
                    chardict = {}
                chardict[len(chardict)+1] = base_keyswitchdict[charkey]
            lowerdict = kblangpack[keyswitch]
            lowerdict[len(lowerdict)+1] = chardict
            kblangpack[keyswitch] = lowerdict                

        def otherkey(keyswitch):
            chardict = {}
            keydict = dicta[lname + '_OTHER']
            for charkey in keydict:
            #need to correct control expressions here, 
            #appears to overwrite previous kblangpack work,
            #needs to append not overwrite.
                if not len(chardict) < 11:
                    lowerdict = kblangpack[keyswitch]
                    lowerdict[len(lowerdict)+1] = chardict
                    kblangpack[keyswitch] = lowerdict
                    chardict = {}                        
                chardict[len(chardict)+1] = keydict[charkey]
            lowerdict = kblangpack[keyswitch]
            lowerdict[len(lowerdict)+1] = chardict
            kblangpack[keyswitch] = lowerdict          

                  
        lowerupperkey('LOWER')
        chardict = lowerupperkey('UPPER')
        otherkey('LOWER')
        otherkey('UPPER')
        

    createkbrowdicts()                    
    return kblangpack



def blockimporter(blockfilepath = ''):
    returndict = {}
    quickfinddict = {}
    a = open(blockfilepath)
    for line in a:
        linesplit = line.split(';')
        if len(linesplit) == 2:
            block, name = linesplit
            if not len(block) == 0:
                block = startendwhitespaceremove(block)
                blocklist = block.split('..')
                
            if not len(name) == 0:
                name = startendwhitespaceremove(name)
                name = name.upper()
            returndict[name] = blocklist
            block1 = int('0x'+blocklist[0],0)
            block2 = int('0x'+blocklist[1],0)
            quickfinddict[tuple(range(block1, block2+1))] = (blocklist, name)
    return (returndict,quickfinddict)

def importer(blockfilepath, unicodedatfilepath):
    blockdict,quickfinddict = blockimporter(blockfilepath)
    unicodedat,blocksdict = preappendunicodedata(unicodedatfilepath,
                                                 quickfinddict)
    for blockname in blockdict:
        #k block name needs possible further parsing since
        #it is used in our search filtration algorithm
        #hmm...we could do away with this completely since
        #lower and upper case delineations are provided
        #so we just need to import and read character case
        #coding here.
        
        block = blockdict[blockname]
        print('processing: ', blockname)
        dicta = readunicodefile(blockname , unicodedat, blocksdict,
                                block)
        dictb = createkeyboardrows(dicta, blockname)
 
        keydatamanager = Keycachedata()
        langpackdict = keydatamanager.retrievekey('Language')

        langpackdict[blockname] = dictb
        keydatamanager.savekey('Language', langpackdict)




importer(stringpathtounicodeblocksfilegoeshere,
         stringpathtounicodedatafilegoeshere) 
 
 
This program basically creates a character set library from existing unicode table data in utf-8 format, not sure if library already exists in Ubuntu, so I may have re invented something of the wheel here doing this, but this nicely stores character set data of case type forms 'Lu', 'Ll', and 'Lo' (upper, lower, and other)...this doesn't include punctuation, control characters and a range of other types...you could manually tweak code filters for doing this if you like using the source above. 

Also I haven't structured for parsing avoidance on unicode table comment lines, simply remove these, and you may need to remove last blocks line as well from blocks table. 

Also the shelve object file is stored in the same directory that the program is run on.  You will need to create the key 'Language' prior to running in order to save table data to this shelve file.  You can do this using the usual python console commands:

>>import shelve
>>a = shelve(stringpathtoshelvefilenamehere, 'n')
>>a['Language'] = {}

or use the Keycachedata class above for key creation...using filename for module importation this can be done as follows:

>>from filename import Keycachedata
>>a = Keycachedata()
>>a.addkey('Language')

Then run script above.

To access this data, you can do so using Keycachedata module as follows:

>>a = Keycachedata()
>>Languagedict = a.retrievekey('Language')

Then Languagedict will contain all such imported language data table infomation, so you simply need to provide the language key which should be all caps, or you can find keys at console by:

>>list(Languagedict.keys())

Friday, April 13, 2012

Language import tidbits: working with unicode in python

Okay so a bit exploration of pythons unicode module stuff and unicodedata modules.  The unicode module appear auto loaded while unicodedata isn't.  The difference here?

the reserved keyword unicode() returns a unicode object of say a string, albeit this can also be done using a reserved expression such as:

>> b = u'A'
 
where b is a unicode object of the upper case Latin letter 'A'.

This unicode object can be passed in turn to any number of unicodedata module object functions.   For, instance,

first importing the unicodedata module

>>import unicodedata

then passing the unicode object exampled above

>>unicodedata.name(b)

returns 'LATIN CAPITAL LETTER A'

One can likewise provide a character return of a unicode named object by using the correct unicode comment naming convention.  Example:

 >>a = unicodedata.lookup('MODIFIER LETTER RHOTIC HOOK')

returns u'\u013e'

which is the unicode point reference.  Note if you tried to use the unicode.decode() function on this you'd get an error in Python's IDLE gui stating something to the effect that this character can't be translated into a recognized ASCII character.  If you want to see its rendered typeset form you could simply use a print() function on this object.  Thus,

>>print(unicodedata.lookup('MODIFIER LETTER RHOTIC HOOK'))

should provide a character rendering of the letter indicated above

which is   ' ˞'

Unicode maintains a database table of such objects, appearing in semicolon separated form here .  I'd also mention one can find code block group information (e.g., Latin, Cyrillic, and so forth) here.  Basically this is provides a library indexing between character set indexes and individual characters themselves.

In python the translated convention, for example, of a unicode code point from  u+013e is indicated above as u'\u013e' .

For those interested further would suggest reading at unicode.org.

And for python programmer's, while I would suggest python's reference information on the unicodedata module, it appears some aspects of coding has changed relatively so to the docs that I've read here...this is to say appears some information that I have furnished above provides more current information in so far as implementation.

If you are working with partial hexidecimal string forms, another conversion method is as follows using this example:

a = '0041'
a = '0x'+a
 
b = eval('unichr(' + a + ')')

typically unicode database represents hexidecimal form in a abridged form relative python, typically full form in python is given by 0x...

but we are in a string form of this hexidecimal number representation, I opted to use the python eval() function which allows us  to evaluate string tokens (e.g., the string 'a = 1 + 1' evaluated would yield a = 2).  We use the python function unichr() to convert the hexidecimal unicode character to its unicode represented form.

Finally if you have difficulties rendering the character in your particular gui, you can further convert this to utf-8 (works for gtk3+ and pango package renderers) by doing the following using the above example:

b = b.encode('utf-8')
 

So far I have written something of a basic importer using unicode database tables, reading semicolon separated values here.  Although links between code blocks table and data tables are off in my case, mostly since min max block correspondence, include possible non existent values in so far as values given written in table, and present algorithm scans from min or max searching for nearest corresponding high low in block range...having problems with this...converted from hexidecimal to decimal, increment/decrement, converted back to hex, truncated hex form to match table key form, but still missing somewhere here.  Will probably go to another solution in the next day or so.




Wednesday, April 11, 2012

Present wordgrid project

Summary:  Having done some interesting stuff in the past several days here.  In exploration of open source code provided by particular group responsible for Sudoku, I managed to work code some (posted previous examples such as keyboard) generated from existing code, and then managed to update this gtk3+ alongside using the framework for a graphical grid that could input not just numbers but written text.  I opted in the case instead of creating a customized  gtk.gdk (under the old gtk2+) drawable widget to use the native Gtk.DrawingArea widget which already provided built in methods that hadn't need be converted for the sake of instantiation provided the old way, basically, 'event' based handlers have been removed and a 'draw' call back function simply need be defined, so this appeared to work out fairly well.

   I  then decided an expanded Latin based Qwerty keyboard set (international) were still a bit limited for programming perhaps with the defined pop up keyboard, so I determined a method to import unicode( utf-8) keyboard layout packs that could be imported under numerous language configurations.

Here this includes not merely, Cyrillic, Hebrew, Arabic, but also many other languages.  I created an importer which segregated key data not merely by case form, but also variant stroke, hook, accent, etc., forms on base types...thus allowing for grouping for easier finding on the keyboard layout grid.

I managed to provide menu option for the user to customise keyboard layouts as needed as quickly as possible (just click the checkbox) and voila new keyboard pops up when toggled here.

As it turns out it hadn't seemed so difficult, just needed a handling class for keyboard layouts as needed, then calling these layouts when the user toggles the program for the popup keyboard.


Working towards this goal of incorporating on existing language learning program, and then working on a crossword puzzles type program.  Basically a program which allows the user to create randomly generated crosswords, importing dual (or mutli, or user customized) language libraries.

Python programming issues for today

Technically, globals for read and write back, I've read tend to be less desirable in programming, but I've resorted this only for the sake of easing flow of data in read/write chains.

If you one needs access to a global, the reserved python token 'global' followed by your variable name, will inside class function or function regardless ensure that a the object variable is in reference to a global object and not a function scope limited or class limited variable. 

Why to use globals at the moment?!  Well it seems the problem were the instantiation of numerous class objects from a parent object that neither provided object inheritance to such child objects.  Here the parent object having reference to object variable data is no good, and otherwise, it seems to me logically one would have to pass on each read/write call back from parent to child necessarily object data along the pathway outside of using a global object that could be referenced to both parent and child, or the other dreadful, method is to use some input/output method to a datafile.  Literally reading from the harddrive...yuck...if I can avoid it would rather avoid here.  The later actually happened to me first, as I carelessly put an file read i/o inside a class instantiation that would be called numerous times just for program initialisation.  Here I instead opted to decrease read/write loads to single i/o operations and then globalized this particular data, here any child class object could access this and refreshes to such data could be done in single as opposed to multiplicity based transactions.  This is to say instead of refreshing data inside all such child class objects at once, data is refreshed on an as needed basis when the child class object calls for need of such data.  The 'better' method of this, however, were to pass a data access or class object through the class object hierarchy which will probably be code revision point in days ahead.

 

Sunday, April 8, 2012

Thought examples of determinism and a bit of clarification

Determinism versus Free Will

context of free will versus determinism...



Not having choice but seemingly subject to the will and whims of others, seems deterministic with respect to the choices and circumstances availed to such individual?  Or at least from an psychological standpoint...that other free will stuff seems to get thrown right out the door at times?!


It seems a relative and psychological assertion more so to the relative abstract analysis of possibility, or that free will encompasses the possibility of inhibiting the free will of others, and that laws are structured so as to in consequence with the possibility of inhibiting the free will of others.


Consider a death row inmate falsely accused of a crime he hadn't committed.  At the very moments of his death, what free will exists for him in such world?!  Could one say relatively so that any number of events in passing at least forward should be determined?!  He has little choice in evading such events that he knows will likely happen?!  What freedom could he find here aside from something of psychological escape alone?!  Of course, it seems to me even that free will and determinism paradoxically exist relative to the other.  One could neither deny so much the capacity of choices made by individuals likewise having some apparent freedom.


To talk of the same prisoner in the abstract, determined structures of laws having existed provides security to the safety and order of society as a whole were the sacrifice of complete free will by any individual in terms of potential outcome.  What I mean here, is that we as individuals sacrifice our potential freedom with the possibility of legal wrongful convictions for the sake of legal structures that very well may not only limit the set of freedoms that any such individual have, but also in the course of time may as a possibility in this reality produce a set of deterministic like if not outright set of deterministic outcomes regarding our existential circumstance.  Does a condition of imprisonment cease to exist because a prisoner has thought otherwise neither to accept his condition of imprisonment?!  Physically it seems isn't his imprisonment yet a condition in reality still having existed all along, and if at the moments prior to his death, he thinks to be free but is not freed: is not the condition of events determined in some manner beyond his free capacity in acting?!

Of course it seems mortality at some representative point in time, serves likewise to illustrate deterministic like consequence.  That is, there is nothing that I could do in the context of free will to avoid this consequent event at some point and time in the future?!

If seemingly the existence of any such event which is deterministic in nature, isn't the logical possibility enough to say that something of determinism does exist if extended even beyond the mere its mere thought up existence?! 

To the argue this, however, neither is to absurdly suggest as an absolutist.  This is neither in the sense of negation or annihilation, and I hadn't suggested one exist mutually exclusive relative the other.

Then there is the matter of time and history past, of course, having expressed this resolution of paradox should seem to exist, the past is determined having provided existential continuity to a present.  While having talked about the outcome of the Titanic sinking as suggested from the result of possible engineering mistakes...talking of mistakes in the context of preventing the tragedy in the past could be erroneous.  Supposing engineers corrected  mistakes in the ship's engineering design such that it could have withstood the collision with the iceberg that may have been estimated in thought today, it seems resolution of paradox would have it always that the Titanic did sink and the occupants of such had no choice other then sinking with such ship.  If it weren't an iceberg, then an even larger iceberg with higher collision velocities, or maybe a massive meteorite or any other circumstance absurdly enough would manifest itself ensuring the continuity of of events past leading to the present.  Thus it seems nothing could prevent it and free will in this context would be absurd, as likewise the decision to improve the design of ship prior to it ill fated voyage.  At least this is supposed to to causality.  It seems we couldn't exist without something of determinism in our present, and our futures could not exist without our present passing into historical determinism. 

To talk of determinism in the context, is neither to talk of the absence of free will, unless we lived literally in a past present, this is to say a determined past un  known to us whose future inhabitants depended upon a course of events ensuring the continuity of their future present, but how would you or I ever know this?! 

If a future weren't clearly with determination, neither a future present existed in some determined fashion which structured something of integral determinism in a past present ensuring causal continuity, then it seems more likely free will should abound in so far as the course of events which shape such future.

Perhaps the determined past present whose future present up to some point in time of future presence, by all means seems mutually exclusive to the idea of free will...this is to say, I could never go back in time prior to my conception to prevent it, and to this extent if the same were true of my present existence...perhaps something would conspire to prevent my death if I tried it...here imagine Christ leaping off a cliff and being saved by angels, it seems something of determinism and purpose might exist in the continuity of events leading to His resurrection seems in some fashion almost miraculously deterministic, and similarly I have heard of strange and odd stories personally speaking of people falling distances greater then fifty feet head first and surviving with no more then a small fracture to the head (wouldn't suggest trying it).  It  seems that even here it would be hard to say at times that something of miraculous determinism exists defying the appearance of physical convention...by all means such a fall usually results in a death?!  Here unfortunately and absurdly a man slips from a step stool perhaps no more then six inches off the ground and hits the back of his head, and goes into something of a permanent coma.  Seems very absurd!

I would offer it isn't to suggest fatalism here, at least it seems my thoughts, however, rational or irrational allow for the possibility that I could choose seemingly at some point in time to go the store freely, however, determined, this neither throws one into despair, at least in mind, I hadn't known a possible determination for my future and would seemingly act as free as I thought in acting.   Of course, as to theology here, it seems others had considered determinism in way of ideas such as pre destination, however, reconciled to the muddier waters of human judgement on these matters. Neither reconciled as in knowing perhaps with certainty individual fate and judgement as reasoned, but suggested logically upon the premise of pre destination, acts and circumstance were self evident in some manner?!  This is to say those acting in accordance could be said to be more self evident in the negative sense, and in the positive sense this were God's determination alone....or in other words they were more careful to embrace the certainty in knowing their certainty while trying to live by acts having shown expressed an image but not totality of certainty, but having stronger judgements against those acting, for instance, amoral, as proving something of self evidence to pre destination in the sense of rejection, but even here maybe give and take?

Although I hear 'Can do no right' and 'Can do no wrong' crop up from time to time sometimes in the language of others, it seems far less commonplace even believing more strongly in the possibility of a more deterministic world neither completely precludes the possibility that others believe more strongly in shown acts having little to do with contrary thinking of futility, fatalism, and abandonment.  Futility seems more in line with irrational thinking in so far as existence, for often it seems the contrary might easily occur to disprove the absolute of such statements in time, at least Calvinist thinkers at such time would have understood something of possible erroneous thinking in presuming certainty of their condition by my mere example of acts alone?  These seem only self serving excuses have little basis in reality.  In the previous mentioned case,  at least engineers of the Titanic might have remedied flaws to the best of their ability concerning a ship's design while a conspiracy would ensue to ensure the ship continued its voyage regardless, people's actions might have been afforded in some way differently relative to another set of actions past, where any new actions hadn't clearly led to some existential paradox of a future present (these would be conservation of matter, energy violations and so forth...or at least one could think of violations of something like bound and free energy violations?!).  It seems at least in thinking I have heard this, and in any event, what ensues is not that all actions must necessarily be the same for the same event to occur (conservative actions, non conservative paths), it seems a manifold of events could be possible in a deterministic past, providing the seeming appearance of free will, but being determined enough so that continuities are maintained in so far as events important to the structural continuity of a future present.  For example, to have a child a couple might not have to go to Denny's they could have gone to...Ihop... and thus the child was still born after they ate where ever they happened to eat that were still determined, and maybe event going out to eat, or eating would even be necessary to the act of conceiving here. 


At least with respect to past context, however, it seems nonetheless, that events are determined events in the context of having been manifest, and determinism allows for the possible shaping of future events.  Without determinism in the past what could be said of the future.  The displacement of matter arrangement which could be posited in some seemingly quantum like arbitrary space in the macroscopic sense should seem something of a chaotic mess, who or what could clearly and continuously exist without causality, and determinism in the macroscopic sense?  As to the couple going to Ihop as opposed to Denny's , you might ask what happened to arrangement of matter that would be displaced otherwise in the past set of events at Denny's that had been relegated to Ihop in a series of events...of course, the response here were something of mirror symmetry, another couple that would have gone to Ihop instead went to Denny's and displaced matter in exactly the same way that the couple that went to Ihop did when in another past they had occurred when having gone to Denny's, and it seems some of a regression of this argument could be had in maintaining causal preservations between two event dissimilar pasts which lead to the same future present.  Okay then you start talking about gas consumed and the problems of energy displacement of one couple relative another, here, lo and behold the funny and odd coincidence occurs that the each set of couples lives in a geographic sense exactly sum total equidistant from either location, or in other words, the gas consumed in driving to either location would sum total remain the same in terms of energy consumption...it the argument could get pretty tedious and funny from this point going forward, but it seems possibility could still exist that in the end, the future that were landed upon were the same from two event dissimilar pasts, as long as alterations of matter in outcomes were neither so different as to provide for conservation of of energy and matter violations here?! 

Mentioned this in thought previous, what makes matter so stable in the causal sense otherwise?! 

This being said, human experience should seem limited enough, what clearly could we see of determinism if we live in the forest which shrouds clearly from view the certainty of our actions and 'free will' therein?!

Leading me back to something of origins here...had something of humorous fascination in thoughts to the theological subject matter of Genesis. Of course, in retrospect to much having been said earlier, while at one time, 'free will' should have existed in so far as the attainment of knowledge pertaining to good and evil, it seems now that  such event is now considered deterministic, no time traveller could avert the possibility that mankind ever fell from grace here or ever prevent such an outcome!  I think of the word 'free will' in the context of 'with' and 'with out' but this perhaps should be erroneous with respect to the possible consideration of mindset.  Innate curiosity to partake in the sharing of the fruit of knowledge, would imply the existence of 'free will' before knowledge of good and evil were ever known?!  Which yet seems a bit strange to me in some way, maybe one considers splitting a hair with respect to so much the difference in psychology having existed which leads to this, one senses in writing here that Adam and Eve never really had the same capacity understanding as we might understand today, prior to consuming fruit which would transform their understanding of their own existence, but none the less something of 'free will' must have existed despite all this with just enough difference between creator and created, allowing for such decision of great momentum?!  And it seems talking about 'free will' in one context relative another should have some apparent contrast, curiosity alone weren't itself on the same level as having obtained something of greater requisite knowledge, nor one supposes that curiosity alone would facilitate the possibility of anything that we think of today regarding 'free will'.  Of course, absurd to say that a being could conceive of evil before having knowledge of it, yet such being acting within capacity of 'free will' simultaneously in mind...prior speaking, I should mention here, there generally shouldn't have been, for instance, teaching Adam not to do wrong and being punished for doing wrong, because Adam didn't have the mindset to conceive wrong.  :)  Some might erroneously choose the words 'determinism' here but one carefully neither posits such words in describing one state of existence relative another.  As to the ongoing stream, seemingly this provides something of a model to those interested in artificial intelligence, for instance.  Here, it seems quite plausible, to us at least in some manner, that a mind itself could have differences and understandings.  What makes one think at any moment of an idea?!  What capacity might be oriented around a given mind with respect to the creation of ideas neither having existed in a prior context in such mind?!  Generally speaking, it seems, however, certain, that any number of thoughts and ideas may generally on a daily basis be generated from the continuity of thoughts having existed in a historical context.  Memory aids with respect to the thought structural process of daily living here.  Long since having grown into adulthood, the translated sensation of a feeling of being hungry, could transpire into the thought, "I would like peanut butter!'  And it seems while the creation of this thought were neither necessarily unique alone relative to its re creation time again wherever memory served to remind that a jar of peanut butter should exist ample to serve in the alleviation of hunger.  It seems more likely these sorts of thought processes could predominate living in an everyday context.  However, for a child that has never seen an 'apple', how does such child conceive of the word 'apple' or know what such object is like without having been taught such word and associated named object here?!  Is it possible?!  One admits here that it seems that the continuity of learning ideas in some ways also have some origins to environment, and that these themselves may not have some mind excepting vacuous source that is indigenous.

Resorting to Plato's allegory of The Cave, it seems likewise one could speak more clearly with respect to the contrasts between knowledge and experience
in so far as learning and comprehension.  It seems even here the idea that a mind could find connection between events or patterns of structures in an environment could exist in so many different ways.  This being said regarding 'determinism' and 'free will' which abounds here?!  It seems ironic that the determined historical context so much provides structure and governance in many way with respect to the orientation of the mind itself.  For Adam and Eve it seems their minds were structured by prior requisite knowledge and experience, excepting certain knowledge here, it seems, curiosity itself neither excepted from the process...I would offer that their minds must have seemed very innocent and child like to us today.  I imagined here the absence of any inset experience, obviously pertaining to evil as we think of it today, and interestingly enough something of embedded in the story were the relation of the idea of knowledge and a differed worldly experience imparting and transmitting in mind something which hadn't existed prior.

It seems one then should ask, what exactly is created the very unique sense of expression that hasn't already been created?!  Certainly dreams, works of art may seem quite unique and distinct relative to anything past, but are these merely variant expressions in some ways of determinant forms already seen in some manner?!

    






 

     


Response to what is significant self sacrifice obligatory

When is significant self sacrifice obligatory?

One day, I happened to donate a small sum of money at a cash register for a particular then active charity.

No sooner had I walked out of the grocery with stores in tote, then having in the parking lot crossed a sum of the same amount on the ground.

There could be many interpretations of this I imagined.

To this extent, I remember having read in another context someone having said to the effect of another's charity: why do or give if you have animosity doing so?
Transcending a bit the abstracts of passion to social justice, there is something of a personal statement concerning direct involvement in active charitable work, and maybe this is very true: what help could you be to yourself and others, if having eroded the charity that you sought to provide?  Is 'sacrifice' an obligation as in duty, as in not having some other desired life relative to another path 'sacrificially' chosen?

Returning to the abstract,
As to the effect of charity,  it seems behaviour is much complex here.  What profit might be had of charity that could be utilised in so many ways?  Much in line with the article above, it seems that even in the efforts of organisations themselves, however, large, diverse, and responsive to any number of circumstances are neither entirely holistic to condition of any and every plight when it has arisen.   How much time and attention should be devoted?  Maybe some consider any effort enough, while others would claim so much could be done significantly reduce or remove a condition in a society?  And if resources are finite and limited what suitable balance should exist in so far as donation of time and monies?

When any number of problems have emerged or have existed simultaneously, how are resources used in addressing these?  Does any one charity resource sufficiently provide address to all?  And how does one intelligently make decision as to what priority in addressing should exist?  Maybe obligatory and thoughtless donations could be ill served?


 

Saturday, April 7, 2012

Notes on Cairo set_source_rgb and set_source_rgba

Noticed three channel values (all non zero) seem to produce a value (255, 255, 255) color which is white.  However two channel values appear to produce their designated colour.   At this point recommend when setting colors that these are done on a two channel basis, i.e., assign no more then two non zero values at any set_sourc_rgb or set_source_rgba call, at a time.

for example, the following arbitrary values should work:
(r,g,b)
(255, 255, 0 ), (178, 89,0), (0, 178, 31), (67, 0, 43), and so forth

but the following doesn't work

(244, 34, 32), (111, 23, 11), and so forth

Friday, April 6, 2012

Python gtk 3+ pango cairo example


from gi.repository import Gtk, Gdk, cairo, Pango, PangoCairo
import math
import sys


RADIUS = 150
N_WORDS = 10
FONT = "Sans Bold 27"

class Squareset(Gtk.DrawingArea):
    def __init__ (self, upper=9, text=''):
##        Gtk.Widget.__init__(self)
        Gtk.DrawingArea.__init__(self)
        self.set_size_request (200, 200)
##        self.show_all()  

    def do_draw_cb(self, widget, cr):
        # The do_draw_cb is called when the widget is asked to draw itself
        # with the 'draw' as opposed to old function 'expose event' 
        # Remember that this will be called a lot of times, so it's usually
        # a good idea to write this code as optimized as it can be, don't
        # Create any resources in here.

          cr.translate ( RADIUS, RADIUS)
        
          layout = PangoCairo.create_layout (cr)
          layout.set_text("Text", -1)
          desc = Pango.font_description_from_string (FONT)
          layout.set_font_description( desc)
##          desc.free()
          rangec = range(0, N_WORDS)
          for i in rangec:
            
              width, height = 0,0
              angle = (360. * i) / N_WORDS;
              red =0.0
              cr.save ()
##              #/* Gradient from red at angle == 60 to blue at angle == 240 */
              red   = (1 + math.cos ((angle - 60) * math.pi / 180.)) / 2
              cr.set_source_rgb ( red, 0, 1.0 - red)
              cr.rotate ( angle * math.pi / 180.)
              #/* Inform Pango to re-layout the text with the new transformation */
              PangoCairo.update_layout (cr, layout)
              width, height = layout.get_size()
              cr.move_to ( - (float(width) / 1024.) / 2, - RADIUS)
              PangoCairo.show_layout (cr, layout)
              cr.restore()
              

def destroy(window):
        Gtk.main_quit()

def main():
    window = Gtk.Window()
    window.set_title ("Hello World")
    box = Gtk.Box('Vertical',5)

    app = Squareset()
##    box.pack_start(app,
##                   True,
##                   True,
##                   0)
    window.add(app)
                       
    app.connect('draw', app.do_draw_cb)
    window.connect_after('destroy', destroy)
    window.show_all()
    Gtk.main()
       
if __name__ == "__main__":
    sys.exit(main()) 

Translated C api example to python utilising PangoCairo and Pango libraries.

This draws pango cairo text

Original example in C here 

Wednesday, April 4, 2012

Python conversion notes between gtk2+ and gtk3+

Some recent tidbits on translations between C and and python languages in so far as gtk libraries.

So far some fairly easy to discern conversions:

Often in python a an object will have a method call which is done so in terms of the convention

gtk.object.method_call

whereas at least in gtk libraries, by c convention,

gtk_object_method_call(object,...)

so if hadn't had a readily provided api, you might be able to guess the method call simply altering syntax here.  Helps also to use the python console to verify existence firstly...as mentioned before a dir(object) call can provide method information alongside additional argument calls for such object.  In c a bit more verbose and redundant then python here with respect to naming conventions on method calls and the applicable class objects to them therein but that's the way it is...

Additionally, some things that I have come across...

type flag objects and the like in the form

gtk.KEYNAME_OBJECTFLAG

need to be converted, not just in gdk libraries.

I believe this were partially (if not fully) mentioned in the conversion process for the C api.

typically something OBJECT might be expressed as

gtk.KEYNAME_OBJECTFLAG

instead, in python the conversion might look like

Gtk.KeyName.OBJECTFLAG

the C api however generally helps in discerning the KeyName class object call.  Ways to find this in the api are:

1.  Probe the method call utilising such flag, the API may provide KeyName
     here even if in gtk2+ it appears differently(truncated or otherwise) relative
     to gtk3+.
2.  In c typically it may be written GtkKeyName (something like
     this anyways)...here you can run the command in python console
     dir(Gtk.KeyName), and you may find a directory of flag objects
     for the given KeyName. 
3.  Obvious the python syntax places a '.' between 'Gtk' and 'KeyName'
     and typically in python possibly converting  '_' to '.'  

generally speaking similarity in method call structures and objects appear to abound cross gtk2+ and gtk3+ libraries, so elsewhere conversion appears fairly straight forward.

As a translating research example I have the following window flag conversion:

w = gtk.Window()
....
w.set_type_hint(gtk.WINDOW_POPUP)

as it turns out we partially have in gtk3+ KeyName provided but not the whole story here and the flag is obtained through a different library altogather, namely, gdk.   How to start here:

1.  we notice the 'w' object is a gtk.Window() object
2.  Then we notice 'set_type_hint'  is a method call on the gtk_window class object
3.  We look up the method call 'set_type_hint' on gtk_window class object in the C api.  where we find that in our look up the following is yielded:

void                gtk_window_set_type_hint            (GtkWindow *window,
                                                         GdkWindowTypeHint hint);

Thus it appears that the argument flag call object for this method in gtk3+ is a
GdkWindwTypeHint object.

At console with Gdk library imported we can call

>> dir(Gdk.WindowTypeHint)

where a list of flags are populated confirming our desired flag.

As it turns out the converted call in gtk3+  is

Gdk.WindowTypeHint.POPUP_MENU

which is the closest equivalent.

Tuesday, April 3, 2012

py gtk3+ popup qwerty keyboard with caps toggle functionality example




from gi.repository import Gtk, Gdk, GObject

import math


TRACKER_COLORS = [
    (0.0,0.0,1.0), #blue
    (0.0,0.75,0.0), #green
    (0.6,0.0,1.0), #purple
    (1.0,0.5,0), #orange
    (0.5,0.5,0.5), #grey
    (0.6,0.15,0.15), #maroonish
    (0,0.3,0.0), #dark green
    (0,0,0.5), #dark blue
    (0.5,0.35,0.1), #muddy
    (0.5,0.25,0), #dark orange
    ]

def Gtkcolor_to_rgb (c):
    return c.red/float(2**16),c.green/float(2**16),c.blue/float(2**16)

def overlay (color_1, color_2, method=1):
    return color_1[0]+color_2[0]*method,color_1[1]+color_2[1]*method,color_1[2]+color_2[2]*method

ERROR_HIGHLIGHT_COLOR = (1.0,0,0)

BASE_SIZE = 35 # The "normal" size of a box (in pixels)

BORDER_WIDTH = 9.0 # The size of space we leave for a box

BORDER_LINE_WIDTH = 4 # The size of the line we draw around a selected box

LITTLE_LINE_WIDTH = 0.25
NORMAL_LINE_WIDTH = 1 # The size of the line we draw around a box

SPACING_FACTOR = 40 # The size of a box compared (roughly) to the size
                    # of padding -- the larger this is, the smaller
                    # the spaces
SMALL_TO_BIG_FACTOR = 3 # The number of times wider than a small line a big line is.

LATIN_QWERTY_TH_LOWER = {1:'q',2:'w',3:'e',4:'r',5:'t', 6:'y', 7:'u',
                           8: 'i', 9:'o', 10:'p'}
LATIN_QWERTY_TM_LOWER = {1:'a', 2:'s', 3:'d', 4:'f', 5:'g', 6:'h',
                           7:'j', 8:'k', 9:'l'}
LATIN_QWERTY_TL_LOWER = {1:'z', 2:'x', 3: 'c', 4:'v', 5:'b', 6:'n',
                         7:'m', 8:'ABC'}
LATIN_QWERTY_TH_UPPER = {1:'Q',2:'W',3:'E',4:'R',5:'T', 6:'Y', 7:'U',
                           8: 'I', 9:'O', 10:'P'}
LATIN_QWERTY_TM_UPPER = {1:'A', 2:'S', 3:'D', 4:'F', 5:'G', 6:'H',
                           7:'J', 8:'K', 9:'L'}
LATIN_QWERTY_TL_UPPER = {1:'Z', 2:'X', 3: 'C', 4:'V', 5:'B', 6:'N',
                         7:'M', 8:'abc'}
LATIN_QKEY_LOWER = {1: LATIN_QWERTY_TH_LOWER, 2: LATIN_QWERTY_TM_LOWER,
                    3: LATIN_QWERTY_TL_LOWER}
LATIN_QKEY_UPPER = {1: LATIN_QWERTY_TH_UPPER, 2: LATIN_QWERTY_TM_UPPER,
                    3: LATIN_QWERTY_TL_UPPER}

class NumberSelector (Gtk.EventBox):

    __gsignals__ = {
        'changed':(GObject.SIGNAL_RUN_LAST,GObject.TYPE_NONE,()),
        }

    def modifykeys(self):
        if self.caseflg:
            Key_Layout = LATIN_QKEY_UPPER
        else:
            Key_Layout = LATIN_QKEY_LOWER
        for y in Key_Layout:
            for x in Key_Layout[y]:
                b = self.bdict[(y,x)]
                b.set_label(Key_Layout[y][x])
                
                self.bdict[(y,x)] = b
        self.show_all()        
                

    def setkeys(self):
        if self.caseflg:
            Key_Layout = LATIN_QKEY_UPPER
        else:
            Key_Layout = LATIN_QKEY_LOWER
            
        self.bdict = {}
        for y in Key_Layout:
            for x in Key_Layout[y]:
                b = Gtk.Button()
                l = Gtk.Label()
                if Key_Layout[y][x]==self.value:
                    l.set_markup('%s'%Key_Layout[y][x])
                else:
                    l.set_markup('%s'%Key_Layout[y][x])
                b.add(l)
                b.set_relief(Gtk.ReliefStyle.HALF)
                l = b.get_children()[0]
                b.set_border_width(0)
                l.set_padding(0,0)
                l.get_alignment()
                b.connect('clicked',self.alpha_clicked, (y,x))
                self.table.attach(b,x,x+1,y,y+1)
                self.bdict[(y,x)] = b
               
        
    
    def __init__ (self,default=None,upper=9):
        self.caseflg = 0
        self.value = default
        Gtk.EventBox.__init__(self)
        self.table = Gtk.Table()
        self.add(self.table)
        self.setkeys()

        self.connect('key-release-event',self.key_press_cb)
        self.show_all()

    def key_press_cb (self, w, e):
        txt = Gdk.keyval_name(e.keyval)
        if txt.isalpha():
            self.value = txt
            self.emit('changed')
        else:
            self.emit('changed')

    def alpha_clicked (self, button, val):
        
        if self.caseflg:
            Key_Layout = LATIN_QKEY_UPPER
            y,x = val
            aval = Key_Layout[y][x]
            
            
        else:
            Key_Layout = LATIN_QKEY_LOWER                
            y,x = val
            aval = Key_Layout[y][x]
                    
        
        if not aval == 'ABC' and not aval == 'abc':
            self.value = aval
            self.emit('changed')
                
      
        else:
            if aval == 'ABC':
                self.caseflg = 1
                self.modifykeys()
            else:
                self.caseflg = 0 
                self.modifykeys()
                
    def get_value (self):
        return self.value

    def set_value (self,val):
        self.value = val


w = Gtk.Window()
w.set_app_paintable(True)
w.set_type_hint(Gdk.WindowTypeHint.POPUP_MENU)
w.set_decorated(False)
ns = NumberSelector()
def number_changed_cb (b):
    w.destroy()
    print('value:', ns.get_value())
    Gtk.main_quit()

ns.connect('changed',number_changed_cb)
w.grab_focus()
w.connect('focus-out-event',lambda *args: w.destroy())

w.add(ns)
w.show_all()
        
Gtk.main()
r = w.get_allocation()

w.show()      


This is a pop up window for a QWERTY keyboard using latest gtk3+ libraries in python.  Albeit has resizing issues initially when toggling caps, this provides a structural framework for on screen pop up keyboard (e.g., something that might be similarly used in tablet based apps).

 

Oblivion

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