idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
243,400 | 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 . colors [ AbstractColor . META ] = config ( ) . metadata_color ( ) lookup_color . colors [ AbstractColor . LINK ] = config ( ) . link_color ( ) try : return lookup_color . colors [ p_color ] except KeyError : return p_color | Converts an AbstractColor to a normal Color . Returns the Color itself when a normal color is passed . | 148 | 21 |
243,401 | 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 . | 72 | 11 |
243,402 | 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 . | 47 | 7 |
243,403 | 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 . write ( archive . print_todos ( ) ) | Performs an archive action on the todolist . | 90 | 12 |
243,404 | 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 . | 57 | 12 |
243,405 | def _post_execute ( self ) : if self . todolist . dirty : # do not archive when the value of the filename is an empty string # (i.e. explicitly left empty in the configuration 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 ( ) : from topydo . commands . SortCommand import SortCommand self . _execute ( SortCommand , [ ] ) if self . backup : self . backup . save ( self . todolist ) self . todofile . write ( self . todolist . print_todos ( ) ) self . todolist . dirty = False self . backup = None | 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 . | 204 | 33 |
243,406 | 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 . | 52 | 9 |
243,407 | 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 . | 40 | 21 |
243,408 | 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 . | 38 | 35 |
243,409 | def _handle_ls ( self ) : try : arg1 = self . argument ( 1 ) arg2 = self . argument ( 2 ) todos = [ ] if arg2 == 'to' or arg1 == 'before' : # dep ls 1 to OR dep ls before 1 number = arg1 if arg2 == 'to' else arg2 todo = self . todolist . todo ( number ) todos = self . todolist . children ( todo ) elif arg1 in { 'to' , 'after' } : # dep ls to 1 OR dep ls after 1 number = arg2 todo = self . todolist . todo ( number ) todos = self . todolist . parents ( todo ) else : raise InvalidCommandArgument sorter = Sorter ( config ( ) . sort_string ( ) ) instance_filter = Filter . InstanceFilter ( todos ) view = View ( sorter , [ instance_filter ] , self . todolist ) self . out ( self . printer . print_list ( view . todos ) ) except InvalidTodoException : self . error ( "Invalid todo number given." ) except InvalidCommandArgument : self . error ( self . usage ( ) ) | Handles the ls subsubcommand . | 270 | 8 |
243,410 | 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 ( todo ) ) todos = sorted ( todos , key = lambda t : t . text ( ) ) self . out ( self . printer . print_list ( todos ) ) except InvalidTodoException : self . error ( "Invalid todo number given." ) except InvalidCommandArgument : self . error ( self . usage ( ) ) | Handles the dot subsubcommand . | 184 | 8 |
243,411 | def todo ( self , p_identifier ) : result = None def todo_by_uid ( p_identifier ) : """ Returns the todo that corresponds to the unique ID. """ result = None if config ( ) . identifiers ( ) == 'text' : try : result = self . _id_todo_map [ p_identifier ] except KeyError : pass # we'll try something else return result def todo_by_linenumber ( p_identifier ) : """ Attempts to find the todo on the given line number. When the identifier is a number but has leading zeros, the result will be None. """ result = None if config ( ) . identifiers ( ) != 'text' : try : if re . match ( '[1-9]\d*' , p_identifier ) : # the expression is a string and no leading zeroes, # treat it as an integer raise TypeError except TypeError as te : try : result = self . _todos [ int ( p_identifier ) - 1 ] except ( ValueError , IndexError ) : raise InvalidTodoException from te return result def todo_by_regexp ( p_identifier ) : """ Returns the todo that is (uniquely) identified by the given regexp. If the regexp matches more than one item, no result is returned. """ result = None candidates = Filter . GrepFilter ( p_identifier ) . filter ( self . _todos ) if len ( candidates ) == 1 : result = candidates [ 0 ] else : raise InvalidTodoException return result result = todo_by_uid ( p_identifier ) if not result : result = todo_by_linenumber ( p_identifier ) if not result : # convert integer to text so we pass on a valid regex result = todo_by_regexp ( str ( p_identifier ) ) return result | 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 . | 415 | 41 |
243,412 | 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 . | 39 | 17 |
243,413 | 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 . | 36 | 19 |
243,414 | 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 . | 75 | 33 |
243,415 | 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 . | 40 | 10 |
243,416 | 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 . | 40 | 10 |
243,417 | 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 . | 44 | 10 |
243,418 | 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 . | 43 | 13 |
243,419 | 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 . | 48 | 17 |
243,420 | 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 . | 73 | 14 |
243,421 | 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 . | 66 | 8 |
243,422 | def prepare ( self , p_args ) : if self . _todo_ids : id_position = p_args . index ( '{}' ) # Not using MultiCommand abilities would make EditCommand awkward 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_id self . _operations . append ( operation_args ) else : self . _operations . append ( p_args ) self . _create_label ( ) | Prepares list of operations to execute based on p_args list of todo items contained in _todo_ids attribute and _subcommand attribute . | 158 | 31 |
243,423 | 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 == last_operation : return True | Executes each operation from _operations attribute . | 90 | 10 |
243,424 | 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 . | 86 | 10 |
243,425 | 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 . | 95 | 11 |
243,426 | 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 . today ( ) + timedelta ( shift ) | Converts a weekday name to an absolute date . | 131 | 10 |
243,427 | 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 = 'th(u(rsday)?)?$' friday = 'fr(i(day)?)?$' saturday = 'sa(t(urday)?)?$' sunday = 'su(n(day)?)?$' weekday = re . match ( '|' . join ( [ monday , tuesday , wednesday , thursday , friday , saturday , sunday ] ) , p_date ) if relative : length = relative . group ( 'length' ) period = relative . group ( 'period' ) result = _convert_pattern ( length , period , p_offset ) elif weekday : result = _convert_weekday_pattern ( weekday . group ( 0 ) ) elif re . match ( 'tod(ay)?$' , p_date ) : result = _convert_pattern ( '0' , 'd' ) elif re . match ( 'tom(orrow)?$' , p_date ) : result = _convert_pattern ( '1' , 'd' ) elif re . match ( 'yes(terday)?$' , p_date ) : result = _convert_pattern ( '-1' , 'd' ) return result | Transforms a relative date into a date object . | 399 | 10 |
243,428 | 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 . | 54 | 10 |
243,429 | 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 = self . todolist . todo ( value ) if p_tag == 'after' : self . todolist . add_dependency ( p_todo , dep ) elif p_tag == 'before' or p_tag == 'partof' : self . todolist . add_dependency ( dep , p_todo ) elif p_tag . startswith ( 'parent' ) : for parent in self . todolist . parents ( dep ) : self . todolist . add_dependency ( parent , p_todo ) elif p_tag . startswith ( 'child' ) : for child in self . todolist . children ( dep ) : self . todolist . add_dependency ( p_todo , child ) except InvalidTodoException : pass p_todo . remove_tag ( p_tag , value ) convert_date ( config ( ) . tag_start ( ) ) convert_date ( config ( ) . tag_due ( ) ) keywords = [ 'after' , 'before' , 'child-of' , 'childof' , 'children-of' , 'childrenof' , 'parent-of' , 'parentof' , 'parents-of' , 'parentsof' , 'partof' , ] for keyword in keywords : add_dependencies ( keyword ) | Post - processes a parsed todo when adding it to the list . | 415 | 14 |
243,430 | 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 [ 'filterexpr' ] = filterexpr column_dict [ 'sortexpr' ] = p_cp . get ( p_column , 'sortexpr' ) column_dict [ 'groupexpr' ] = p_cp . get ( p_column , 'groupexpr' ) column_dict [ 'show_all' ] = p_cp . getboolean ( p_column , 'show_all' ) return column_dict defaults = { 'filterexpr' : '' , 'sortexpr' : config ( ) . sort_string ( ) , 'groupexpr' : config ( ) . group_string ( ) , 'show_all' : '0' , } cp = RawConfigParser ( defaults , strict = False ) files = [ "topydo_columns.ini" , "topydo_columns.conf" , ".topydo_columns" , home_config_path ( '.topydo_columns' ) , home_config_path ( '.config/topydo/columns' ) , "/etc/topydo_columns.conf" , ] if p_alt_layout_path is not None : files . insert ( 0 , expanduser ( p_alt_layout_path ) ) for filename in files : if cp . read ( filename ) : break column_list = [ ] for column in cp . sections ( ) : column_list . append ( _get_column_dict ( cp , column ) ) return column_list | Returns list with complete column configuration dicts . | 447 | 9 |
243,431 | 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 . | 54 | 16 |
243,432 | 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 . _source_buffer = None if not hasattr ( self . _source , 'read' ) : self . _finished_input = True if lib . ZSTD_isError ( zresult ) : raise ZstdError ( 'zstd decompress error: %s' % _zstd_error ( zresult ) ) # Emit data if there is data AND either: # a) output buffer is full (read amount is satisfied) # b) we're at end of a frame and not in frame spanning mode return ( out_buffer . pos and ( out_buffer . pos == out_buffer . size or zresult == 0 and not self . _read_across_frames ) ) | Decompress available input into an output buffer . | 252 | 10 |
243,433 | 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 system_zstd : sources . update ( [ os . path . join ( actual_root , p ) for p in zstd_sources ] ) if support_legacy : sources . update ( [ os . path . join ( actual_root , p ) for p in zstd_sources_legacy ] ) sources = list ( sources ) include_dirs = set ( [ os . path . join ( actual_root , d ) for d in ext_includes ] ) if not system_zstd : include_dirs . update ( [ os . path . join ( actual_root , d ) for d in zstd_includes ] ) if support_legacy : include_dirs . update ( [ os . path . join ( actual_root , d ) for d in zstd_includes_legacy ] ) include_dirs = list ( include_dirs ) depends = [ os . path . join ( actual_root , p ) for p in zstd_depends ] compiler = distutils . ccompiler . new_compiler ( ) # Needed for MSVC. if hasattr ( compiler , 'initialize' ) : compiler . initialize ( ) if compiler . compiler_type == 'unix' : compiler_type = 'unix' elif compiler . compiler_type == 'msvc' : compiler_type = 'msvc' elif compiler . compiler_type == 'mingw32' : compiler_type = 'mingw32' else : raise Exception ( 'unhandled compiler type: %s' % compiler . compiler_type ) extra_args = [ '-DZSTD_MULTITHREAD' ] if not system_zstd : extra_args . append ( '-DZSTDLIB_VISIBILITY=' ) extra_args . append ( '-DZDICTLIB_VISIBILITY=' ) extra_args . append ( '-DZSTDERRORLIB_VISIBILITY=' ) if compiler_type == 'unix' : extra_args . append ( '-fvisibility=hidden' ) if not system_zstd and support_legacy : extra_args . append ( '-DZSTD_LEGACY_SUPPORT=1' ) if warnings_as_errors : if compiler_type in ( 'unix' , 'mingw32' ) : extra_args . append ( '-Werror' ) elif compiler_type == 'msvc' : extra_args . append ( '/WX' ) else : assert False libraries = [ 'zstd' ] if system_zstd else [ ] # Python 3.7 doesn't like absolute paths. So normalize to relative. sources = [ os . path . relpath ( p , root ) for p in sources ] include_dirs = [ os . path . relpath ( p , root ) for p in include_dirs ] depends = [ os . path . relpath ( p , root ) for p in depends ] # TODO compile with optimizations. return Extension ( name , sources , include_dirs = include_dirs , depends = depends , extra_compile_args = extra_args , libraries = libraries ) | Obtain a distutils . extension . Extension for the C extension . | 780 | 14 |
243,434 | 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 . | 74 | 10 |
243,435 | 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 . | 63 | 4 |
243,436 | 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 . elevation if use_elevation else 0 sun = self . astral . sun_utc ( date , self . latitude , self . longitude , observer_elevation = elevation ) if local : for key , dt in sun . items ( ) : sun [ key ] = dt . astimezone ( self . tz ) return sun | Returns dawn sunrise noon sunset and dusk as a dictionary . | 158 | 11 |
243,437 | 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 . elevation if use_elevation else 0 sunrise = self . astral . sunrise_utc ( date , self . latitude , self . longitude , elevation ) if local : return sunrise . astimezone ( self . tz ) else : return sunrise | Return sunrise time . | 137 | 4 |
243,438 | 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 ( ) if elevation > 90.0 : elevation = 180.0 - elevation direction = SUN_SETTING time_ = self . astral . time_at_elevation_utc ( elevation , direction , date , self . latitude , self . longitude ) if local : return time_ . astimezone ( self . tz ) else : return time_ | Calculate the time when the sun is at the specified elevation . | 163 | 14 |
243,439 | 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 . today ( ) elevation = self . elevation if use_elevation else 0 start , end = self . astral . blue_hour_utc ( direction , date , self . latitude , self . longitude , elevation ) if local : start = start . astimezone ( self . tz ) end = end . astimezone ( self . tz ) return start , end | Returns the start and end times of the Blue Hour when the sun is traversing in the specified direction . | 167 | 21 |
243,440 | 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 . | 63 | 11 |
243,441 | 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 . | 61 | 9 |
243,442 | 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 | 66 | 5 |
243,443 | 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 . | 72 | 14 |
243,444 | 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 ] [ "formatted_address" ] pos = formatted_address . find ( "," ) if pos == - 1 : location . name = formatted_address location . region = "" else : location . name = formatted_address [ : pos ] . strip ( ) location . region = formatted_address [ pos + 1 : ] . strip ( ) geo_location = response [ "results" ] [ 0 ] [ "geometry" ] [ "location" ] location . latitude = float ( geo_location [ "lat" ] ) location . longitude = float ( geo_location [ "lng" ] ) else : raise AstralError ( "GoogleGeocoder: Unable to locate %s. Server Response=%s" % ( key , response [ "status" ] ) ) | Lookup the Google geocoding API information for key | 263 | 11 |
243,445 | 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 . timezone = response [ "timeZoneId" ] else : location . timezone = "UTC" | Query the timezone information with the latitude and longitude of the specified location . | 122 | 16 |
243,446 | 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 ( float ( response [ "results" ] [ 0 ] [ "elevation" ] ) ) else : location . elevation = 0 | Query the elevation information with the latitude and longitude of the specified location . | 126 | 15 |
243,447 | 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 , longitude ) sunset = self . sunset_utc ( date , latitude , longitude , observer_elevation = observer_elevation ) dusk = self . dusk_utc ( date , latitude , longitude , observer_elevation = observer_elevation ) return { "dawn" : dawn , "sunrise" : sunrise , "noon" : noon , "sunset" : sunset , "dusk" : dusk , } | Calculate all the info for the sun at once . All times are returned in the UTC timezone . | 189 | 22 |
243,448 | 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 ] == "math domain error" : raise AstralError ( ( "Sun never reaches %d degrees below the horizon, " "at this location." ) % ( depression - 90 ) ) else : raise | Calculate dawn time in the UTC timezone . | 128 | 11 |
243,449 | 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 this day, " "at this location." ) ) else : raise | Calculate sunrise time in the UTC timezone . | 106 | 11 |
243,450 | 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 ) * 60 ) if second > 59 : second -= 60 minute += 1 elif second < 0 : second += 60 minute -= 1 if minute > 59 : minute -= 60 hour += 1 elif minute < 0 : minute += 60 hour -= 1 if hour > 23 : hour -= 24 date += datetime . timedelta ( days = 1 ) elif hour < 0 : hour += 24 date -= datetime . timedelta ( days = 1 ) noon = datetime . datetime ( date . year , date . month , date . day , hour , minute , second ) noon = pytz . UTC . localize ( noon ) # pylint: disable=E1120 return noon | Calculate solar noon time in the UTC timezone . | 256 | 12 |
243,451 | 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 this day, " "at this location." ) ) else : raise | Calculate sunset time in the UTC timezone . | 105 | 11 |
243,452 | 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 [ 0 ] == "math domain error" : raise AstralError ( ( "Sun never reaches %d degrees below the horizon, " "at this location." ) % ( depression - 90 ) ) else : raise | Calculate dusk time in the UTC timezone . | 127 | 11 |
243,453 | 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 - hour ) * 60 ) second = int ( ( ( ( timeUTC - hour ) * 60 ) - minute ) * 60 ) if second > 59 : second -= 60 minute += 1 elif second < 0 : second += 60 minute -= 1 if minute > 59 : minute -= 60 hour += 1 elif minute < 0 : minute += 60 hour -= 1 if hour < 0 : hour += 24 date -= datetime . timedelta ( days = 1 ) midnight = datetime . datetime ( date . year , date . month , date . day , hour , minute , second ) midnight = pytz . UTC . localize ( midnight ) # pylint: disable=E1120 return midnight | Calculate solar midnight time in the UTC timezone . | 259 | 12 |
243,454 | 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 . | 72 | 14 |
243,455 | 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 . | 90 | 14 |
243,456 | 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 , latitude , longitude , observer_elevation ) if direction == SUN_RISING : return start , end else : return end , start | Returns the start and end times of the Blue Hour in the UTC timezone when the sun is traversing in the specified direction . | 128 | 26 |
243,457 | 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_elevation ) except ValueError as exc : if exc . args [ 0 ] == "math domain error" : raise AstralError ( ( "Sun never reaches an elevation of %d degrees" "at this location." ) % elevation ) else : raise | Calculate the time in the UTC timezone when the sun is at the specified elevation on the specified date . | 135 | 23 |
243,458 | 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 . astimezone ( pytz . utc ) timenow = ( utc_datetime . hour + ( utc_datetime . minute / 60.0 ) + ( utc_datetime . second / 3600.0 ) ) JD = self . _julianday ( dateandtime ) t = self . _jday_to_jcentury ( JD + timenow / 24.0 ) theta = self . _sun_declination ( t ) eqtime = self . _eq_of_time ( t ) solarDec = theta # in degrees solarTimeFix = eqtime - ( 4.0 * - longitude ) + ( 60 * zone ) trueSolarTime = ( dateandtime . hour * 60.0 + dateandtime . minute + dateandtime . second / 60.0 + solarTimeFix ) # in minutes while trueSolarTime > 1440 : trueSolarTime = trueSolarTime - 1440 hourangle = trueSolarTime / 4.0 - 180.0 # Thanks to Louis Schwarzmayr for the next line: if hourangle < - 180 : hourangle = hourangle + 360.0 harad = radians ( hourangle ) csz = sin ( radians ( latitude ) ) * sin ( radians ( solarDec ) ) + cos ( radians ( latitude ) ) * cos ( radians ( solarDec ) ) * cos ( harad ) if csz > 1.0 : csz = 1.0 elif csz < - 1.0 : csz = - 1.0 zenith = degrees ( acos ( csz ) ) azDenom = cos ( radians ( latitude ) ) * sin ( radians ( zenith ) ) if abs ( azDenom ) > 0.001 : azRad = ( ( sin ( radians ( latitude ) ) * cos ( radians ( zenith ) ) ) - sin ( radians ( solarDec ) ) ) / azDenom if abs ( azRad ) > 1.0 : if azRad < 0 : azRad = - 1.0 else : azRad = 1.0 azimuth = 180.0 - degrees ( acos ( azRad ) ) if hourangle > 0.0 : azimuth = - azimuth else : if latitude > 0.0 : azimuth = 180.0 else : azimuth = 0.0 if azimuth < 0.0 : azimuth = azimuth + 360.0 return azimuth | Calculate the azimuth angle of the sun . | 634 | 12 |
243,459 | def solar_zenith ( self , dateandtime , latitude , longitude ) : return 90.0 - self . solar_elevation ( dateandtime , latitude , longitude ) | Calculates the solar zenith angle . | 40 | 10 |
243,460 | 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 . | 65 | 13 |
243,461 | 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 = datetime . timedelta ( seconds = ( sunset - sunrise ) . seconds / 8 ) # Mo,Sa,Fr,We,Th,Tu,Su octant_index = [ 1 , 6 , 4 , 5 , 3 , 2 , 7 ] weekday = date . weekday ( ) octant = octant_index [ weekday ] start = sunrise + ( octant_duration * octant ) end = start + octant_duration return start , end | Calculate ruhakaalam times in the UTC timezone . | 185 | 14 |
243,462 | def _depression_adjustment ( self , elevation ) : if elevation <= 0 : return 0 r = 6356900 # radius of the earth 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 . | 118 | 15 |
243,463 | 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 == 'success' : assert isinstance ( job , Job ) assert exception is None assert stacktrace is None elif status == 'timeout' : assert isinstance ( job , Job ) assert result is None assert exception is None assert stacktrace is None elif status == 'failure' : assert isinstance ( job , Job ) assert result is None assert exception is not None assert stacktrace is not None | Example callback function . | 157 | 4 |
243,464 | 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 exception: {}' . format ( e ) ) | Execute the callback . | 93 | 5 |
243,465 | 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 as err : self . _logger . exception ( 'Job was invalid: {}' . format ( err ) ) self . _execute_callback ( 'invalid' , msg , None , None , None , None ) else : self . _logger . info ( 'Executing job {}: {}' . format ( job . id , job_repr ) ) if job . timeout : timer = threading . Timer ( job . timeout , _thread . interrupt_main ) timer . start ( ) else : timer = None try : res = job . func ( * job . args , * * job . kwargs ) except KeyboardInterrupt : self . _logger . error ( 'Job {} timed out or was interrupted' . format ( job . id ) ) self . _execute_callback ( 'timeout' , msg , job , None , None , None ) except Exception as err : self . _logger . exception ( 'Job {} raised an exception:' . format ( job . id ) ) tb = traceback . format_exc ( ) self . _execute_callback ( 'failure' , msg , job , None , err , tb ) else : self . _logger . info ( 'Job {} returned: {}' . format ( job . id , res ) ) self . _execute_callback ( 'success' , msg , job , res , None , None ) finally : if timer is not None : timer . cancel ( ) | De - serialize the message and execute the job . | 403 | 11 |
243,466 | 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 ) message = Message ( topic = record . topic , partition = record . partition , offset = record . offset , key = record . key , value = record . value ) self . _process_message ( message ) if commit_offsets : self . _consumer . commit ( ) messages_processed += 1 return messages_processed | Start processing Kafka messages and executing jobs . | 157 | 8 |
243,467 | def get_call_repr ( func , * args , * * kwargs ) : # Functions, builtins and methods if ismethod ( func ) or isfunction ( func ) or isbuiltin ( func ) : func_repr = '{}.{}' . format ( func . __module__ , func . __qualname__ ) # A callable class instance elif not isclass ( func ) and hasattr ( func , '__call__' ) : func_repr = '{}.{}' . format ( func . __module__ , func . __class__ . __name__ ) else : func_repr = repr ( func ) args_reprs = [ repr ( arg ) for arg in args ] kwargs_reprs = [ k + '=' + repr ( v ) for k , v in sorted ( kwargs . items ( ) ) ] return '{}({})' . format ( func_repr , ', ' . join ( args_reprs + kwargs_reprs ) ) | Return the string representation of the function call . | 227 | 9 |
243,468 | 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 . | 72 | 11 |
243,469 | def send ( instructions , printer_identifier = None , backend_identifier = None , blocking = True ) : status = { 'instructions_sent' : True , # The instructions were sent to the printer. 'outcome' : 'unknown' , # String description of the outcome of the sending operation like: 'unknown', 'sent', 'printed', 'error' 'printer_state' : None , # If the selected backend supports reading back the printer state, this key will contain it. 'did_print' : False , # If True, a print was produced. It defaults to False if the outcome is uncertain (due to a backend without read-back capability). 'ready_for_next_job' : False , # If True, the printer is ready to receive the next instructions. It defaults to False if the state is unknown. } selected_backend = None if backend_identifier : selected_backend = backend_identifier else : try : selected_backend = guess_backend ( printer_identifier ) except : logger . info ( "No backend stated. Selecting the default linux_kernel backend." ) selected_backend = 'linux_kernel' be = backend_factory ( selected_backend ) list_available_devices = be [ 'list_available_devices' ] BrotherQLBackend = be [ 'backend_class' ] printer = BrotherQLBackend ( printer_identifier ) start = time . time ( ) logger . info ( 'Sending instructions to the printer. Total: %d bytes.' , len ( instructions ) ) printer . write ( instructions ) status [ 'outcome' ] = 'sent' if not blocking : return status if selected_backend == 'network' : """ No need to wait for completion. The network backend doesn't support readback. """ return status while time . time ( ) - start < 10 : data = printer . read ( ) if not data : time . sleep ( 0.005 ) continue try : result = interpret_response ( data ) except ValueError : logger . error ( "TIME %.3f - Couln't understand response: %s" , time . time ( ) - start , data ) continue status [ 'printer_state' ] = result logger . debug ( 'TIME %.3f - result: %s' , time . time ( ) - start , result ) if result [ 'errors' ] : logger . error ( 'Errors occured: %s' , result [ 'errors' ] ) status [ 'outcome' ] = 'error' break if result [ 'status_type' ] == 'Printing completed' : status [ 'did_print' ] = True status [ 'outcome' ] = 'printed' if result [ 'status_type' ] == 'Phase change' and result [ 'phase_type' ] == 'Waiting to receive' : status [ 'ready_for_next_job' ] = True if status [ 'did_print' ] and status [ 'ready_for_next_job' ] : break if not status [ 'did_print' ] : logger . warning ( "'printing completed' status not received." ) if not status [ 'ready_for_next_job' ] : logger . warning ( "'waiting to receive' status not received." ) if ( not status [ 'did_print' ] ) or ( not status [ 'ready_for_next_job' ] ) : logger . warning ( 'Printing potentially not successful?' ) if status [ 'did_print' ] and status [ 'ready_for_next_job' ] : logger . info ( "Printing was successful. Waiting for the next job." ) return status | Send instruction bytes to a printer . | 789 | 7 |
243,470 | 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' : instruction_buffer += instruction elif join_raster and 'raster' in OPCODES [ opcode ] [ 0 ] and 'raster' in last_opcode : instruction_buffer += instruction else : if instruction_buffer : new_instructions . append ( instruction_buffer ) instruction_buffer = instruction last_opcode = OPCODES [ opcode ] [ 0 ] if instruction_buffer : new_instructions . append ( instruction_buffer ) return new_instructions | Process a list of instructions by merging subsequent instuctions with identical opcodes into large instructions . | 205 | 18 |
243,471 | def cli ( ctx , * args , * * kwargs ) : backend = kwargs . get ( 'backend' , None ) model = kwargs . get ( 'model' , None ) printer = kwargs . get ( 'printer' , None ) debug = kwargs . get ( 'debug' ) # Store the general CLI options in the context meta dictionary. # The name corresponds to the second half of the respective envvar: ctx . meta [ 'MODEL' ] = model ctx . meta [ 'BACKEND' ] = backend ctx . meta [ 'PRINTER' ] = printer logging . basicConfig ( level = 'DEBUG' if debug else 'INFO' ) | Command line interface for the brother_ql Python package . | 152 | 11 |
243,472 | 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" ) # computer print ( "About the computer:" ) for attr in ( 'platform' , 'processor' , 'release' , 'system' , 'machine' , 'architecture' ) : print ( ' * ' + attr . title ( ) + ':' , getattr ( platform , attr ) ( ) ) # Python print ( "About the installed Python version:" ) py_version = str ( sys . version ) . replace ( '\n' , ' ' ) print ( " *" , py_version ) # brother_ql print ( "About the brother_ql package:" ) pkg = get_distribution ( 'brother_ql' ) print ( " * package location:" , pkg . location ) print ( " * package version: " , pkg . version ) try : cli_loc = shutil . which ( 'brother_ql' ) except : cli_loc = 'unknown' print ( " * brother_ql CLI path:" , cli_loc ) # brother_ql's requirements print ( "About the requirements of brother_ql:" ) fmt = " {req:14s} | {spec:10s} | {ins_vers:17s}" print ( fmt . format ( req = 'requirement' , spec = 'requested' , ins_vers = 'installed version' ) ) print ( fmt . format ( req = '-' * 14 , spec = '-' * 10 , ins_vers = '-' * 17 ) ) requirements = list ( pkg . requires ( ) ) requirements . sort ( key = lambda x : x . project_name ) for req in requirements : proj = req . project_name req_pkg = get_distribution ( proj ) spec = ' ' . join ( req . specs [ 0 ] ) if req . specs else 'any' print ( fmt . format ( req = proj , spec = spec , ins_vers = req_pkg . version ) ) print ( "\n##################\n" ) | print debug info about running environment | 503 | 6 |
243,473 | 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 = BrotherQLRaster ( model ) qlr . exception_on_warning = True kwargs [ 'cut' ] = not kwargs [ 'no_cut' ] del kwargs [ 'no_cut' ] instructions = convert ( qlr = qlr , * * kwargs ) send ( instructions = instructions , printer_identifier = printer , backend_identifier = backend , blocking = True ) | Print a label of the provided IMAGE . | 187 | 9 |
243,474 | def list_available_devices ( ) : class find_class ( object ) : def __init__ ( self , class_ ) : self . _class = class_ def __call__ ( self , device ) : # first, let's check the device if device . bDeviceClass == self . _class : return True # ok, transverse all devices to find an interface that matches our class for cfg in device : # find_descriptor: what's it? intf = usb . util . find_descriptor ( cfg , bInterfaceClass = self . _class ) if intf is not None : return True return False # only Brother printers printers = usb . core . find ( find_all = 1 , custom_match = find_class ( 7 ) , idVendor = 0x04f9 ) def identifier ( dev ) : try : serial = usb . util . get_string ( dev , 256 , dev . iSerialNumber ) return 'usb://0x{:04x}:0x{:04x}_{}' . format ( dev . idVendor , dev . idProduct , serial ) except : return 'usb://0x{:04x}:0x{:04x}' . format ( dev . idVendor , dev . idProduct ) return [ { 'identifier' : identifier ( printer ) , 'instance' : printer } for printer in printers ] | List all available devices for the respective backend | 298 | 8 |
243,475 | 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_ql . labels import LabelsManager lm = LabelsManager ( ) label_sizes = list ( lm . iter_identifiers ( ) ) for label in lm . iter_elements ( ) : l = { } l [ 'name' ] = label . name l [ 'kind' ] = label . form_factor l [ 'color' ] = label . color l [ 'tape_size' ] = label . tape_size l [ 'dots_total' ] = label . dots_total l [ 'dots_printable' ] = label . dots_printable l [ 'right_margin_dots' ] = label . offset_r l [ 'feed_margin' ] = label . feed_margin l [ 'restrict_printers' ] = label . restricted_to_models label_type_specs [ label . identifier ] = l | We contain this code inside a function so that the imports we do in here are not visible at the module level . | 307 | 23 |
243,476 | def guess_backend ( identifier ) : if identifier . startswith ( 'usb://' ) or identifier . startswith ( '0x' ) : return 'pyusb' elif identifier . startswith ( 'file://' ) or identifier . startswith ( '/dev/usb/' ) or identifier . startswith ( 'lp' ) : return 'linux_kernel' elif identifier . startswith ( 'tcp://' ) : return 'network' else : raise ValueError ( 'Cannot guess backend for given identifier: %s' % identifier ) | guess the backend from a given identifier string for the device | 124 | 12 |
243,477 | def featured_event_query ( self , * * kwargs ) : if not kwargs . get ( 'location' ) and ( not kwargs . get ( 'latitude' ) or not kwargs . get ( 'longitude' ) ) : raise ValueError ( 'A valid location (parameter "location") or latitude/longitude combination ' '(parameters "latitude" and "longitude") must be provided.' ) return self . _query ( FEATURED_EVENT_API_URL , * * kwargs ) | Query the Yelp Featured Event API . | 119 | 7 |
243,478 | def _get_clean_parameters ( kwargs ) : return dict ( ( k , v ) for k , v in kwargs . items ( ) if v is not None ) | Clean the parameters by filtering out any parameters that have a None value . | 40 | 14 |
243,479 | def _query ( self , url , * * kwargs ) : parameters = YelpAPI . _get_clean_parameters ( kwargs ) response = self . _yelp_session . get ( url , headers = self . _headers , params = parameters , timeout = self . _timeout_s , ) response_json = response . json ( ) # shouldn't happen, but this will raise a ValueError if the response isn't JSON # Yelp can return one of many different API errors, so check for one of them. # The Yelp Fusion API does not yet have a complete list of errors, but this is on the TODO list; see # https://github.com/Yelp/yelp-fusion/issues/95 for more info. if 'error' in response_json : raise YelpAPI . YelpAPIError ( '{}: {}' . format ( response_json [ 'error' ] [ 'code' ] , response_json [ 'error' ] [ 'description' ] ) ) # we got a good response, so return return response_json | All query methods have the same logic so don t repeat it! Query the URL parse the response as JSON and check for errors . If all goes well return the parsed JSON . | 230 | 35 |
243,480 | def url_join ( base , * args ) : scheme , netloc , path , query , fragment = urlsplit ( base ) path = path if len ( path ) else "/" path = posixpath . join ( path , * [ ( '%s' % x ) for x in args ] ) return urlunsplit ( [ scheme , netloc , path , query , fragment ] ) | Helper function to join an arbitrary number of url segments together . | 85 | 12 |
243,481 | def probe_to_graphsrv ( probe ) : config = probe . config # manual group set up via `group` config key if "group" in config : source , group = config [ "group" ] . split ( "." ) group_field = config . get ( "group_field" , "host" ) group_value = config [ group_field ] graphsrv . group . add ( source , group , { group_value : { group_field : group_value } } , * * config ) return # automatic group setup for fping # FIXME: this should be somehow more dynamic for k , v in list ( config . items ( ) ) : if isinstance ( v , dict ) and "hosts" in v : r = { } for host in v . get ( "hosts" ) : if isinstance ( host , dict ) : r [ host [ "host" ] ] = host else : r [ host ] = { "host" : host } graphsrv . group . add ( probe . name , k , r , * * v ) | takes a probe instance and generates a graphsrv data group for it using the probe s config | 230 | 20 |
243,482 | def new_message ( self ) : msg = { } msg [ 'data' ] = [ ] msg [ 'type' ] = self . plugin_type msg [ 'source' ] = self . name msg [ 'ts' ] = ( datetime . datetime . utcnow ( ) - datetime . datetime ( 1970 , 1 , 1 ) ) . total_seconds ( ) return msg | creates a new message setting type source ts data - data is initialized to an empty array | 84 | 18 |
243,483 | def popen ( self , args , * * kwargs ) : self . log . debug ( "popen %s" , ' ' . join ( args ) ) return vaping . io . subprocess . Popen ( args , * * kwargs ) | creates a subprocess with passed args | 55 | 8 |
243,484 | def queue_emission ( self , msg ) : if not msg : return for _emitter in self . _emit : if not hasattr ( _emitter , 'emit' ) : continue def emit ( emitter = _emitter ) : self . log . debug ( "emit to {}" . format ( emitter . name ) ) emitter . emit ( msg ) self . log . debug ( "queue emission to {} ({})" . format ( _emitter . name , self . _emit_queue . qsize ( ) ) ) self . _emit_queue . put ( emit ) | queue an emission of a message for all output plugins | 131 | 10 |
243,485 | def send_emission ( self ) : if self . _emit_queue . empty ( ) : return emit = self . _emit_queue . get ( ) emit ( ) | emit and remove the first emission in the queue | 39 | 10 |
243,486 | def validate_file_handler ( self ) : if self . fh . closed : try : self . fh = open ( self . path , "r" ) self . fh . seek ( 0 , 2 ) except OSError as err : logging . error ( "Could not reopen file: {}" . format ( err ) ) return False open_stat = os . fstat ( self . fh . fileno ( ) ) try : file_stat = os . stat ( self . path ) except OSError as err : logging . error ( "Could not stat file: {}" . format ( err ) ) return False if open_stat != file_stat : self . log self . fh . close ( ) return False return True | Here we validate that our filehandler is pointing to an existing file . | 159 | 14 |
243,487 | def probe ( self ) : # make sure the filehandler is still valid # (e.g. file stat hasnt changed, file exists etc.) if not self . validate_file_handler ( ) : return [ ] messages = [ ] # read any new lines and push them onto the stack for line in self . fh . readlines ( self . max_lines ) : data = { "path" : self . path } msg = self . new_message ( ) # process the line - this is where parsing happens parsed = self . process_line ( line , data ) if not parsed : continue data . update ( parsed ) # process the probe - this is where data assignment # happens data = self . process_probe ( data ) msg [ "data" ] = [ data ] messages . append ( msg ) # process all new messages before returning them # for emission messages = self . process_messages ( messages ) return messages | Probe the file for new lines | 195 | 7 |
243,488 | def filename_formatters ( self , data , row ) : r = { "source" : data . get ( "source" ) , "field" : self . field , "type" : data . get ( "type" ) } r . update ( * * row ) return r | Returns a dict containing the various filename formatter values | 60 | 10 |
243,489 | def format_filename ( self , data , row ) : return self . filename . format ( * * self . filename_formatters ( data , row ) ) | Returns a formatted filename using the template stored in self . filename | 33 | 12 |
243,490 | def emit ( self , message ) : # handle vaping data that arrives in a list if isinstance ( message . get ( "data" ) , list ) : for row in message . get ( "data" ) : # format filename from data filename = self . format_filename ( message , row ) # create database file if it does not exist yet if not os . path . exists ( filename ) : self . create ( filename ) # update database self . log . debug ( "storing time:%d, %s:%.5f in %s" % ( message . get ( "ts" ) , self . field , row . get ( self . field ) , filename ) ) self . update ( filename , message . get ( "ts" ) , row . get ( self . field ) ) | emit to database | 167 | 4 |
243,491 | def parse_interval ( val ) : re_intv = re . compile ( r"([\d\.]+)([a-zA-Z]+)" ) val = val . strip ( ) total = 0.0 for match in re_intv . findall ( val ) : unit = match [ 1 ] count = float ( match [ 0 ] ) if unit == 's' : total += count elif unit == 'm' : total += count * 60 elif unit == 'ms' : total += count / 1000 elif unit == "h" : total += count * 3600 elif unit == 'd' : total += count * 86400 else : raise ValueError ( "unknown unit from interval string '%s'" % val ) return total | converts a string to float of seconds . 5 = 500ms 90 = 1m30s | 164 | 19 |
243,492 | def hosts_args ( self ) : host_args = [ ] for row in self . hosts : if isinstance ( row , dict ) : host_args . append ( row [ "host" ] ) else : host_args . append ( row ) # using a set changes the order dedupe = list ( ) for each in host_args : if each not in dedupe : dedupe . append ( each ) return dedupe | hosts list can contain strings specifying a host directly or dicts containing a host key to specify the host | 90 | 21 |
243,493 | def parse_verbose ( self , line ) : try : logging . debug ( line ) ( host , pings ) = line . split ( ' : ' ) cnt = 0 lost = 0 times = [ ] pings = pings . strip ( ) . split ( ' ' ) cnt = len ( pings ) for latency in pings : if latency == '-' : continue times . append ( float ( latency ) ) lost = cnt - len ( times ) if lost : loss = lost / float ( cnt ) else : loss = 0.0 rv = { 'host' : host . strip ( ) , 'cnt' : cnt , 'loss' : loss , 'data' : times , } if times : rv [ 'min' ] = min ( times ) rv [ 'max' ] = max ( times ) rv [ 'avg' ] = sum ( times ) / len ( times ) rv [ 'last' ] = times [ - 1 ] return rv except Exception as e : logging . error ( "failed to get data: {}" . format ( e ) ) | parse output from verbose format | 237 | 6 |
243,494 | def start ( ctx , * * kwargs ) : update_context ( ctx , kwargs ) daemon = mk_daemon ( ctx ) if ctx . debug or kwargs [ 'no_fork' ] : daemon . run ( ) else : daemon . start ( ) | start a vaping process | 63 | 4 |
243,495 | def stop ( ctx , * * kwargs ) : update_context ( ctx , kwargs ) daemon = mk_daemon ( ctx ) daemon . stop ( ) | stop a vaping process | 39 | 4 |
243,496 | def restart ( ctx , * * kwargs ) : update_context ( ctx , kwargs ) daemon = mk_daemon ( ctx ) daemon . stop ( ) daemon . start ( ) | restart a vaping process | 44 | 5 |
243,497 | def render_content ( self , request ) : context = self . data . copy ( ) context . update ( self . render_vars ( request ) ) return render ( self . template , request . app , context , request = request ) | Return a string containing the HTML to be rendered for the panel . | 50 | 13 |
243,498 | def inject ( self , request , response ) : # called in host app if not isinstance ( response , Response ) : return settings = request . app [ APP_KEY ] [ 'settings' ] response_html = response . body route = request . app . router [ 'debugtoolbar.request' ] toolbar_url = route . url_for ( request_id = request [ 'id' ] ) button_style = settings [ 'button_style' ] css_path = request . app . router [ STATIC_ROUTE_NAME ] . url_for ( filename = 'css/toolbar_button.css' ) toolbar_css = toolbar_css_template % { 'css_path' : css_path } toolbar_html = toolbar_html_template % { 'button_style' : button_style , 'css_path' : css_path , 'toolbar_url' : toolbar_url } toolbar_html = toolbar_html . encode ( response . charset or 'utf-8' ) toolbar_css = toolbar_css . encode ( response . charset or 'utf-8' ) response_html = replace_insensitive ( response_html , b'</head>' , toolbar_css + b'</head>' ) response . body = replace_insensitive ( response_html , b'</body>' , toolbar_html + b'</body>' ) | Inject the debug toolbar iframe into an HTML response . | 304 | 12 |
243,499 | def common_segment_count ( path , value ) : i = 0 if len ( path ) <= len ( value ) : for x1 , x2 in zip ( path , value ) : if x1 == x2 : i += 1 else : return 0 return i | Return the number of path segments common to both | 57 | 9 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.