idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
4,800
def from_jd ( jd ) : jd = trunc ( jd ) + 0.5 g = gregorian . from_jd ( jd ) gy = g [ 0 ] bstarty = EPOCH_GREGORIAN_YEAR if jd <= gregorian . to_jd ( gy , 3 , 20 ) : x = 1 else : x = 0 bys = gy - ( bstarty + ( ( ( gregorian . to_jd ( gy , 1 , 1 ) <= jd ) and x ) ) ) year = bys + 1 days = jd - to_jd ( year , 1 , 1 ) bld = to_jd ( year , 20 , 1 ) if jd >= bld : month = 20 else : month = trunc ( days / 19 ) + 1 day = int ( ( jd + 1 ) - to_jd ( year , month , 1 ) ) return year , month , day
Calculate Bahai date from Julian day
4,801
def to_jd ( baktun , katun , tun , uinal , kin ) : return EPOCH + ( baktun * 144000 ) + ( katun * 7200 ) + ( tun * 360 ) + ( uinal * 20 ) + kin
Determine Julian day from Mayan long count
4,802
def from_jd ( jd ) : d = jd - EPOCH baktun = trunc ( d / 144000 ) d = ( d % 144000 ) katun = trunc ( d / 7200 ) d = ( d % 7200 ) tun = trunc ( d / 360 ) d = ( d % 360 ) uinal = trunc ( d / 20 ) kin = int ( ( d % 20 ) ) return ( baktun , katun , tun , uinal , kin )
Calculate Mayan long count from Julian day
4,803
def to_haab ( jd ) : lcount = trunc ( jd ) + 0.5 - EPOCH day = ( lcount + 348 ) % 365 count = day % 20 month = trunc ( day / 20 ) return int ( count ) , HAAB_MONTHS [ month ]
Determine Mayan Haab month and day from Julian day
4,804
def to_tzolkin ( jd ) : lcount = trunc ( jd ) + 0.5 - EPOCH day = amod ( lcount + 4 , 13 ) name = amod ( lcount + 20 , 20 ) return int ( day ) , TZOLKIN_NAMES [ int ( name ) - 1 ]
Determine Mayan Tzolkin month and day from Julian day
4,805
def longcount_generator ( baktun , katun , tun , uinal , kin ) : j = to_jd ( baktun , katun , tun , uinal , kin ) while True : yield from_jd ( j ) j = j + 1
Generate long counts starting with input
4,806
def next_haab ( month , jd ) : if jd < EPOCH : raise IndexError ( "Input day is before Mayan epoch." ) hday , hmonth = to_haab ( jd ) if hmonth == month : days = 1 - hday else : count1 = _haab_count ( hday , hmonth ) count2 = _haab_count ( 1 , month ) days = ( count2 - count1 ) % 365 return jd + days
For a given haab month and a julian day count find the next start of that month on or after the JDC
4,807
def next_tzolkin ( tzolkin , jd ) : if jd < EPOCH : raise IndexError ( "Input day is before Mayan epoch." ) count1 = _tzolkin_count ( * to_tzolkin ( jd ) ) count2 = _tzolkin_count ( * tzolkin ) add_days = ( count2 - count1 ) % 260 return jd + add_days
For a given tzolk in day and a julian day count find the next occurrance of that tzolk in after the date
4,808
def next_tzolkin_haab ( tzolkin , haab , jd ) : haabcount = _haab_count ( * to_haab ( jd ) ) haab_desired_count = _haab_count ( * haab ) haab_days = ( haab_desired_count - haabcount ) % 365 possible_haab = set ( h + haab_days for h in range ( 0 , 18980 , 365 ) ) tzcount = _tzolkin_count ( * to_tzolkin ( jd ) ) tz_desired_count = _tzolkin_count ( * tzolkin ) tzolkin_days = ( tz_desired_count - tzcount ) % 260 possible_tz = set ( t + tzolkin_days for t in range ( 0 , 18980 , 260 ) ) try : return possible_tz . intersection ( possible_haab ) . pop ( ) + jd except KeyError : raise IndexError ( "That Haab'-Tzolk'in combination isn't possible" )
For a given haab - tzolk in combination and a Julian day count find the next occurrance of the combination after the date
4,809
def haab_monthcalendar ( baktun = None , katun = None , tun = None , uinal = None , kin = None , jdc = None ) : if not jdc : jdc = to_jd ( baktun , katun , tun , uinal , kin ) haab_number , haab_month = to_haab ( jdc ) first_j = jdc - haab_number + 1 tzolkin_start_number , tzolkin_start_name = to_tzolkin ( first_j ) gen_longcount = longcount_generator ( * from_jd ( first_j ) ) gen_tzolkin = tzolkin_generator ( tzolkin_start_number , tzolkin_start_name ) lpad = tzolkin_start_number - 1 rpad = 13 - ( tzolkin_start_number + 19 % 13 ) monlen = month_length ( haab_month ) days = [ None ] * lpad + list ( range ( 1 , monlen + 1 ) ) + rpad * [ None ] def g ( x , generate ) : if x is None : return None return next ( generate ) return [ [ ( k , g ( k , gen_tzolkin ) , g ( k , gen_longcount ) ) for k in days [ i : i + 13 ] ] for i in range ( 0 , len ( days ) , 13 ) ]
For a given long count return a calender of the current haab month divided into tzolkin weeks
4,810
def _update_data ( self , data = { } ) : pending_changes = self . _changes or { } try : del self . _changes except : pass try : custom_field_data = data . pop ( 'custom_fields' ) except KeyError : pass else : self . custom_fields = Custom_Fields ( custom_field_data ) for key , value in data . iteritems ( ) : lookup_key = self . _field_type . get ( key , key ) if lookup_key == 'datetime' or lookup_key == 'date' : self . __dict__ [ key ] = datetime_parse ( value ) else : self . __dict__ [ key ] = self . _redmine . check_cache ( lookup_key , value ) self . _changes = pending_changes
Update the data in this object .
4,811
def _remap_tag_to_tag_id ( cls , tag , new_data ) : try : value = new_data [ tag ] except : return tag_id = tag + '_id' try : new_data [ tag_id ] = value [ 'id' ] except : try : new_data [ tag_id ] = value . id except AttributeError : new_data [ tag_id ] = value del new_data [ tag ]
Remaps a given changed field from tag to tag_id .
4,812
def _add_item_manager ( self , key , item_class , ** paths ) : updated_paths = { } for path_type , path_value in paths . iteritems ( ) : updated_paths [ path_type ] = path_value . format ( ** self . __dict__ ) manager = Redmine_Items_Manager ( self . _redmine , item_class , ** updated_paths ) self . __dict__ [ key ] = manager
Add an item manager to this object .
4,813
def refresh ( self ) : if not self . _item_path : raise AttributeError ( 'refresh is not available for %s' % self . _type ) if not self . id : raise RedmineError ( '%s did not come from the Redmine server - no link.' % self . _type ) try : self . save ( ) except : pass target = self . _item_path % self . id json_data = self . _redmine . get ( target ) data = self . _redmine . unwrap_json ( self . _type , json_data ) self . _update_data ( data = data )
Refresh this item from data on the server . Will save any unsaved data first .
4,814
def _get_changes ( self ) : result = dict ( ( f [ 'id' ] , f . get ( 'value' , '' ) ) for f in self . _data if f . get ( 'changed' , False ) ) self . _clear_changes return result
Get all changed values .
4,815
def new ( self , ** dict ) : if not self . _item_new_path : raise AttributeError ( 'new is not available for %s' % self . _item_name ) for tag in self . _object . _remap_to_id : self . _object . _remap_tag_to_tag_id ( tag , dict ) target = self . _item_new_path payload = json . dumps ( { self . _item_type : dict } ) json_data = self . _redmine . post ( target , payload ) data = self . _redmine . unwrap_json ( self . _item_type , json_data ) data [ '_source_path' ] = target return self . _objectify ( data = data )
Create a new item with the provided dict information . Returns the new item .
4,816
def get ( self , id , ** options ) : if not self . _item_path : raise AttributeError ( 'get is not available for %s' % self . _item_name ) target = self . _item_path % id json_data = self . _redmine . get ( target , ** options ) data = self . _redmine . unwrap_json ( self . _item_type , json_data ) data [ '_source_path' ] = target return self . _objectify ( data = data )
Get a single item with the given ID
4,817
def update ( self , id , ** dict ) : if not self . _item_path : raise AttributeError ( 'update is not available for %s' % self . _item_name ) target = ( self . _update_path or self . _item_path ) % id payload = json . dumps ( { self . _item_type : dict } ) self . _redmine . put ( target , payload ) return None
Update a given item with the passed data .
4,818
def delete ( self , id ) : if not self . _item_path : raise AttributeError ( 'delete is not available for %s' % self . _item_name ) target = self . _item_path % id self . _redmine . delete ( target ) return None
Delete a single item with the given ID
4,819
def query ( self , ** options ) : if not self . _query_path : raise AttributeError ( 'query is not available for %s' % self . _item_name ) last_item = 0 offset = 0 current_item = None limit = options . get ( 'limit' , 25 ) options [ 'limit' ] = limit target = self . _query_path while True : options [ 'offset' ] = offset json_data = self . _redmine . get ( target , options ) try : data = json . loads ( json_data ) except : raise RedmineError ( json_data ) data_container = data [ self . _query_container ] for item_data in data_container : yield ( self . _objectify ( data = item_data ) ) if not data_container : break try : if int ( data [ 'total_count' ] ) > ( offset + len ( data_container ) ) : offset += limit else : break except : break
Return an iterator for the given items .
4,820
def _setup_authentication ( self , username , password ) : if self . version < 1.1 : if not username : username = self . _key self . _key = None if not username : return if not password : password = '12345' password_mgr = urllib2 . HTTPPasswordMgrWithDefaultRealm ( ) password_mgr . add_password ( None , self . _url , username , password ) handler = urllib2 . HTTPBasicAuthHandler ( password_mgr ) self . _opener = urllib2 . build_opener ( handler ) self . _opener . open ( self . _url ) urllib2 . install_opener ( self . _opener )
Create the authentication object with the given credentials .
4,821
def open_raw ( self , page , parms = None , payload = None , HTTPrequest = None , payload_type = 'application/json' ) : if not parms : parms = { } if self . _key and not self . key_in_header : parms [ 'key' ] = self . _key urldata = '' if parms : urldata = '?' + urllib . urlencode ( parms ) fullUrl = self . _url + page if self . debug : print fullUrl + urldata try : self . _opener . open ( fullUrl ) except AttributeError : pass if HTTPrequest : request = HTTPrequest ( fullUrl + urldata ) else : request = urllib2 . Request ( fullUrl + urldata ) if self . _key and self . key_in_header : request . add_header ( 'X-Redmine-API-Key' , self . _key ) if self . impersonate and self . impersonation_supported : request . add_header ( 'X-Redmine-Switch-User' , self . impersonate ) if payload : request . add_header ( 'Content-Type' , payload_type ) response = urllib2 . urlopen ( request , payload ) else : response = urllib2 . urlopen ( request ) return response
Opens a page from the server with optional XML . Returns a response file - like object
4,822
def open ( self , page , parms = None , payload = None , HTTPrequest = None ) : response = self . open_raw ( page , parms , payload , HTTPrequest ) return response . read ( )
Opens a page from the server with optional content . Returns the string response .
4,823
def post ( self , page , payload , parms = None ) : if self . readonlytest : print 'Redmine read only test: Pretending to create: ' + page return payload else : return self . open ( page , parms , payload )
Posts a string payload to the server - used to make new Redmine items . Returns an JSON string or error .
4,824
def put ( self , page , payload , parms = None ) : if self . readonlytest : print 'Redmine read only test: Pretending to update: ' + page else : return self . open ( page , parms , payload , HTTPrequest = self . PUT_Request )
Puts an XML object on the server - used to update Redmine items . Returns nothing useful .
4,825
def delete ( self , page ) : if self . readonlytest : print 'Redmine read only test: Pretending to delete: ' + page else : return self . open ( page , HTTPrequest = self . DELETE_Request )
Deletes a given object on the server - used to remove items from Redmine . Use carefully!
4,826
def unwrap_json ( self , type , json_data ) : try : data = json . loads ( json_data ) except ValueError : raise RedmineError ( json_data ) try : data = data [ type ] except KeyError : pass return data
Decodes a json string and unwraps any type it finds within .
4,827
def find_all_item_classes ( self ) : import redmine as public_classes item_class = { } for key , value in public_classes . __dict__ . items ( ) : try : if issubclass ( value , Redmine_Item ) : item_class [ key . lower ( ) ] = value except : continue self . item_class = item_class
Finds and stores a reference to all Redmine_Item subclasses for later use .
4,828
def check_cache ( self , type , data , obj = None ) : try : id = data [ 'id' ] except : return data try : type = obj . _get_type ( ) except : pass try : hit = self . item_cache [ type ] [ id ] except KeyError : pass else : hit . _update_data ( data ) return hit if not obj : obj = self . item_class . get ( type , Redmine_Item ) new_item = obj ( redmine = self , data = data , type = type ) self . item_cache . setdefault ( type , { } ) [ id ] = new_item return new_item
Returns the updated cached version of the given dict
4,829
def substract ( self , pt ) : if isinstance ( pt , Point ) : return Point ( pt . x - self . x , pt . y - self . y , pt . z - self . z ) else : raise TypeError
Return a Point instance as the displacement of two points .
4,830
def from_list ( cls , l ) : if len ( l ) == 3 : x , y , z = map ( float , l ) return cls ( x , y , z ) elif len ( l ) == 2 : x , y = map ( float , l ) return cls ( x , y ) else : raise AttributeError
Return a Point instance from a given list
4,831
def multiply ( self , number ) : return self . from_list ( [ x * number for x in self . to_list ( ) ] )
Return a Vector as the product of the vector and a real number .
4,832
def magnitude ( self ) : return math . sqrt ( reduce ( lambda x , y : x + y , [ x ** 2 for x in self . to_list ( ) ] ) )
Return magnitude of the vector .
4,833
def sum ( self , vector ) : return self . from_list ( [ x + vector . vector [ i ] for i , x in self . to_list ( ) ] )
Return a Vector instance as the vector sum of two vectors .
4,834
def dot ( self , vector , theta = None ) : if theta is not None : return ( self . magnitude ( ) * vector . magnitude ( ) * math . degrees ( math . cos ( theta ) ) ) return ( reduce ( lambda x , y : x + y , [ x * vector . vector [ i ] for i , x in self . to_list ( ) ( ) ] ) )
Return the dot product of two vectors .
4,835
def cross ( self , vector ) : return Vector ( ( self . y * vector . z - self . z * vector . y ) , ( self . z * vector . x - self . x * vector . z ) , ( self . x * vector . y - self . y * vector . x ) )
Return a Vector instance as the cross product of two vectors
4,836
def unit ( self ) : return Vector ( ( self . x / self . magnitude ( ) ) , ( self . y / self . magnitude ( ) ) , ( self . z / self . magnitude ( ) ) )
Return a Vector instance of the unit vector
4,837
def angle ( self , vector ) : return math . degrees ( math . acos ( self . dot ( vector ) / ( self . magnitude ( ) * vector . magnitude ( ) ) ) )
Return the angle between two vectors in degrees .
4,838
def non_parallel ( self , vector ) : if ( self . is_parallel ( vector ) is not True and self . is_perpendicular ( vector ) is not True ) : return True return False
Return True if vectors are non - parallel .
4,839
def rotate ( self , angle , axis = ( 0 , 0 , 1 ) ) : if not all ( isinstance ( a , int ) for a in axis ) : raise ValueError x , y , z = self . x , self . y , self . z if ( axis [ 2 ] ) : x = ( self . x * math . cos ( angle ) - self . y * math . sin ( angle ) ) y = ( self . x * math . sin ( angle ) + self . y * math . cos ( angle ) ) if ( axis [ 1 ] ) : x = self . x * math . cos ( angle ) + self . z * math . sin ( angle ) z = - self . x * math . sin ( angle ) + self . z * math . cos ( angle ) if ( axis [ 0 ] ) : y = self . y * math . cos ( angle ) - self . z * math . sin ( angle ) z = self . y * math . sin ( angle ) + self . z * math . cos ( angle ) return Vector ( x , y , z )
Returns the rotated vector . Assumes angle is in radians
4,840
def from_points ( cls , point1 , point2 ) : if isinstance ( point1 , Point ) and isinstance ( point2 , Point ) : displacement = point1 . substract ( point2 ) return cls ( displacement . x , displacement . y , displacement . z ) raise TypeError
Return a Vector instance from two given points .
4,841
def spherical ( cls , mag , theta , phi = 0 ) : return cls ( mag * math . sin ( phi ) * math . cos ( theta ) , mag * math . sin ( phi ) * math . sin ( theta ) , mag * math . cos ( phi ) )
Returns a Vector instance from spherical coordinates
4,842
def cylindrical ( cls , mag , theta , z = 0 ) : return cls ( mag * math . cos ( theta ) , mag * math . sin ( theta ) , z )
Returns a Vector instance from cylindircal coordinates
4,843
def amod ( a , b ) : modded = int ( a % b ) return b if modded is 0 else modded
Modulus function which returns numerator if modulus is zero
4,844
def search_weekday ( weekday , jd , direction , offset ) : return weekday_before ( weekday , jd + ( direction * offset ) )
Determine the Julian date for the next or previous weekday
4,845
def irafglob ( inlist , atfile = None ) : if inlist is None or len ( inlist ) == 0 : return [ ] if isinstance ( inlist , list ) : flist = [ ] for f in inlist : flist += irafglob ( f ) elif ',' in inlist : flist = [ ] for f in inlist . split ( ',' ) : f = f . strip ( ) flist += irafglob ( f ) elif inlist [ 0 ] == '@' : flist = [ ] for f in open ( inlist [ 1 : ] , 'r' ) . readlines ( ) : f = f . rstrip ( ) if atfile : f = atfile ( f ) flist += irafglob ( f ) else : if osfn : inlist = osfn ( inlist ) flist = glob . glob ( inlist ) return flist
Returns a list of filenames based on the type of IRAF input .
4,846
def pack ( self ) : try : structs_ = get_structs_for_fields ( [ self . fields [ 0 ] ] ) except ( TypeError ) : raise PackError ( self ) if structs_ == [ ] : try : structs_ = get_structs_for_fields ( [ self . fields [ 0 ] , self . fields [ 1 ] ] ) except ( IndexError , TypeError ) : raise PackError ( self ) for struct_ in structs_ : try : return struct_ . pack ( * self . fields ) except struct . error : pass raise PackError ( self )
Return binary format of packet .
4,847
def unpack ( cls , rawpacket ) : structs_ = get_structs_for_rawpacket ( rawpacket ) for struct_ in structs_ : try : return cls ( * struct_ . unpack ( rawpacket ) ) except struct . error : raise pass return cls ( 0xff , rawpacket )
Instantiate Packet from binary string .
4,848
def ch_handler ( offset = 0 , length = - 1 , ** kw ) : global _lastSel offset = int ( offset ) length = int ( length ) if length < 0 : length = len ( _lastSel ) return _lastSel [ offset : offset + length ]
Handle standard PRIMARY clipboard access . Note that offset and length are passed as strings . This differs from CLIPBOARD .
4,849
def put ( text , cbname ) : global _lastSel _checkTkInit ( ) if cbname == 'CLIPBOARD' : _theRoot . clipboard_clear ( ) if text : _theRoot . clipboard_append ( text ) return if cbname == 'PRIMARY' : _lastSel = text _theRoot . selection_handle ( ch_handler , selection = 'PRIMARY' ) _theRoot . selection_own ( selection = 'PRIMARY' ) return raise RuntimeError ( "Unexpected clipboard name: " + str ( cbname ) )
Put the given string into the given clipboard .
4,850
def get ( cbname ) : _checkTkInit ( ) if cbname == 'PRIMARY' : try : return _theRoot . selection_get ( selection = 'PRIMARY' ) except : return None if cbname == 'CLIPBOARD' : try : return _theRoot . selection_get ( selection = 'CLIPBOARD' ) except : return None raise RuntimeError ( "Unexpected clipboard name: " + str ( cbname ) )
Get the contents of the given clipboard .
4,851
def put ( self , measurementId ) : json = request . get_json ( ) try : start = self . _calculateStartTime ( json ) except ValueError : return 'invalid date format in request' , 400 duration = json [ 'duration' ] if 'duration' in json else 10 if start is None : return 'no start time' , 400 else : scheduled , message = self . _measurementController . schedule ( measurementId , duration , start , description = json . get ( 'description' ) ) return message , 200 if scheduled else 400
Initiates a new measurement . Accepts a json payload with the following attributes ;
4,852
def printCols ( strlist , cols = 5 , width = 80 ) : nlines = ( len ( strlist ) + cols - 1 ) // cols line = nlines * [ "" ] for i in range ( len ( strlist ) ) : c , r = divmod ( i , nlines ) nwid = c * width // cols - len ( line [ r ] ) if nwid > 0 : line [ r ] = line [ r ] + nwid * " " + strlist [ i ] else : line [ r ] = line [ r ] + " " + strlist [ i ] for s in line : print ( s )
Print elements of list in cols columns
4,853
def stripQuotes ( value ) : if value [ : 1 ] == '"' : value = value [ 1 : ] if value [ - 1 : ] == '"' : value = value [ : - 1 ] value = re . sub ( _re_doubleq2 , '"' , value ) elif value [ : 1 ] == "'" : value = value [ 1 : ] if value [ - 1 : ] == "'" : value = value [ : - 1 ] value = re . sub ( _re_singleq2 , "'" , value ) return value
Strip single or double quotes off string ; remove embedded quote pairs
4,854
def rglob ( root , pattern ) : retlist = [ ] if None not in ( pattern , root ) : for base , dirs , files in os . walk ( root ) : goodfiles = fnmatch . filter ( files , pattern ) retlist . extend ( os . path . join ( base , f ) for f in goodfiles ) return retlist
Same thing as glob . glob but recursively checks subdirs .
4,855
def translateName ( s , dot = 0 ) : s = s . replace ( '$' , 'DOLLAR' ) sparts = s . split ( '.' ) for i in range ( len ( sparts ) ) : if sparts [ i ] == "" or sparts [ i ] [ 0 ] in string . digits or keyword . iskeyword ( sparts [ i ] ) : sparts [ i ] = 'PY' + sparts [ i ] if dot : return 'DOT' . join ( sparts ) else : return '.' . join ( sparts )
Convert CL parameter or variable name to Python - acceptable name
4,856
def init_tk_default_root ( withdraw = True ) : if not capable . OF_GRAPHICS : raise RuntimeError ( "Cannot run this command without graphics" ) if not TKNTR . _default_root : junk = TKNTR . Tk ( ) retval = TKNTR . _default_root if withdraw and retval : retval . withdraw ( ) return retval
In case the _default_root value is required you may safely call this ahead of time to ensure that it has been initialized . If it has already been this is a no - op .
4,857
def tkreadline ( file = None ) : if file is None : file = sys . stdin if not hasattr ( file , "readline" ) : raise TypeError ( "file must be a filehandle with a readline method" ) try : fd = file . fileno ( ) except : fd = None if ( fd and capable . OF_GRAPHICS ) : tkread ( fd , 0 ) if not select . select ( [ fd ] , [ ] , [ ] , 0 ) [ 0 ] : return '' return file . readline ( )
Read a line from file while running Tk mainloop .
4,858
def launchBrowser ( url , brow_bin = 'mozilla' , subj = None ) : if not subj : subj = url if sys . platform not in ( 'os2warp, iphone' ) : import webbrowser if not webbrowser . open ( url ) : print ( "Error opening URL: " + url ) else : print ( 'Help on "' + subj + '" is now being displayed in a web browser' ) return pid = os . fork ( ) if pid == 0 : if sys . platform == 'darwin' : if 0 != os . system ( 'open "' + url + '"' ) : print ( "Error opening URL: " + url ) os . _exit ( 0 ) else : if not subj : subj = url print ( 'Help on "' + subj + '" is now being displayed in a browser' )
Given a URL try to pop it up in a browser on most platforms . brow_bin is only used on OS s where there is no open or start cmd .
4,859
def read ( self , file , nbytes ) : if not capable . OF_GRAPHICS : raise RuntimeError ( "Cannot run this command without graphics" ) if isinstance ( file , int ) : fd = file else : try : fd = file . fileno ( ) except : raise TypeError ( "file must be an integer or a filehandle/socket" ) init_tk_default_root ( ) self . widget = TKNTR . _default_root if not self . widget : s = [ ] while nbytes > 0 : snew = os . read ( fd , nbytes ) if snew : if PY3K : snew = snew . decode ( 'ascii' , 'replace' ) s . append ( snew ) nbytes -= len ( snew ) else : break return "" . join ( s ) else : self . nbytes = nbytes self . value = [ ] self . widget . tk . createfilehandler ( fd , TKNTR . READABLE | TKNTR . EXCEPTION , self . _read ) try : self . widget . mainloop ( ) finally : self . widget . tk . deletefilehandler ( fd ) return "" . join ( self . value )
Read nbytes characters from file while running Tk mainloop
4,860
def _read ( self , fd , mask ) : try : if select . select ( [ fd ] , [ ] , [ ] , 0 ) [ 0 ] : snew = os . read ( fd , self . nbytes ) if PY3K : snew = snew . decode ( 'ascii' , 'replace' ) self . value . append ( snew ) self . nbytes -= len ( snew ) else : snew = '' if ( self . nbytes <= 0 or len ( snew ) == 0 ) and self . widget : self . widget . quit ( ) except OSError : raise IOError ( "Error reading from %s" % ( fd , ) )
Read waiting data and terminate Tk mainloop if done
4,861
def legal_date ( year , month , day ) : try : assert year >= 1 assert 0 < month <= 14 assert 0 < day <= 28 if month == 14 : if isleap ( year + YEAR_EPOCH - 1 ) : assert day <= 2 else : assert day == 1 except AssertionError : raise ValueError ( "Invalid Positivist date: ({}, {}, {})" . format ( year , month , day ) ) return True
Checks if a given date is a legal positivist date
4,862
def to_jd ( year , month , day ) : legal_date ( year , month , day ) gyear = year + YEAR_EPOCH - 1 return ( gregorian . EPOCH - 1 + ( 365 * ( gyear - 1 ) ) + floor ( ( gyear - 1 ) / 4 ) + ( - floor ( ( gyear - 1 ) / 100 ) ) + floor ( ( gyear - 1 ) / 400 ) + ( month - 1 ) * 28 + day )
Convert a Positivist date to Julian day count .
4,863
def from_jd ( jd ) : try : assert jd >= EPOCH except AssertionError : raise ValueError ( 'Invalid Julian day' ) depoch = floor ( jd - 0.5 ) + 0.5 - gregorian . EPOCH quadricent = floor ( depoch / gregorian . INTERCALATION_CYCLE_DAYS ) dqc = depoch % gregorian . INTERCALATION_CYCLE_DAYS cent = floor ( dqc / gregorian . LEAP_SUPPRESSION_DAYS ) dcent = dqc % gregorian . LEAP_SUPPRESSION_DAYS quad = floor ( dcent / gregorian . LEAP_CYCLE_DAYS ) dquad = dcent % gregorian . LEAP_CYCLE_DAYS yindex = floor ( dquad / gregorian . YEAR_DAYS ) year = ( quadricent * gregorian . INTERCALATION_CYCLE_YEARS + cent * gregorian . LEAP_SUPPRESSION_YEARS + quad * gregorian . LEAP_CYCLE_YEARS + yindex ) if yindex == 4 : yearday = 365 year = year - 1 else : yearday = ( depoch - quadricent * gregorian . INTERCALATION_CYCLE_DAYS - cent * gregorian . LEAP_SUPPRESSION_DAYS - quad * gregorian . LEAP_CYCLE_DAYS - yindex * gregorian . YEAR_DAYS ) month = floor ( yearday / 28 ) return ( year - YEAR_EPOCH + 2 , month + 1 , int ( yearday - ( month * 28 ) ) + 1 )
Convert a Julian day count to Positivist date .
4,864
def dayname ( year , month , day ) : legal_date ( year , month , day ) yearday = ( month - 1 ) * 28 + day if isleap ( year + YEAR_EPOCH - 1 ) : dname = data . day_names_leap [ yearday - 1 ] else : dname = data . day_names [ yearday - 1 ] return MONTHS [ month - 1 ] , dname
Give the name of the month and day for a given date .
4,865
def _evictStaleDevices ( self ) : while self . running : expiredDeviceIds = [ key for key , value in self . devices . items ( ) if value . hasExpired ( ) ] for key in expiredDeviceIds : logger . warning ( "Device timeout, removing " + key ) del self . devices [ key ] time . sleep ( 1 ) logger . warning ( "DeviceCaretaker is now shutdown" )
A housekeeping function which runs in a worker thread and which evicts devices that haven t sent an update for a while .
4,866
def list_parse ( name_list ) : if name_list and name_list [ 0 ] == '@' : value = name_list [ 1 : ] if not os . path . exists ( value ) : log . warning ( 'The file %s does not exist' % value ) return try : return [ v . strip ( ) for v in open ( value , 'r' ) . readlines ( ) ] except IOError as e : log . warning ( 'reading %s failed: %s; ignoring this file' % ( value , e ) ) else : return [ v . strip ( ) for v in name_list . split ( ',' ) ]
Parse a comma - separated list of values or a filename ( starting with
4,867
def _mmInit ( self ) : mmkeys = { } mmkeysGet = mmkeys . setdefault minkeylength = self . minkeylength for key in self . data . keys ( ) : lenkey = len ( key ) start = min ( minkeylength , lenkey ) for i in range ( start , lenkey + 1 ) : mmkeysGet ( key [ 0 : i ] , [ ] ) . append ( key ) self . mmkeys = mmkeys
Create the minimum match dictionary of keys
4,868
def resolve ( self , key , keylist ) : raise AmbiguousKeyError ( "Ambiguous key " + repr ( key ) + ", could be any of " + str ( sorted ( keylist ) ) )
Hook to resolve ambiguities in selected keys
4,869
def get ( self , key , failobj = None , exact = 0 ) : if not exact : key = self . getfullkey ( key , new = 1 ) return self . data . get ( key , failobj )
Raises exception if key is ambiguous
4,870
def _has ( self , key , exact = 0 ) : if not exact : key = self . getfullkey ( key , new = 1 ) return key in self . data
Raises an exception if key is ambiguous
4,871
def getall ( self , key , failobj = None ) : if self . mmkeys is None : self . _mmInit ( ) k = self . mmkeys . get ( key ) if not k : return failobj return list ( map ( self . data . get , k ) )
Returns a list of all the matching values for key containing a single entry for unambiguous matches and multiple entries for ambiguous matches .
4,872
def get ( self , key , failobj = None , exact = 0 ) : if not exact : try : key = self . getfullkey ( key ) except KeyError : return failobj return self . data . get ( key , failobj )
Returns failobj if key is not found or is ambiguous
4,873
def _has ( self , key , exact = 0 ) : if not exact : try : key = self . getfullkey ( key ) return 1 except KeyError : return 0 else : return key in self . data
Returns false if key is not found or is ambiguous
4,874
def parFactory ( fields , strict = 0 ) : if len ( fields ) < 3 or None in fields [ 0 : 3 ] : raise SyntaxError ( "At least 3 fields must be given" ) type = fields [ 1 ] if type in _string_types : return IrafParS ( fields , strict ) elif type == 'R' : return StrictParR ( fields , 1 ) elif type in _real_types : return IrafParR ( fields , strict ) elif type == "I" : return StrictParI ( fields , 1 ) elif type == "i" : return IrafParI ( fields , strict ) elif type == "b" : return IrafParB ( fields , strict ) elif type == "ar" : return IrafParAR ( fields , strict ) elif type == "ai" : return IrafParAI ( fields , strict ) elif type == "as" : return IrafParAS ( fields , strict ) elif type == "ab" : return IrafParAB ( fields , strict ) elif type [ : 1 ] == "a" : raise SyntaxError ( "Cannot handle arrays of type %s" % type ) else : raise SyntaxError ( "Cannot handle parameter type %s" % type )
parameter factory function
4,875
def setCmdline ( self , value = 1 ) : if value : self . __dict__ [ 'flags' ] = self . flags | _cmdlineFlag else : self . __dict__ [ 'flags' ] = self . flags & ~ _cmdlineFlag
Set cmdline flag
4,876
def setChanged ( self , value = 1 ) : if value : self . __dict__ [ 'flags' ] = self . flags | _changedFlag else : self . __dict__ [ 'flags' ] = self . flags & ~ _changedFlag
Set changed flag
4,877
def isLearned ( self , mode = None ) : if "l" in self . mode : return 1 if "h" in self . mode : return 0 if "a" in self . mode : if mode is None : mode = 'ql' if "h" in mode and "l" not in mode : return 0 return 1
Return true if this parameter is learned
4,878
def getWithPrompt ( self ) : if self . prompt : pstring = self . prompt . split ( "\n" ) [ 0 ] . strip ( ) else : pstring = self . name if self . choice : schoice = list ( map ( self . toString , self . choice ) ) pstring = pstring + " (" + "|" . join ( schoice ) + ")" elif self . min not in [ None , INDEF ] or self . max not in [ None , INDEF ] : pstring = pstring + " (" if self . min not in [ None , INDEF ] : pstring = pstring + self . toString ( self . min ) pstring = pstring + ":" if self . max not in [ None , INDEF ] : pstring = pstring + self . toString ( self . max ) pstring = pstring + ")" if self . value is not None : pstring = pstring + " (" + self . toString ( self . value , quoted = 1 ) + ")" pstring = pstring + ": " stdout = sys . __stdout__ try : if sys . stdout . isatty ( ) or not stdout . isatty ( ) : stdout = sys . stdout except AttributeError : pass stdin = sys . __stdin__ try : if sys . stdin . isatty ( ) or not stdin . isatty ( ) : stdin = sys . stdin except AttributeError : pass stdout . write ( pstring ) stdout . flush ( ) ovalue = irafutils . tkreadline ( stdin ) value = ovalue . strip ( ) while ( 1 ) : try : if value == "" : value = self . _nullPrompt ( ) self . set ( value ) if self . value is not None : return if ovalue == "" : stdout . flush ( ) raise EOFError ( "EOF on parameter prompt" ) print ( "Error: specify a value for the parameter" ) except ValueError as e : print ( str ( e ) ) stdout . write ( pstring ) stdout . flush ( ) ovalue = irafutils . tkreadline ( stdin ) value = ovalue . strip ( )
Interactively prompt for parameter value
4,879
def checkOneValue ( self , v , strict = 0 ) : if v in [ None , INDEF ] or ( isinstance ( v , str ) and v [ : 1 ] == ")" ) : return v elif v == "" : return None elif self . choice is not None and v not in self . choiceDict : schoice = list ( map ( self . toString , self . choice ) ) schoice = "|" . join ( schoice ) raise ValueError ( "Parameter %s: " "value %s is not in choice list (%s)" % ( self . name , str ( v ) , schoice ) ) elif ( self . min not in [ None , INDEF ] and v < self . min ) : raise ValueError ( "Parameter %s: " "value `%s' is less than minimum `%s'" % ( self . name , str ( v ) , str ( self . min ) ) ) elif ( self . max not in [ None , INDEF ] and v > self . max ) : raise ValueError ( "Parameter %s: " "value `%s' is greater than maximum `%s'" % ( self . name , str ( v ) , str ( self . max ) ) ) return v
Checks a single value to see if it is in range or choice list
4,880
def pretty ( self , verbose = 0 ) : plines = self . prompt . split ( '\n' ) for i in range ( len ( plines ) - 1 ) : plines [ i + 1 ] = 32 * ' ' + plines [ i + 1 ] plines = '\n' . join ( plines ) namelen = min ( len ( self . name ) , 12 ) pvalue = self . get ( prompt = 0 , lpar = 1 ) alwaysquoted = [ 's' , 'f' , '*gcur' , '*imcur' , '*ukey' , 'pset' ] if self . type in alwaysquoted and self . value is not None : pvalue = '"' + pvalue + '"' if self . mode == "h" : s = "%13s = %-15s %s" % ( "(" + self . name [ : namelen ] , pvalue + ")" , plines ) else : s = "%13s = %-15s %s" % ( self . name [ : namelen ] , pvalue , plines ) if not verbose : return s if self . choice is not None : s = s + "\n" + 32 * " " + "|" nline = 33 for i in range ( len ( self . choice ) ) : sch = str ( self . choice [ i ] ) + "|" s = s + sch nline = nline + len ( sch ) + 1 if nline > 80 : s = s + "\n" + 32 * " " + "|" nline = 33 elif self . min not in [ None , INDEF ] or self . max not in [ None , INDEF ] : s = s + "\n" + 32 * " " if self . min not in [ None , INDEF ] : s = s + str ( self . min ) + " <= " s = s + self . name if self . max not in [ None , INDEF ] : s = s + " <= " + str ( self . max ) return s
Return pretty list description of parameter
4,881
def _setChoice ( self , s , strict = 0 ) : clist = _getChoice ( s , strict ) self . choice = list ( map ( self . _coerceValue , clist ) ) self . _setChoiceDict ( )
Set choice parameter from string s
4,882
def _setChoiceDict ( self ) : self . choiceDict = { } for c in self . choice : self . choiceDict [ c ] = c
Create dictionary for choice list
4,883
def _optionalPrompt ( self , mode ) : if ( self . mode == "h" ) or ( self . mode == "a" and mode == "h" ) : if not self . isLegal ( ) : self . getWithPrompt ( ) elif self . mode == "u" : if not self . isLegal ( ) : raise ValueError ( "Attempt to access undefined local variable `%s'" % self . name ) else : if self . isCmdline ( ) == 0 : self . getWithPrompt ( )
Interactively prompt for parameter if necessary
4,884
def _getPFilename ( self , native , prompt ) : return self . get ( native = native , prompt = prompt )
Get p_filename field for this parameter
4,885
def _getField ( self , field , native = 0 , prompt = 1 ) : try : field = _getFieldDict [ field ] except KeyError as e : raise SyntaxError ( "Cannot get field " + field + " for parameter " + self . name + "\n" + str ( e ) ) if field == "p_value" : return self . get ( native = native , prompt = prompt ) elif field == "p_name" : return self . name elif field == "p_xtype" : return self . type elif field == "p_type" : return self . _getPType ( ) elif field == "p_mode" : return self . mode elif field == "p_prompt" : return self . prompt elif field == "p_scope" : return self . scope elif field == "p_default" or field == "p_filename" : return self . _getPFilename ( native , prompt ) elif field == "p_maximum" : if native : return self . max else : return self . toString ( self . max ) elif field == "p_minimum" : if self . choice is not None : if native : return self . choice else : schoice = list ( map ( self . toString , self . choice ) ) return "|" + "|" . join ( schoice ) + "|" else : if native : return self . min else : return self . toString ( self . min ) else : raise RuntimeError ( "Program bug in IrafPar._getField()\n" + "Requested field " + field + " for parameter " + self . name )
Get a parameter field value
4,886
def _setField ( self , value , field , check = 1 ) : try : field = _setFieldDict [ field ] except KeyError as e : raise SyntaxError ( "Cannot set field " + field + " for parameter " + self . name + "\n" + str ( e ) ) if field == "p_prompt" : self . prompt = irafutils . removeEscapes ( irafutils . stripQuotes ( value ) ) elif field == "p_value" : self . set ( value , check = check ) elif field == "p_filename" : self . set ( value , check = check ) elif field == "p_scope" : self . scope = value elif field == "p_maximum" : self . max = self . _coerceOneValue ( value ) elif field == "p_minimum" : if isinstance ( value , str ) and '|' in value : self . _setChoice ( irafutils . stripQuotes ( value ) ) else : self . min = self . _coerceOneValue ( value ) elif field == "p_mode" : self . mode = irafutils . stripQuotes ( value ) else : raise RuntimeError ( "Program bug in IrafPar._setField()" + "Requested field " + field + " for parameter " + self . name )
Set a parameter field value
4,887
def _sumindex ( self , index = None ) : try : ndim = len ( index ) except TypeError : index = ( index , ) ndim = 1 if len ( self . shape ) != ndim : raise ValueError ( "Index to %d-dimensional array %s has too %s dimensions" % ( len ( self . shape ) , self . name , [ "many" , "few" ] [ len ( self . shape ) > ndim ] ) ) sumindex = 0 for i in range ( ndim - 1 , - 1 , - 1 ) : index1 = index [ i ] if index1 < 0 or index1 >= self . shape [ i ] : raise ValueError ( "Dimension %d index for array %s is out of bounds (value=%d)" % ( i + 1 , self . name , index1 ) ) sumindex = index1 + sumindex * self . shape [ i ] return sumindex
Convert tuple index to 1 - D index into value
4,888
def _coerceValue ( self , value , strict = 0 ) : try : if isinstance ( value , str ) : value = value . split ( ) if len ( value ) != len ( self . value ) : raise IndexError v = len ( self . value ) * [ 0 ] for i in range ( len ( v ) ) : v [ i ] = self . _coerceOneValue ( value [ i ] , strict ) return v except ( IndexError , TypeError ) : raise ValueError ( "Value must be a " + repr ( len ( self . value ) ) + "-element array for " + self . name )
Coerce parameter to appropriate type
4,889
def _setChoiceDict ( self ) : self . choiceDict = minmatch . MinMatchDict ( ) for c in self . choice : self . choiceDict . add ( c , c )
Create min - match dictionary for choice list
4,890
def legal_date ( year , month , day ) : if month == 2 : daysinmonth = 29 if isleap ( year ) else 28 else : daysinmonth = 30 if month in HAVE_30_DAYS else 31 if not ( 0 < day <= daysinmonth ) : raise ValueError ( "Month {} doesn't have a day {}" . format ( month , day ) ) return True
Check if this is a legal date in the Gregorian calendar
4,891
def to_jd2 ( year , month , day ) : legal_date ( year , month , day ) if month <= 2 : year = year - 1 month = month + 12 a = floor ( year / 100 ) b = floor ( a / 4 ) c = 2 - a + b e = floor ( 365.25 * ( year + 4716 ) ) f = floor ( 30.6001 * ( month + 1 ) ) return c + day + e + f - 1524.5
Gregorian to Julian Day Count for years between 1801 - 2099
4,892
def to_jd ( year , month , day ) : "Retrieve the Julian date equivalent for this date" return day + ( month - 1 ) * 30 + ( year - 1 ) * 365 + floor ( year / 4 ) + EPOCH - 1
Retrieve the Julian date equivalent for this date
4,893
def from_jd ( jdc ) : "Create a new date from a Julian date." cdc = floor ( jdc ) + 0.5 - EPOCH year = floor ( ( cdc - floor ( ( cdc + 366 ) / 1461 ) ) / 365 ) + 1 yday = jdc - to_jd ( year , 1 , 1 ) month = floor ( yday / 30 ) + 1 day = yday - ( month - 1 ) * 30 + 1 return year , month , day
Create a new date from a Julian date .
4,894
def print_archive ( self , format = True ) : if len ( list ( self . orig_wcs . keys ( ) ) ) > 0 : block = 'Original WCS keywords for ' + self . rootname + '\n' block += ' backed up on ' + repr ( self . orig_wcs [ 'WCSCDATE' ] ) + '\n' if not format : for key in self . wcstrans . keys ( ) : block += key . upper ( ) + " = " + repr ( self . get_archivekw ( key ) ) + '\n' block = 'PA_V3: ' + repr ( self . pa_obs ) + '\n' else : block += 'CD_11 CD_12: ' + repr ( self . get_archivekw ( 'CD1_1' ) ) + ' ' + repr ( self . get_archivekw ( 'CD1_2' ) ) + '\n' block += 'CD_21 CD_22: ' + repr ( self . get_archivekw ( 'CD2_1' ) ) + ' ' + repr ( self . get_archivekw ( 'CD2_2' ) ) + '\n' block += 'CRVAL : ' + repr ( self . get_archivekw ( 'CRVAL1' ) ) + ' ' + repr ( self . get_archivekw ( 'CRVAL2' ) ) + '\n' block += 'CRPIX : ' + repr ( self . get_archivekw ( 'CRPIX1' ) ) + ' ' + repr ( self . get_archivekw ( 'CRPIX2' ) ) + '\n' block += 'NAXIS : ' + repr ( int ( self . get_archivekw ( 'NAXIS1' ) ) ) + ' ' + repr ( int ( self . get_archivekw ( 'NAXIS2' ) ) ) + '\n' block += 'Plate Scale : ' + repr ( self . get_archivekw ( 'pixel scale' ) ) + '\n' block += 'ORIENTAT : ' + repr ( self . get_archivekw ( 'ORIENTAT' ) ) + '\n' print ( block )
Prints out archived WCS keywords .
4,895
def set_orient ( self ) : self . orient = RADTODEG ( N . arctan2 ( self . cd12 , self . cd22 ) )
Return the computed orientation based on CD matrix .
4,896
def updateWCS ( self , pixel_scale = None , orient = None , refpos = None , refval = None , size = None ) : _updateCD = no if orient is not None and orient != self . orient : pa = DEGTORAD ( orient ) self . orient = orient self . _orient_lin = orient _updateCD = yes else : pa = DEGTORAD ( self . orient ) if pixel_scale is not None and pixel_scale != self . pscale : _ratio = pixel_scale / self . pscale self . pscale = pixel_scale _updateCD = yes else : pixel_scale = self . pscale _ratio = None if _ratio is not None : self . naxis1 /= _ratio self . naxis2 /= _ratio self . crpix1 = self . naxis1 / 2. self . crpix2 = self . naxis2 / 2. if size is not None : self . naxis1 = size [ 0 ] self . naxis2 = size [ 1 ] self . naxis1 = int ( self . naxis1 ) self . naxis2 = int ( self . naxis2 ) if refpos is not None : self . crpix1 = refpos [ 0 ] self . crpix2 = refpos [ 1 ] if self . crpix1 is None : self . crpix1 = self . naxis1 / 2. self . crpix2 = self . naxis2 / 2. if refval is not None : self . crval1 = refval [ 0 ] self . crval2 = refval [ 1 ] if _updateCD : pscale = pixel_scale / 3600. self . cd11 = - pscale * N . cos ( pa ) self . cd12 = pscale * N . sin ( pa ) self . cd21 = self . cd12 self . cd22 = - self . cd11 self . update ( )
Create a new CD Matrix from the absolute pixel scale and reference image orientation .
4,897
def xy2rd ( self , pos ) : if self . ctype1 . find ( 'TAN' ) < 0 or self . ctype2 . find ( 'TAN' ) < 0 : print ( 'XY2RD only supported for TAN projections.' ) raise TypeError if isinstance ( pos , N . ndarray ) : posx = pos [ : , 0 ] posy = pos [ : , 1 ] else : posx = pos [ 0 ] posy = pos [ 1 ] xi = self . cd11 * ( posx - self . crpix1 ) + self . cd12 * ( posy - self . crpix2 ) eta = self . cd21 * ( posx - self . crpix1 ) + self . cd22 * ( posy - self . crpix2 ) xi = DEGTORAD ( xi ) eta = DEGTORAD ( eta ) ra0 = DEGTORAD ( self . crval1 ) dec0 = DEGTORAD ( self . crval2 ) ra = N . arctan ( ( xi / ( N . cos ( dec0 ) - eta * N . sin ( dec0 ) ) ) ) + ra0 dec = N . arctan ( ( ( eta * N . cos ( dec0 ) + N . sin ( dec0 ) ) / ( N . sqrt ( ( N . cos ( dec0 ) - eta * N . sin ( dec0 ) ) ** 2 + xi ** 2 ) ) ) ) ra = RADTODEG ( ra ) dec = RADTODEG ( dec ) ra = DIVMOD ( ra , 360. ) return ra , dec
This method would apply the WCS keywords to a position to generate a new sky position .
4,898
def rotateCD ( self , orient ) : _delta = self . get_orient ( ) - orient if _delta == 0. : return _rot = fileutil . buildRotMatrix ( _delta ) _cd = N . array ( [ [ self . cd11 , self . cd12 ] , [ self . cd21 , self . cd22 ] ] , dtype = N . float64 ) _cdrot = N . dot ( _cd , _rot ) self . cd11 = _cdrot [ 0 ] [ 0 ] self . cd12 = _cdrot [ 0 ] [ 1 ] self . cd21 = _cdrot [ 1 ] [ 0 ] self . cd22 = _cdrot [ 1 ] [ 1 ] self . orient = orient
Rotates WCS CD matrix to new orientation given by orient
4,899
def write ( self , fitsname = None , wcs = None , archive = True , overwrite = False , quiet = True ) : self . update ( ) image = self . rootname _fitsname = fitsname if image . find ( '.fits' ) < 0 and _fitsname is not None : self . geisname = image image = self . rootname = _fitsname fimg = fileutil . openImage ( image , mode = 'update' , fitsname = _fitsname ) _root , _iextn = fileutil . parseFilename ( image ) _extn = fileutil . getExtn ( fimg , _iextn ) if wcs : _wcsobj = wcs else : _wcsobj = self for key in _wcsobj . wcstrans . keys ( ) : _dkey = _wcsobj . wcstrans [ key ] if _dkey != 'pscale' : _extn . header [ key ] = _wcsobj . __dict__ [ _dkey ] fimg . close ( ) del fimg if archive : self . write_archive ( fitsname = fitsname , overwrite = overwrite , quiet = quiet )
Write out the values of the WCS keywords to the specified image .