idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
55,500
def execute ( self ) : if self . args and self . argument ( 0 ) == "help" : self . error ( self . usage ( ) + "\n\n" + self . help ( ) ) return False return True
Execute the command . Intercepts the help subsubcommand to show the help text .
55,501
def argument ( self , p_number ) : try : return self . args [ p_number ] except IndexError as ie : raise InvalidCommandArgument from ie
Retrieves a value from the argument list at the given position .
55,502
def config ( p_path = None , p_overrides = None ) : if not config . instance or p_path is not None or p_overrides is not None : try : config . instance = _Config ( p_path , p_overrides ) except configparser . ParsingError as perr : raise ConfigError ( str ( perr ) ) from perr return config . instance
Retrieve the config instance .
55,503
def colors ( self , p_hint_possible = True ) : lookup = { 'false' : 0 , 'no' : 0 , '0' : 0 , '1' : 16 , 'true' : 16 , 'yes' : 16 , '16' : 16 , '256' : 256 , } try : forced = self . cp . get ( 'topydo' , 'force_colors' ) == '1' except ValueError : forced = self . defaults [ 'topydo' ] [ 'force_colors' ] == '1' try : col...
Returns 0 16 or 256 representing the number of colors that should be used in the output .
55,504
def hidden_tags ( self ) : hidden_tags = self . cp . get ( 'ls' , 'hide_tags' ) return [ ] if hidden_tags == '' else [ tag . strip ( ) for tag in hidden_tags . split ( ',' ) ]
Returns a list of tags to be hidden from the ls output .
55,505
def hidden_item_tags ( self ) : hidden_item_tags = self . cp . get ( 'ls' , 'hidden_item_tags' ) return [ ] if hidden_item_tags == '' else [ tag . strip ( ) for tag in hidden_item_tags . split ( ',' ) ]
Returns a list of tags which hide an item from the ls output .
55,506
def priority_color ( self , p_priority ) : def _str_to_dict ( p_string ) : pri_colors_dict = dict ( ) for pri_color in p_string . split ( ',' ) : pri , color = pri_color . split ( ':' ) pri_colors_dict [ pri ] = Color ( color ) return pri_colors_dict try : pri_colors_str = self . cp . get ( 'colorscheme' , 'priority_co...
Returns a dict with priorities as keys and color numbers as value .
55,507
def aliases ( self ) : aliases = self . cp . items ( 'aliases' ) alias_dict = dict ( ) for alias , meaning in aliases : try : meaning = shlex . split ( meaning ) real_subcommand = meaning [ 0 ] alias_args = meaning [ 1 : ] alias_dict [ alias ] = ( real_subcommand , alias_args ) except ValueError as verr : alias_dict [ ...
Returns dict with aliases names as keys and pairs of actual subcommand and alias args as values .
55,508
def column_keymap ( self ) : keystates = set ( ) shortcuts = self . cp . items ( 'column_keymap' ) keymap_dict = dict ( shortcuts ) for combo , action in shortcuts : combo_as_list = re . split ( '(<[A-Z].+?>|.)' , combo ) [ 1 : : 2 ] if len ( combo_as_list ) > 1 : keystates |= set ( accumulate ( combo_as_list [ : - 1 ]...
Returns keymap and keystates used in column mode
55,509
def editor ( self ) : result = 'vi' if 'TOPYDO_EDITOR' in os . environ and os . environ [ 'TOPYDO_EDITOR' ] : result = os . environ [ 'TOPYDO_EDITOR' ] else : try : result = str ( self . cp . get ( 'edit' , 'editor' ) ) except configparser . NoOptionError : if 'EDITOR' in os . environ and os . environ [ 'EDITOR' ] : re...
Returns the editor to invoke . It returns a list with the command in the first position and its arguments in the remainder .
55,510
def execute ( self ) : if not super ( ) . execute ( ) : return False self . printer . add_filter ( PrettyPrinterNumbers ( self . todolist ) ) self . _process_flags ( ) if self . from_file : try : new_todos = self . get_todos_from_file ( ) for todo in new_todos : self . _add_todo ( todo ) except ( IOError , OSError ) : ...
Adds a todo item to the list .
55,511
def advance_recurring_todo ( p_todo , p_offset = None , p_strict = False ) : todo = Todo ( p_todo . source ( ) ) pattern = todo . tag_value ( 'rec' ) if not pattern : raise NoRecurrenceException ( ) elif pattern . startswith ( '+' ) : p_strict = True pattern = pattern [ 1 : ] if p_strict : offset = p_todo . due_date ( ...
Given a Todo item return a new instance of a Todo item with the dates shifted according to the recurrence rule .
55,512
def _get_table_size ( p_alphabet , p_num ) : try : for width , size in sorted ( _TABLE_SIZES [ len ( p_alphabet ) ] . items ( ) ) : if p_num < size * 0.01 : return width , size except KeyError : pass raise _TableSizeException ( 'Could not find appropriate table size for given alphabet' )
Returns a prime number that is suitable for the hash table size . The size is dependent on the alphabet used and the number of items that need to be hashed . The table size is at least 100 times larger than the number of items to be hashed to avoid collisions .
55,513
def hash_list_values ( p_list , p_key = lambda i : i ) : def to_base ( p_alphabet , p_value ) : result = '' while p_value : p_value , i = divmod ( p_value , len ( p_alphabet ) ) result = p_alphabet [ i ] + result return result or p_alphabet [ 0 ] result = [ ] used = set ( ) alphabet = config ( ) . identifier_alphabet (...
Calculates a unique value for each item in the list these can be used as identifiers .
55,514
def max_id_length ( p_num ) : try : alphabet = config ( ) . identifier_alphabet ( ) length , _ = _get_table_size ( alphabet , p_num ) except _TableSizeException : length , _ = _get_table_size ( _DEFAULT_ALPHABET , p_num ) return length
Returns the length of the IDs used given the number of items that are assigned an ID . Used for padding in lists .
55,515
def filter ( self , p_todo_str , p_todo ) : if config ( ) . colors ( ) : p_todo_str = TopydoString ( p_todo_str , p_todo ) priority_color = config ( ) . priority_color ( p_todo . priority ( ) ) colors = [ ( r'\B@(\S*\w)' , AbstractColor . CONTEXT ) , ( r'\B\+(\S*\w)' , AbstractColor . PROJECT ) , ( r'\b\S+:[^/\s]\S*\b'...
Applies the colors .
55,516
def get_filter_list ( p_expression ) : result = [ ] for arg in p_expression : is_negated = len ( arg ) > 1 and arg [ 0 ] == '-' arg = arg [ 1 : ] if is_negated else arg argfilter = None for match , _filter in MATCHES : if re . match ( match , arg ) : argfilter = _filter ( arg ) break if not argfilter : argfilter = Grep...
Returns a list of GrepFilters OrdinalTagFilters or NegationFilters based on the given filter expression .
55,517
def match ( self , p_todo ) : children = self . todolist . children ( p_todo ) uncompleted = [ todo for todo in children if not todo . is_completed ( ) ] return not uncompleted
Returns True when there are no children that are uncompleted yet .
55,518
def match ( self , p_todo ) : try : self . todos . index ( p_todo ) return True except ValueError : return False
Returns True when p_todo appears in the list of given todos .
55,519
def match ( self , p_todo ) : for my_tag in config ( ) . hidden_item_tags ( ) : my_values = p_todo . tag_values ( my_tag ) for my_value in my_values : if not my_value in ( 0 , '0' , False , 'False' ) : return False return True
Returns True when p_todo doesn t have a tag to mark it as hidden .
55,520
def compare_operands ( self , p_operand1 , p_operand2 ) : if self . operator == '<' : return p_operand1 < p_operand2 elif self . operator == '<=' : return p_operand1 <= p_operand2 elif self . operator == '=' : return p_operand1 == p_operand2 elif self . operator == '>=' : return p_operand1 >= p_operand2 elif self . ope...
Returns True if conditional constructed from both operands and self . operator is valid . Returns False otherwise .
55,521
def match ( self , p_todo ) : operand1 = self . value operand2 = p_todo . priority ( ) or 'ZZ' return self . compare_operands ( operand1 , operand2 )
Performs a match on a priority in the todo .
55,522
def date_suggestions ( ) : days_of_week = { 0 : "Monday" , 1 : "Tuesday" , 2 : "Wednesday" , 3 : "Thursday" , 4 : "Friday" , 5 : "Saturday" , 6 : "Sunday" } dates = [ 'today' , 'tomorrow' , ] dow = datetime . date . today ( ) . weekday ( ) for i in range ( dow + 2 % 7 , dow + 7 ) : dates . append ( days_of_week [ i % 7...
Returns a list of relative date that is presented to the user as auto complete suggestions .
55,523
def write ( p_file , p_string ) : if not config ( ) . colors ( p_file . isatty ( ) ) : p_string = escape_ansi ( p_string ) if p_string : p_file . write ( p_string + "\n" )
Write p_string to file p_file trailed by a newline character .
55,524
def lookup_color ( p_color ) : if not lookup_color . colors : lookup_color . colors [ AbstractColor . NEUTRAL ] = Color ( 'NEUTRAL' ) lookup_color . colors [ AbstractColor . PROJECT ] = config ( ) . project_color ( ) lookup_color . colors [ AbstractColor . CONTEXT ] = config ( ) . context_color ( ) lookup_color . color...
Converts an AbstractColor to a normal Color . Returns the Color itself when a normal color is passed .
55,525
def insert_ansi ( p_string ) : result = p_string . data for pos , color in sorted ( p_string . colors . items ( ) , reverse = True ) : color = lookup_color ( color ) result = result [ : pos ] + color . as_ansi ( ) + result [ pos : ] return result
Returns a string with color information at the right positions .
55,526
def version ( ) : from topydo . lib . Version import VERSION , LICENSE print ( "topydo {}\n" . format ( VERSION ) ) print ( LICENSE ) sys . exit ( 0 )
Print the current version and exit .
55,527
def _archive ( self ) : archive , archive_file = _retrieve_archive ( ) if self . backup : self . backup . add_archive ( archive ) if archive : from topydo . commands . ArchiveCommand import ArchiveCommand command = ArchiveCommand ( self . todolist , archive ) command . execute ( ) if archive . dirty : archive_file . wr...
Performs an archive action on the todolist .
55,528
def is_read_only ( p_command ) : read_only_commands = tuple ( cmd for cmd in ( 'revert' , ) + READ_ONLY_COMMANDS ) return p_command . name ( ) in read_only_commands
Returns True when the given command class is read - only .
55,529
def _post_execute ( self ) : if self . todolist . dirty : if self . do_archive and config ( ) . archive ( ) : self . _archive ( ) elif config ( ) . archive ( ) and self . backup : archive = _retrieve_archive ( ) [ 0 ] self . backup . add_archive ( archive ) self . _post_archive_action ( ) if config ( ) . keep_sorted ( ...
Should be called when executing the user requested command has been completed . It will do some maintenance and write out the final result to the todo . txt file .
55,530
def get_date ( self , p_tag ) : string = self . tag_value ( p_tag ) result = None try : result = date_string_to_date ( string ) if string else None except ValueError : pass return result
Given a date tag return a date object .
55,531
def is_active ( self ) : start = self . start_date ( ) return not self . is_completed ( ) and ( not start or start <= date . today ( ) )
Returns True when the start date is today or in the past and the task has not yet been completed .
55,532
def days_till_due ( self ) : due = self . due_date ( ) if due : diff = due - date . today ( ) return diff . days return 0
Returns the number of days till the due date . Returns a negative number of days when the due date is in the past . Returns 0 when the task has no due date .
55,533
def _handle_ls ( self ) : try : arg1 = self . argument ( 1 ) arg2 = self . argument ( 2 ) todos = [ ] if arg2 == 'to' or arg1 == 'before' : number = arg1 if arg2 == 'to' else arg2 todo = self . todolist . todo ( number ) todos = self . todolist . children ( todo ) elif arg1 in { 'to' , 'after' } : number = arg2 todo = ...
Handles the ls subsubcommand .
55,534
def _handle_dot ( self ) : self . printer = DotPrinter ( self . todolist ) try : arg = self . argument ( 1 ) todo = self . todolist . todo ( arg ) arg = self . argument ( 1 ) todos = set ( [ self . todolist . todo ( arg ) ] ) todos |= set ( self . todolist . children ( todo ) ) todos |= set ( self . todolist . parents ...
Handles the dot subsubcommand .
55,535
def todo ( self , p_identifier ) : result = None def todo_by_uid ( p_identifier ) : result = None if config ( ) . identifiers ( ) == 'text' : try : result = self . _id_todo_map [ p_identifier ] except KeyError : pass return result def todo_by_linenumber ( p_identifier ) : result = None if config ( ) . identifiers ( ) !...
The _todos list has the same order as in the backend store ( usually a todo . txt file . The user refers to the first task as number 1 so use index 0 etc .
55,536
def add ( self , p_src ) : todos = self . add_list ( [ p_src ] ) return todos [ 0 ] if len ( todos ) else None
Given a todo string parse it and put it to the end of the list .
55,537
def replace ( self , p_todos ) : self . erase ( ) self . add_todos ( p_todos ) self . dirty = True
Replaces whole todolist with todo objects supplied as p_todos .
55,538
def append ( self , p_todo , p_string ) : if len ( p_string ) > 0 : new_text = p_todo . source ( ) + ' ' + p_string p_todo . set_source_text ( new_text ) self . _update_todo_ids ( ) self . dirty = True
Appends a text to the todo specified by its number . The todo will be parsed again such that tags and projects in de appended string are processed .
55,539
def projects ( self ) : result = set ( ) for todo in self . _todos : projects = todo . projects ( ) result = result . union ( projects ) return result
Returns a set of all projects in this list .
55,540
def contexts ( self ) : result = set ( ) for todo in self . _todos : contexts = todo . contexts ( ) result = result . union ( contexts ) return result
Returns a set of all contexts in this list .
55,541
def linenumber ( self , p_todo ) : try : return self . _todos . index ( p_todo ) + 1 except ValueError as ex : raise InvalidTodoException from ex
Returns the line number of the todo item .
55,542
def uid ( self , p_todo ) : try : return self . _todo_id_map [ p_todo ] except KeyError as ex : raise InvalidTodoException from ex
Returns the unique text - based ID for a todo item .
55,543
def number ( self , p_todo ) : if config ( ) . identifiers ( ) == "text" : return self . uid ( p_todo ) else : return self . linenumber ( p_todo )
Returns the line number or text ID of a todo ( depends on the configuration .
55,544
def max_id_length ( self ) : if config ( ) . identifiers ( ) == "text" : return max_id_length ( len ( self . _todos ) ) else : try : return math . ceil ( math . log ( len ( self . _todos ) , 10 ) ) except ValueError : return 0
Returns the maximum length of a todo ID used for formatting purposes .
55,545
def ids ( self ) : if config ( ) . identifiers ( ) == 'text' : ids = self . _id_todo_map . keys ( ) else : ids = [ str ( i + 1 ) for i in range ( self . count ( ) ) ] return set ( ids )
Returns set with all todo IDs .
55,546
def prepare ( self , p_args ) : if self . _todo_ids : id_position = p_args . index ( '{}' ) if self . _multi : p_args [ id_position : id_position + 1 ] = self . _todo_ids self . _operations . append ( p_args ) else : for todo_id in self . _todo_ids : operation_args = p_args [ : ] operation_args [ id_position ] = todo_i...
Prepares list of operations to execute based on p_args list of todo items contained in _todo_ids attribute and _subcommand attribute .
55,547
def execute ( self ) : last_operation = len ( self . _operations ) - 1 for i , operation in enumerate ( self . _operations ) : command = self . _cmd ( operation ) if command . execute ( ) is False : return False else : action = command . execute_post_archive_actions self . _post_archive_actions . append ( action ) if i...
Executes each operation from _operations attribute .
55,548
def _add_months ( p_sourcedate , p_months ) : month = p_sourcedate . month - 1 + p_months year = p_sourcedate . year + month // 12 month = month % 12 + 1 day = min ( p_sourcedate . day , calendar . monthrange ( year , month ) [ 1 ] ) return date ( year , month , day )
Adds a number of months to the source date .
55,549
def _add_business_days ( p_sourcedate , p_bdays ) : result = p_sourcedate delta = 1 if p_bdays > 0 else - 1 while abs ( p_bdays ) > 0 : result += timedelta ( delta ) weekday = result . weekday ( ) if weekday >= 5 : continue p_bdays = p_bdays - 1 if delta > 0 else p_bdays + 1 return result
Adds a number of business days to the source date .
55,550
def _convert_weekday_pattern ( p_weekday ) : day_value = { 'mo' : 0 , 'tu' : 1 , 'we' : 2 , 'th' : 3 , 'fr' : 4 , 'sa' : 5 , 'su' : 6 } target_day_string = p_weekday [ : 2 ] . lower ( ) target_day = day_value [ target_day_string ] day = date . today ( ) . weekday ( ) shift = 7 - ( day - target_day ) % 7 return date . t...
Converts a weekday name to an absolute date .
55,551
def relative_date_to_date ( p_date , p_offset = None ) : result = None p_date = p_date . lower ( ) p_offset = p_offset or date . today ( ) relative = re . match ( '(?P<length>-?[0-9]+)(?P<period>[dwmyb])$' , p_date , re . I ) monday = 'mo(n(day)?)?$' tuesday = 'tu(e(sday)?)?$' wednesday = 'we(d(nesday)?)?$' thursday = ...
Transforms a relative date into a date object .
55,552
def filter ( self , p_todo_str , p_todo ) : return "|{:>3}| {}" . format ( self . todolist . number ( p_todo ) , p_todo_str )
Prepends the number to the todo string .
55,553
def postprocess_input_todo ( self , p_todo ) : def convert_date ( p_tag ) : value = p_todo . tag_value ( p_tag ) if value : dateobj = relative_date_to_date ( value ) if dateobj : p_todo . set_tag ( p_tag , dateobj . isoformat ( ) ) def add_dependencies ( p_tag ) : for value in p_todo . tag_values ( p_tag ) : try : dep ...
Post - processes a parsed todo when adding it to the list .
55,554
def columns ( p_alt_layout_path = None ) : def _get_column_dict ( p_cp , p_column ) : column_dict = dict ( ) filterexpr = p_cp . get ( p_column , 'filterexpr' ) try : title = p_cp . get ( p_column , 'title' ) except NoOptionError : title = filterexpr column_dict [ 'title' ] = title or 'Yet another column' column_dict [...
Returns list with complete column configuration dicts .
55,555
def _active_todos ( self ) : return [ todo for todo in self . todolist . todos ( ) if not self . _uncompleted_children ( todo ) and todo . is_active ( ) ]
Returns a list of active todos taking uncompleted subtodos into account .
55,556
def _decompress_into_buffer ( self , out_buffer ) : zresult = lib . ZSTD_decompressStream ( self . _decompressor . _dctx , out_buffer , self . _in_buffer ) if self . _in_buffer . pos == self . _in_buffer . size : self . _in_buffer . src = ffi . NULL self . _in_buffer . pos = 0 self . _in_buffer . size = 0 self . _sourc...
Decompress available input into an output buffer .
55,557
def get_c_extension ( support_legacy = False , system_zstd = False , name = 'zstd' , warnings_as_errors = False , root = None ) : actual_root = os . path . abspath ( os . path . dirname ( __file__ ) ) root = root or actual_root sources = set ( [ os . path . join ( actual_root , p ) for p in ext_sources ] ) if not syste...
Obtain a distutils . extension . Extension for the C extension .
55,558
def timezone ( self ) : if not self . _timezone_group and not self . _timezone_location : return None if self . _timezone_location != "" : return "%s/%s" % ( self . _timezone_group , self . _timezone_location ) else : return self . _timezone_group
The name of the time zone for the location .
55,559
def tz ( self ) : if self . timezone is None : return None try : tz = pytz . timezone ( self . timezone ) return tz except pytz . UnknownTimeZoneError : raise AstralError ( "Unknown timezone '%s'" % self . timezone )
Time zone information .
55,560
def sun ( self , date = None , local = True , use_elevation = True ) : if local and self . timezone is None : raise ValueError ( "Local time requested but Location has no timezone set." ) if self . astral is None : self . astral = Astral ( ) if date is None : date = datetime . date . today ( ) elevation = self . elevat...
Returns dawn sunrise noon sunset and dusk as a dictionary .
55,561
def sunrise ( self , date = None , local = True , use_elevation = True ) : if local and self . timezone is None : raise ValueError ( "Local time requested but Location has no timezone set." ) if self . astral is None : self . astral = Astral ( ) if date is None : date = datetime . date . today ( ) elevation = self . el...
Return sunrise time .
55,562
def time_at_elevation ( self , elevation , direction = SUN_RISING , date = None , local = True ) : if local and self . timezone is None : raise ValueError ( "Local time requested but Location has no timezone set." ) if self . astral is None : self . astral = Astral ( ) if date is None : date = datetime . date . today (...
Calculate the time when the sun is at the specified elevation .
55,563
def blue_hour ( self , direction = SUN_RISING , date = None , local = True , use_elevation = True ) : if local and self . timezone is None : raise ValueError ( "Local time requested but Location has no timezone set." ) if self . astral is None : self . astral = Astral ( ) if date is None : date = datetime . date . toda...
Returns the start and end times of the Blue Hour when the sun is traversing in the specified direction .
55,564
def moon_phase ( self , date = None , rtype = int ) : if self . astral is None : self . astral = Astral ( ) if date is None : date = datetime . date . today ( ) return self . astral . moon_phase ( date , rtype )
Calculates the moon phase for a specific date .
55,565
def add_locations ( self , locations ) : if isinstance ( locations , ( str , ustr ) ) : self . _add_from_str ( locations ) elif isinstance ( locations , ( list , tuple ) ) : self . _add_from_list ( locations )
Add extra locations to AstralGeocoder .
55,566
def _add_from_str ( self , s ) : if sys . version_info [ 0 ] < 3 and isinstance ( s , str ) : s = s . decode ( 'utf-8' ) for line in s . split ( "\n" ) : self . _parse_line ( line )
Add locations from a string
55,567
def _add_from_list ( self , l ) : for item in l : if isinstance ( item , ( str , ustr ) ) : self . _add_from_str ( item ) elif isinstance ( item , ( list , tuple ) ) : location = Location ( item ) self . _add_location ( location )
Add locations from a list of either strings or lists or tuples .
55,568
def _get_geocoding ( self , key , location ) : url = self . _location_query_base % quote_plus ( key ) if self . api_key : url += "&key=%s" % self . api_key data = self . _read_from_url ( url ) response = json . loads ( data ) if response [ "status" ] == "OK" : formatted_address = response [ "results" ] [ 0 ] [ "formatt...
Lookup the Google geocoding API information for key
55,569
def _get_timezone ( self , location ) : url = self . _timezone_query_base % ( location . latitude , location . longitude , int ( time ( ) ) , ) if self . api_key != "" : url += "&key=%s" % self . api_key data = self . _read_from_url ( url ) response = json . loads ( data ) if response [ "status" ] == "OK" : location . ...
Query the timezone information with the latitude and longitude of the specified location .
55,570
def _get_elevation ( self , location ) : url = self . _elevation_query_base % ( location . latitude , location . longitude ) if self . api_key != "" : url += "&key=%s" % self . api_key data = self . _read_from_url ( url ) response = json . loads ( data ) if response [ "status" ] == "OK" : location . elevation = int ( f...
Query the elevation information with the latitude and longitude of the specified location .
55,571
def sun_utc ( self , date , latitude , longitude , observer_elevation = 0 ) : dawn = self . dawn_utc ( date , latitude , longitude , observer_elevation = observer_elevation ) sunrise = self . sunrise_utc ( date , latitude , longitude , observer_elevation = observer_elevation ) noon = self . solar_noon_utc ( date , long...
Calculate all the info for the sun at once . All times are returned in the UTC timezone .
55,572
def dawn_utc ( self , date , latitude , longitude , depression = 0 , observer_elevation = 0 ) : if depression == 0 : depression = self . _depression depression += 90 try : return self . _calc_time ( depression , SUN_RISING , date , latitude , longitude , observer_elevation ) except ValueError as exc : if exc . args [ 0...
Calculate dawn time in the UTC timezone .
55,573
def sunrise_utc ( self , date , latitude , longitude , observer_elevation = 0 ) : try : return self . _calc_time ( 90 + 0.833 , SUN_RISING , date , latitude , longitude , observer_elevation ) except ValueError as exc : if exc . args [ 0 ] == "math domain error" : raise AstralError ( ( "Sun never reaches the horizon on ...
Calculate sunrise time in the UTC timezone .
55,574
def solar_noon_utc ( self , date , longitude ) : jc = self . _jday_to_jcentury ( self . _julianday ( date ) ) eqtime = self . _eq_of_time ( jc ) timeUTC = ( 720.0 - ( 4 * longitude ) - eqtime ) / 60.0 hour = int ( timeUTC ) minute = int ( ( timeUTC - hour ) * 60 ) second = int ( ( ( ( timeUTC - hour ) * 60 ) - minute )...
Calculate solar noon time in the UTC timezone .
55,575
def sunset_utc ( self , date , latitude , longitude , observer_elevation = 0 ) : try : return self . _calc_time ( 90 + 0.833 , SUN_SETTING , date , latitude , longitude , observer_elevation ) except ValueError as exc : if exc . args [ 0 ] == "math domain error" : raise AstralError ( ( "Sun never reaches the horizon on ...
Calculate sunset time in the UTC timezone .
55,576
def dusk_utc ( self , date , latitude , longitude , depression = 0 , observer_elevation = 0 ) : if depression == 0 : depression = self . _depression depression += 90 try : return self . _calc_time ( depression , SUN_SETTING , date , latitude , longitude , observer_elevation ) except ValueError as exc : if exc . args [ ...
Calculate dusk time in the UTC timezone .
55,577
def solar_midnight_utc ( self , date , longitude ) : julianday = self . _julianday ( date ) newt = self . _jday_to_jcentury ( julianday + 0.5 + - longitude / 360.0 ) eqtime = self . _eq_of_time ( newt ) timeUTC = ( - longitude * 4.0 ) - eqtime timeUTC = timeUTC / 60.0 hour = int ( timeUTC ) minute = int ( ( timeUTC - h...
Calculate solar midnight time in the UTC timezone .
55,578
def daylight_utc ( self , date , latitude , longitude , observer_elevation = 0 ) : start = self . sunrise_utc ( date , latitude , longitude , observer_elevation ) end = self . sunset_utc ( date , latitude , longitude , observer_elevation ) return start , end
Calculate daylight start and end times in the UTC timezone .
55,579
def night_utc ( self , date , latitude , longitude , observer_elevation = 0 ) : start = self . dusk_utc ( date , latitude , longitude , 18 , observer_elevation ) tomorrow = date + datetime . timedelta ( days = 1 ) end = self . dawn_utc ( tomorrow , latitude , longitude , 18 , observer_elevation ) return start , end
Calculate night start and end times in the UTC timezone .
55,580
def blue_hour_utc ( self , direction , date , latitude , longitude , observer_elevation = 0 ) : if date is None : date = datetime . date . today ( ) start = self . time_at_elevation_utc ( - 6 , direction , date , latitude , longitude , observer_elevation ) end = self . time_at_elevation_utc ( - 4 , direction , date , l...
Returns the start and end times of the Blue Hour in the UTC timezone when the sun is traversing in the specified direction .
55,581
def time_at_elevation_utc ( self , elevation , direction , date , latitude , longitude , observer_elevation = 0 ) : if elevation > 90.0 : elevation = 180.0 - elevation direction = SUN_SETTING depression = 90 - elevation try : return self . _calc_time ( depression , direction , date , latitude , longitude , observer_ele...
Calculate the time in the UTC timezone when the sun is at the specified elevation on the specified date .
55,582
def solar_azimuth ( self , dateandtime , latitude , longitude ) : if latitude > 89.8 : latitude = 89.8 if latitude < - 89.8 : latitude = - 89.8 if dateandtime . tzinfo is None : zone = 0 utc_datetime = dateandtime else : zone = - dateandtime . utcoffset ( ) . total_seconds ( ) / 3600.0 utc_datetime = dateandtime . asti...
Calculate the azimuth angle of the sun .
55,583
def solar_zenith ( self , dateandtime , latitude , longitude ) : return 90.0 - self . solar_elevation ( dateandtime , latitude , longitude )
Calculates the solar zenith angle .
55,584
def moon_phase ( self , date , rtype = int ) : if rtype != float and rtype != int : rtype = int moon = self . _moon_phase_asfloat ( date ) if moon >= 28.0 : moon -= 28.0 moon = rtype ( moon ) return moon
Calculates the phase of the moon on the specified date .
55,585
def rahukaalam_utc ( self , date , latitude , longitude , observer_elevation = 0 ) : if date is None : date = datetime . date . today ( ) sunrise = self . sunrise_utc ( date , latitude , longitude , observer_elevation ) sunset = self . sunset_utc ( date , latitude , longitude , observer_elevation ) octant_duration = da...
Calculate ruhakaalam times in the UTC timezone .
55,586
def _depression_adjustment ( self , elevation ) : if elevation <= 0 : return 0 r = 6356900 a1 = r h1 = r + elevation theta1 = acos ( a1 / h1 ) a2 = r * sin ( theta1 ) b2 = r - ( r * cos ( theta1 ) ) h2 = sqrt ( pow ( a2 , 2 ) + pow ( b2 , 2 ) ) alpha = acos ( a2 / h2 ) return degrees ( alpha )
Calculate the extra degrees of depression due to the increase in elevation .
55,587
def callback ( status , message , job , result , exception , stacktrace ) : assert status in [ 'invalid' , 'success' , 'timeout' , 'failure' ] assert isinstance ( message , Message ) if status == 'invalid' : assert job is None assert result is None assert exception is None assert stacktrace is None if status == 'succes...
Example callback function .
55,588
def _execute_callback ( self , status , message , job , res , err , stacktrace ) : if self . _callback is not None : try : self . _logger . info ( 'Executing callback ...' ) self . _callback ( status , message , job , res , err , stacktrace ) except Exception as e : self . _logger . exception ( 'Callback raised an exce...
Execute the callback .
55,589
def _process_message ( self , msg ) : self . _logger . info ( 'Processing Message(topic={}, partition={}, offset={}) ...' . format ( msg . topic , msg . partition , msg . offset ) ) try : job = self . _deserializer ( msg . value ) job_repr = get_call_repr ( job . func , * job . args , ** job . kwargs ) except Exception...
De - serialize the message and execute the job .
55,590
def start ( self , max_messages = math . inf , commit_offsets = True ) : self . _logger . info ( 'Starting {} ...' . format ( self ) ) self . _consumer . unsubscribe ( ) self . _consumer . subscribe ( [ self . topic ] ) messages_processed = 0 while messages_processed < max_messages : record = next ( self . _consumer ) ...
Start processing Kafka messages and executing jobs .
55,591
def get_call_repr ( func , * args , ** kwargs ) : if ismethod ( func ) or isfunction ( func ) or isbuiltin ( func ) : func_repr = '{}.{}' . format ( func . __module__ , func . __qualname__ ) elif not isclass ( func ) and hasattr ( func , '__call__' ) : func_repr = '{}.{}' . format ( func . __module__ , func . __class__...
Return the string representation of the function call .
55,592
def using ( self , timeout = None , key = None , partition = None ) : return EnqueueSpec ( topic = self . _topic , producer = self . _producer , serializer = self . _serializer , logger = self . _logger , timeout = timeout or self . _timeout , key = key , partition = partition )
Set enqueue specifications such as timeout key and partition .
55,593
def send ( instructions , printer_identifier = None , backend_identifier = None , blocking = True ) : status = { 'instructions_sent' : True , 'outcome' : 'unknown' , 'printer_state' : None , 'did_print' : False , 'ready_for_next_job' : False , } selected_backend = None if backend_identifier : selected_backend = backend...
Send instruction bytes to a printer .
55,594
def merge_specific_instructions ( chunks , join_preamble = True , join_raster = True ) : new_instructions = [ ] last_opcode = None instruction_buffer = b'' for instruction in chunks : opcode = match_opcode ( instruction ) if join_preamble and OPCODES [ opcode ] [ 0 ] == 'preamble' and last_opcode == 'preamble' : instru...
Process a list of instructions by merging subsequent instuctions with identical opcodes into large instructions .
55,595
def cli ( ctx , * args , ** kwargs ) : backend = kwargs . get ( 'backend' , None ) model = kwargs . get ( 'model' , None ) printer = kwargs . get ( 'printer' , None ) debug = kwargs . get ( 'debug' ) ctx . meta [ 'MODEL' ] = model ctx . meta [ 'BACKEND' ] = backend ctx . meta [ 'PRINTER' ] = printer logging . basicConf...
Command line interface for the brother_ql Python package .
55,596
def env ( ctx , * args , ** kwargs ) : import sys , platform , os , shutil from pkg_resources import get_distribution , working_set print ( "\n##################\n" ) print ( "Information about the running environment of brother_ql." ) print ( "(Please provide this information when reporting any issue.)\n" ) print ( "A...
print debug info about running environment
55,597
def print_cmd ( ctx , * args , ** kwargs ) : backend = ctx . meta . get ( 'BACKEND' , 'pyusb' ) model = ctx . meta . get ( 'MODEL' ) printer = ctx . meta . get ( 'PRINTER' ) from brother_ql . conversion import convert from brother_ql . backends . helpers import send from brother_ql . raster import BrotherQLRaster qlr =...
Print a label of the provided IMAGE .
55,598
def list_available_devices ( ) : class find_class ( object ) : def __init__ ( self , class_ ) : self . _class = class_ def __call__ ( self , device ) : if device . bDeviceClass == self . _class : return True for cfg in device : intf = usb . util . find_descriptor ( cfg , bInterfaceClass = self . _class ) if intf is not...
List all available devices for the respective backend
55,599
def _populate_label_legacy_structures ( ) : global DIE_CUT_LABEL , ENDLESS_LABEL , ROUND_DIE_CUT_LABEL global label_sizes , label_type_specs from brother_ql . labels import FormFactor DIE_CUT_LABEL = FormFactor . DIE_CUT ENDLESS_LABEL = FormFactor . ENDLESS ROUND_DIE_CUT_LABEL = FormFactor . ROUND_DIE_CUT from brother_...
We contain this code inside a function so that the imports we do in here are not visible at the module level .