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,300 | def meaning ( phrase , source_lang = "en" , dest_lang = "en" , format = "json" ) : base_url = Vocabulary . __get_api_link ( "glosbe" ) url = base_url . format ( word = phrase , source_lang = source_lang , dest_lang = dest_lang ) json_obj = Vocabulary . __return_json ( url ) if json_obj : try : tuc_content = json_obj [ "tuc" ] # "tuc_content" is a "list" except KeyError : return False '''get meanings''' meanings_list = Vocabulary . __parse_content ( tuc_content , "meanings" ) return Response ( ) . respond ( meanings_list , format ) # print(meanings_list) # return json.dumps(meanings_list) else : return False | make calls to the glosbe API | 194 | 8 |
243,301 | def part_of_speech ( phrase , format = 'json' ) : # We get a list object as a return value from the Wordnik API base_url = Vocabulary . __get_api_link ( "wordnik" ) url = base_url . format ( word = phrase . lower ( ) , action = "definitions" ) json_obj = Vocabulary . __return_json ( url ) if not json_obj : return False result = [ ] for idx , obj in enumerate ( json_obj ) : text = obj . get ( 'partOfSpeech' , None ) example = obj . get ( 'text' , None ) result . append ( { "seq" : idx , "text" : text , "example" : example } ) return Response ( ) . respond ( result , format ) | querrying Wordnik s API for knowing whether the word is a noun adjective and the like | 176 | 19 |
243,302 | def usage_example ( phrase , format = 'json' ) : base_url = Vocabulary . __get_api_link ( "urbandict" ) url = base_url . format ( action = "define" , word = phrase ) word_examples = { } json_obj = Vocabulary . __return_json ( url ) if json_obj : examples_list = json_obj [ "list" ] for i , example in enumerate ( examples_list ) : if example [ "thumbs_up" ] > example [ "thumbs_down" ] : word_examples [ i ] = example [ "example" ] . replace ( "\r" , "" ) . replace ( "\n" , "" ) if word_examples : # reforamatting "word_examples" using "__clean_dict()" # return json.dumps(Vocabulary.__clean_dict(word_examples)) # return Vocabulary.__clean_dict(word_examples) return Response ( ) . respond ( Vocabulary . __clean_dict ( word_examples ) , format ) else : return False else : return False | Takes the source phrase and queries it to the urbandictionary API | 249 | 14 |
243,303 | def pronunciation ( phrase , format = 'json' ) : base_url = Vocabulary . __get_api_link ( "wordnik" ) url = base_url . format ( word = phrase . lower ( ) , action = "pronunciations" ) json_obj = Vocabulary . __return_json ( url ) if json_obj : ''' Refer : http://stackoverflow.com/q/18337407/3834059 ''' ## TODO: Fix the unicode issue mentioned in ## https://github.com/tasdikrahman/vocabulary#181known-issues for idx , obj in enumerate ( json_obj ) : obj [ 'seq' ] = idx if sys . version_info [ : 2 ] <= ( 2 , 7 ) : ## python2 # return json_obj return Response ( ) . respond ( json_obj , format ) else : # python3 # return json.loads(json.dumps(json_obj, ensure_ascii=False)) return Response ( ) . respond ( json_obj , format ) else : return False | Gets the pronunciation from the Wordnik API | 235 | 9 |
243,304 | def hyphenation ( phrase , format = 'json' ) : base_url = Vocabulary . __get_api_link ( "wordnik" ) url = base_url . format ( word = phrase . lower ( ) , action = "hyphenation" ) json_obj = Vocabulary . __return_json ( url ) if json_obj : # return json.dumps(json_obj) # return json_obj return Response ( ) . respond ( json_obj , format ) else : return False | Returns back the stress points in the phrase passed | 109 | 9 |
243,305 | def __respond_with_dict ( self , data ) : response = { } if isinstance ( data , list ) : temp_data , data = data , { } for key , value in enumerate ( temp_data ) : data [ key ] = value data . pop ( 'seq' , None ) for index , item in data . items ( ) : values = item if isinstance ( item , list ) or isinstance ( item , dict ) : values = self . __respond_with_dict ( item ) if isinstance ( values , dict ) and len ( values ) == 1 : ( key , values ) , = values . items ( ) response [ index ] = values return response | Builds a python dictionary from a json object | 145 | 9 |
243,306 | def __respond_with_list ( self , data ) : response = [ ] if isinstance ( data , dict ) : data . pop ( 'seq' , None ) data = list ( data . values ( ) ) for item in data : values = item if isinstance ( item , list ) or isinstance ( item , dict ) : values = self . __respond_with_list ( item ) if isinstance ( values , list ) and len ( values ) == 1 : response . extend ( values ) else : response . append ( values ) return response | Builds a python list from a json object | 116 | 9 |
243,307 | def respond ( self , data , format = 'json' ) : dispatchers = { "dict" : self . __respond_with_dict , "list" : self . __respond_with_list } if not dispatchers . get ( format , False ) : return json . dumps ( data ) return dispatchers [ format ] ( data ) | Converts a json object to a python datastructure based on specified format | 75 | 15 |
243,308 | def get_todos ( self ) : if self . is_expression : self . get_todos_from_expr ( ) else : if self . last_argument : numbers = self . args [ : - 1 ] else : numbers = self . args for number in numbers : try : self . todos . append ( self . todolist . todo ( number ) ) except InvalidTodoException : self . invalid_numbers . append ( number ) | Gets todo objects from supplied todo IDs . | 100 | 11 |
243,309 | def _markup ( p_todo , p_focus ) : pri = p_todo . priority ( ) pri = 'pri_' + pri if pri else PaletteItem . DEFAULT if not p_focus : attr_dict = { None : pri } else : # use '_focus' palette entries instead of standard ones attr_dict = { None : pri + '_focus' } attr_dict [ PaletteItem . PROJECT ] = PaletteItem . PROJECT_FOCUS attr_dict [ PaletteItem . CONTEXT ] = PaletteItem . CONTEXT_FOCUS attr_dict [ PaletteItem . METADATA ] = PaletteItem . METADATA_FOCUS attr_dict [ PaletteItem . LINK ] = PaletteItem . LINK_FOCUS return attr_dict | Returns an attribute spec for the colors that correspond to the given todo item . | 184 | 16 |
243,310 | def create ( p_class , p_todo , p_id_width = 4 ) : def parent_progress_may_have_changed ( p_todo ) : """ Returns True when a todo's progress should be updated because it is dependent on the parent's progress. """ return p_todo . has_tag ( 'p' ) and not p_todo . has_tag ( 'due' ) source = p_todo . source ( ) if source in p_class . cache : widget = p_class . cache [ source ] if p_todo is not widget . todo : # same source text but different todo instance (could happen # after an edit where a new Todo instance is created with the # same text as before) # simply fix the reference in the stored widget. widget . todo = p_todo if parent_progress_may_have_changed ( p_todo ) : widget . update_progress ( ) else : widget = p_class ( p_todo , p_id_width ) p_class . cache [ source ] = widget return widget | Creates a TodoWidget instance for the given todo . Widgets are cached the same object is returned for the same todo item . | 237 | 29 |
243,311 | def _complete ( self ) : def find_word_start ( p_text , p_pos ) : """ Returns position of the beginning of a word ending in p_pos. """ return p_text . lstrip ( ) . rfind ( ' ' , 0 , p_pos ) + 1 def get_word_before_pos ( p_text , p_pos ) : start = find_word_start ( p_text , p_pos ) return ( p_text [ start : p_pos ] , start ) pos = self . edit_pos text = self . edit_text completer = self . completer word_before_cursor , start = get_word_before_pos ( text , pos ) completions = completer . get_completions ( word_before_cursor , start == 0 ) # store slices before and after place for completion self . _surrounding_text = ( text [ : start ] , text [ pos : ] ) single_completion = len ( completions ) == 1 completion_done = single_completion and completions [ 0 ] == word_before_cursor if completion_done or not completions : self . completion_mode = False return elif single_completion : replacement = completions [ 0 ] else : replacement = commonprefix ( completions ) zero_candidate = replacement if replacement else word_before_cursor if zero_candidate != completions [ 0 ] : completions . insert ( 0 , zero_candidate ) self . completion_box . add_completions ( completions ) self . insert_completion ( replacement ) self . completion_mode = not single_completion | Main completion function . | 356 | 4 |
243,312 | def _home_del ( self ) : text = self . edit_text [ self . edit_pos : ] self . set_edit_text ( text ) self . _home ( ) | Deletes the line content before the cursor | 40 | 8 |
243,313 | def _end_del ( self ) : text = self . edit_text [ : self . edit_pos ] self . set_edit_text ( text ) | Deletes the line content after the cursor | 34 | 8 |
243,314 | def add_edge ( self , p_from , p_to , p_id = None ) : if not self . has_edge ( p_from , p_to ) : if not self . has_node ( p_from ) : self . add_node ( p_from ) if not self . has_node ( p_to ) : self . add_node ( p_to ) self . _edges [ p_from ] . add ( p_to ) self . _edge_numbers [ ( p_from , p_to ) ] = p_id | Adds an edge to the graph . The nodes will be added if they don t exist . | 124 | 18 |
243,315 | def reachable_nodes ( self , p_id , p_recursive = True , p_reverse = False ) : stack = [ p_id ] visited = set ( ) result = set ( ) while len ( stack ) : current = stack . pop ( ) if current in visited or current not in self . _edges : continue visited . add ( current ) if p_reverse : parents = [ node for node , neighbors in self . _edges . items ( ) if current in neighbors ] stack = stack + parents result = result . union ( parents ) else : stack = stack + list ( self . _edges [ current ] ) result = result . union ( self . _edges [ current ] ) if not p_recursive : break return result | Returns the set of all neighbors that the given node can reach . | 161 | 13 |
243,316 | def reachable_nodes_reverse ( self , p_id , p_recursive = True ) : return self . reachable_nodes ( p_id , p_recursive , True ) | Find neighbors in the inverse graph . | 43 | 7 |
243,317 | def remove_node ( self , p_id , remove_unconnected_nodes = True ) : if self . has_node ( p_id ) : for neighbor in self . incoming_neighbors ( p_id ) : self . _edges [ neighbor ] . remove ( p_id ) neighbors = set ( ) if remove_unconnected_nodes : neighbors = self . outgoing_neighbors ( p_id ) del self . _edges [ p_id ] for neighbor in neighbors : if self . is_isolated ( neighbor ) : self . remove_node ( neighbor ) | Removes a node from the graph . | 128 | 8 |
243,318 | def is_isolated ( self , p_id ) : return ( len ( self . incoming_neighbors ( p_id ) ) == 0 and len ( self . outgoing_neighbors ( p_id ) ) == 0 ) | Returns True iff the given node has no incoming or outgoing edges . | 51 | 14 |
243,319 | def has_edge ( self , p_from , p_to ) : return p_from in self . _edges and p_to in self . _edges [ p_from ] | Returns True when the graph has the given edge . | 41 | 10 |
243,320 | def remove_edge ( self , p_from , p_to , p_remove_unconnected_nodes = True ) : if self . has_edge ( p_from , p_to ) : self . _edges [ p_from ] . remove ( p_to ) try : del self . _edge_numbers [ ( p_from , p_to ) ] except KeyError : return None if p_remove_unconnected_nodes : if self . is_isolated ( p_from ) : self . remove_node ( p_from ) if self . is_isolated ( p_to ) : self . remove_node ( p_to ) | Removes an edge from the graph . | 145 | 8 |
243,321 | def transitively_reduce ( self ) : removals = set ( ) for from_node , neighbors in self . _edges . items ( ) : childpairs = [ ( c1 , c2 ) for c1 in neighbors for c2 in neighbors if c1 != c2 ] for child1 , child2 in childpairs : if self . has_path ( child1 , child2 ) and not self . has_path ( child1 , from_node ) : removals . add ( ( from_node , child2 ) ) for edge in removals : self . remove_edge ( edge [ 0 ] , edge [ 1 ] ) | Performs a transitive reduction on the graph . | 142 | 10 |
243,322 | def dot ( self , p_print_labels = True ) : out = 'digraph g {\n' for from_node , neighbors in sorted ( self . _edges . items ( ) ) : out += " {}\n" . format ( from_node ) for neighbor in sorted ( neighbors ) : out += " {} -> {}" . format ( from_node , neighbor ) edge_id = self . edge_id ( from_node , neighbor ) if edge_id and p_print_labels : out += ' [label="{}"]' . format ( edge_id ) out += "\n" out += '}\n' return out | Prints the graph in Dot format . | 140 | 8 |
243,323 | def _print ( self ) : if self . printer is None : # create a standard printer with some filters indent = config ( ) . list_indent ( ) final_format = ' ' * indent + self . format filters = [ ] filters . append ( PrettyPrinterFormatFilter ( self . todolist , final_format ) ) self . printer = pretty_printer_factory ( self . todolist , filters ) try : if self . group_expression : self . out ( self . printer . print_groups ( self . _view ( ) . groups ) ) else : self . out ( self . printer . print_list ( self . _view ( ) . todos ) ) except ListFormatError : self . error ( 'Error while parsing format string (list_format config' ' option or -F)' ) | Prints the todos in the right format . | 177 | 10 |
243,324 | def parse_line ( p_string ) : result = { 'completed' : False , 'completionDate' : None , 'priority' : None , 'creationDate' : None , 'text' : "" , 'projects' : [ ] , 'contexts' : [ ] , 'tags' : { } , } completed_head = _COMPLETED_HEAD_MATCH . match ( p_string ) normal_head = _NORMAL_HEAD_MATCH . match ( p_string ) rest = p_string if completed_head : result [ 'completed' ] = True completion_date = completed_head . group ( 'completionDate' ) try : result [ 'completionDate' ] = date_string_to_date ( completion_date ) except ValueError : pass creation_date = completed_head . group ( 'creationDate' ) try : result [ 'creationDate' ] = date_string_to_date ( creation_date ) except ValueError : pass rest = completed_head . group ( 'rest' ) elif normal_head : result [ 'priority' ] = normal_head . group ( 'priority' ) creation_date = normal_head . group ( 'creationDate' ) try : result [ 'creationDate' ] = date_string_to_date ( creation_date ) except ValueError : pass rest = normal_head . group ( 'rest' ) for word in rest . split ( ) : project = _PROJECT_MATCH . match ( word ) if project : result [ 'projects' ] . append ( project . group ( 1 ) ) context = _CONTEXT_MATCH . match ( word ) if context : result [ 'contexts' ] . append ( context . group ( 1 ) ) tag = _TAG_MATCH . match ( word ) if tag : tag_name = tag . group ( 'tag' ) tag_value = tag . group ( 'value' ) try : result [ 'tags' ] [ tag_name ] . append ( tag_value ) except KeyError : result [ 'tags' ] [ tag_name ] = [ tag_value ] else : result [ 'text' ] += word + ' ' # strip trailing space from resulting text result [ 'text' ] = result [ 'text' ] [ : - 1 ] return result | Parses a single line as can be encountered in a todo . txt file . First checks whether the standard elements are present such as priority creation date completeness check and the completion date . | 496 | 40 |
243,325 | def _dates ( p_word_before_cursor ) : to_absolute = lambda s : relative_date_to_date ( s ) . isoformat ( ) start_value_pos = p_word_before_cursor . find ( ':' ) + 1 value = p_word_before_cursor [ start_value_pos : ] for reldate in date_suggestions ( ) : if not reldate . startswith ( value ) : continue yield Completion ( reldate , - len ( value ) , display_meta = to_absolute ( reldate ) ) | Generator for date completion . | 129 | 6 |
243,326 | def add_completions ( self , p_completions ) : palette = PaletteItem . MARKED for completion in p_completions : width = len ( completion ) if width > self . min_width : self . min_width = width w = urwid . Text ( completion ) self . items . append ( urwid . AttrMap ( w , None , focus_map = palette ) ) self . items . set_focus ( 0 ) | Creates proper urwid . Text widgets for all completion candidates from p_completions list and populates them into the items attribute . | 98 | 28 |
243,327 | def _apply_filters ( self , p_todos ) : result = p_todos for _filter in sorted ( self . _filters , key = lambda f : f . order ) : result = _filter . filter ( result ) return result | Applies the filters to the list of todo items . | 56 | 12 |
243,328 | def todos ( self ) : result = self . _sorter . sort ( self . todolist . todos ( ) ) return self . _apply_filters ( result ) | Returns a sorted and filtered list of todos in this view . | 40 | 13 |
243,329 | def execute_specific ( self , p_todo ) : self . _handle_recurrence ( p_todo ) self . execute_specific_core ( p_todo ) printer = PrettyPrinter ( ) self . out ( self . prefix ( ) + printer . print_todo ( p_todo ) ) | Actions specific to this command . | 69 | 7 |
243,330 | def date_string_to_date ( p_date ) : result = None if p_date : parsed_date = re . match ( r'(\d{4})-(\d{2})-(\d{2})' , p_date ) if parsed_date : result = date ( int ( parsed_date . group ( 1 ) ) , # year int ( parsed_date . group ( 2 ) ) , # month int ( parsed_date . group ( 3 ) ) # day ) else : raise ValueError return result | Given a date in YYYY - MM - DD returns a Python date object . Throws a ValueError if the date is invalid . | 113 | 28 |
243,331 | def get_terminal_size ( p_getter = None ) : try : return get_terminal_size . getter ( ) except AttributeError : if p_getter : get_terminal_size . getter = p_getter else : def inner ( ) : try : # shutil.get_terminal_size was added to the standard # library in Python 3.3 try : from shutil import get_terminal_size as _get_terminal_size # pylint: disable=no-name-in-module except ImportError : from backports . shutil_get_terminal_size import get_terminal_size as _get_terminal_size # pylint: disable=import-error size = _get_terminal_size ( ) except ValueError : # This can result from the 'underlying buffer being detached', which # occurs during running the unittest on Windows (but not on Linux?) terminal_size = namedtuple ( 'Terminal_Size' , 'columns lines' ) size = terminal_size ( 80 , 24 ) return size get_terminal_size . getter = inner return get_terminal_size . getter ( ) | Try to determine terminal size at run time . If that is not possible returns the default size of 80x24 . | 263 | 23 |
243,332 | def translate_key_to_config ( p_key ) : if len ( p_key ) > 1 : key = p_key . capitalize ( ) if key . startswith ( 'Ctrl' ) or key . startswith ( 'Meta' ) : key = key [ 0 ] + '-' + key [ 5 : ] key = '<' + key + '>' else : key = p_key return key | Translates urwid key event to form understandable by topydo config parser . | 91 | 17 |
243,333 | def humanize_date ( p_datetime ) : now = arrow . now ( ) _date = now . replace ( day = p_datetime . day , month = p_datetime . month , year = p_datetime . year ) return _date . humanize ( now ) . replace ( 'just now' , 'today' ) | Returns a relative date string from a datetime object . | 74 | 11 |
243,334 | def _check_id_validity ( self , p_ids ) : errors = [ ] valid_ids = self . todolist . ids ( ) if len ( p_ids ) == 0 : errors . append ( 'No todo item was selected' ) else : errors = [ "Invalid todo ID: {}" . format ( todo_id ) for todo_id in p_ids - valid_ids ] errors = '\n' . join ( errors ) if errors else None return errors | Checks if there are any invalid todo IDs in p_ids list . | 110 | 16 |
243,335 | def _execute_handler ( self , p_command , p_todo_id = None , p_output = None ) : p_output = p_output or self . _output self . _console_visible = False self . _last_cmd = ( p_command , p_output == self . _output ) try : p_command = shlex . split ( p_command ) except ValueError as verr : self . _print_to_console ( 'Error: ' + str ( verr ) ) return try : subcommand , args = get_subcommand ( p_command ) except ConfigError as cerr : self . _print_to_console ( 'Error: {}. Check your aliases configuration.' . format ( cerr ) ) return if subcommand is None : self . _print_to_console ( GENERIC_HELP ) return env_args = ( self . todolist , p_output , self . _output , self . _input ) ids = None if '{}' in args : if self . _has_marked_todos ( ) : ids = self . marked_todos else : ids = { p_todo_id } if p_todo_id else set ( ) invalid_ids = self . _check_id_validity ( ids ) if invalid_ids : self . _print_to_console ( 'Error: ' + invalid_ids ) return transaction = Transaction ( subcommand , env_args , ids ) transaction . prepare ( args ) label = transaction . label self . _backup ( subcommand , p_label = label ) try : if transaction . execute ( ) : post_archive_action = transaction . execute_post_archive_actions self . _post_archive_action = post_archive_action self . _post_execute ( ) else : self . _rollback ( ) except TypeError : # TODO: show error message pass | Executes a command given as a string . | 420 | 9 |
243,336 | def _viewdata_to_view ( self , p_data ) : sorter = Sorter ( p_data [ 'sortexpr' ] , p_data [ 'groupexpr' ] ) filters = [ ] if not p_data [ 'show_all' ] : filters . append ( DependencyFilter ( self . todolist ) ) filters . append ( RelevanceFilter ( ) ) filters . append ( HiddenTagFilter ( ) ) filters += get_filter_list ( p_data [ 'filterexpr' ] . split ( ) ) return UIView ( sorter , filters , self . todolist , p_data ) | Converts a dictionary describing a view to an actual UIView instance . | 145 | 15 |
243,337 | def _update_view ( self , p_data ) : view = self . _viewdata_to_view ( p_data ) if self . column_mode == _APPEND_COLUMN or self . column_mode == _COPY_COLUMN : self . _add_column ( view ) elif self . column_mode == _INSERT_COLUMN : self . _add_column ( view , self . columns . focus_position ) elif self . column_mode == _EDIT_COLUMN : current_column = self . columns . focus current_column . title = p_data [ 'title' ] current_column . view = view self . _viewwidget_visible = False self . _blur_commandline ( ) | Creates a view from the data entered in the view widget . | 165 | 13 |
243,338 | def _add_column ( self , p_view , p_pos = None ) : def execute_silent ( p_cmd , p_todo_id = None ) : self . _execute_handler ( p_cmd , p_todo_id , lambda _ : None ) todolist = TodoListWidget ( p_view , p_view . data [ 'title' ] , self . keymap ) urwid . connect_signal ( todolist , 'execute_command_silent' , execute_silent ) urwid . connect_signal ( todolist , 'execute_command' , self . _execute_handler ) urwid . connect_signal ( todolist , 'repeat_cmd' , self . _repeat_last_cmd ) urwid . connect_signal ( todolist , 'refresh' , self . mainloop . screen . clear ) urwid . connect_signal ( todolist , 'add_pending_action' , self . _set_alarm ) urwid . connect_signal ( todolist , 'remove_pending_action' , self . _remove_alarm ) urwid . connect_signal ( todolist , 'column_action' , self . _column_action_handler ) urwid . connect_signal ( todolist , 'show_keystate' , self . _print_keystate ) urwid . connect_signal ( todolist , 'toggle_mark' , self . _process_mark_toggle ) options = self . columns . options ( width_type = 'given' , width_amount = config ( ) . column_width ( ) , box_widget = True ) item = ( todolist , options ) if p_pos == None : p_pos = len ( self . columns . contents ) self . columns . contents . insert ( p_pos , item ) self . columns . focus_position = p_pos self . _blur_commandline ( ) | Given an UIView adds a new column widget with the todos in that view . | 444 | 18 |
243,339 | def _process_mark_toggle ( self , p_todo_id , p_force = None ) : if p_force in [ 'mark' , 'unmark' ] : action = p_force else : action = 'mark' if p_todo_id not in self . marked_todos else 'unmark' if action == 'mark' : self . marked_todos . add ( p_todo_id ) return True else : self . marked_todos . remove ( p_todo_id ) return False | Adds p_todo_id to marked_todos attribute and returns True if p_todo_id is not already marked . Removes p_todo_id from marked_todos and returns False otherwise . | 120 | 48 |
243,340 | def reset ( self ) : self . titleedit . set_edit_text ( "" ) self . sortedit . set_edit_text ( "" ) self . filteredit . set_edit_text ( "" ) self . relevantradio . set_state ( True ) self . pile . focus_item = 0 | Resets the form . | 65 | 5 |
243,341 | def has_tag ( self , p_key , p_value = "" ) : tags = self . fields [ 'tags' ] return p_key in tags and ( p_value == "" or p_value in tags [ p_key ] ) | Returns true when there is at least one tag with the given key . If a value is passed it will only return true when there exists a tag with the given key - value combination . | 53 | 37 |
243,342 | def _remove_tag_helper ( self , p_key , p_value ) : tags = self . fields [ 'tags' ] try : tags [ p_key ] = [ t for t in tags [ p_key ] if p_value != "" and t != p_value ] if len ( tags [ p_key ] ) == 0 : del tags [ p_key ] except KeyError : pass | Removes a tag from the internal todo dictionary . Only those instances with the given value are removed . If the value is empty all tags with the given key are removed . | 88 | 35 |
243,343 | def set_tag ( self , p_key , p_value = "" , p_force_add = False , p_old_value = "" ) : if p_value == "" : self . remove_tag ( p_key , p_old_value ) return tags = self . fields [ 'tags' ] value = p_old_value if p_old_value else self . tag_value ( p_key ) if not p_force_add and value : self . _remove_tag_helper ( p_key , value ) self . src = re . sub ( r'\b' + p_key + ':' + value + r'\b' , p_key + ':' + p_value , self . src ) else : self . src += ' ' + p_key + ':' + p_value try : tags [ p_key ] . append ( p_value ) except KeyError : tags [ p_key ] = [ p_value ] | Sets a occurrence of the tag identified by p_key . Sets an arbitrary instance of the tag when the todo contains multiple tags with this key . When p_key does not exist the tag is added . | 212 | 43 |
243,344 | def tags ( self ) : tags = self . fields [ 'tags' ] return [ ( t , v ) for t in tags for v in tags [ t ] ] | Returns a list of tuples with key - value pairs representing tags in this todo item . | 35 | 19 |
243,345 | def set_source_text ( self , p_text ) : self . src = p_text . strip ( ) self . fields = parse_line ( self . src ) | Sets the todo source text . The text will be parsed again . | 37 | 15 |
243,346 | def set_completed ( self , p_completion_date = date . today ( ) ) : if not self . is_completed ( ) : self . set_priority ( None ) self . fields [ 'completed' ] = True self . fields [ 'completionDate' ] = p_completion_date self . src = re . sub ( r'^(\([A-Z]\) )?' , 'x ' + p_completion_date . isoformat ( ) + ' ' , self . src ) | Marks the todo as complete . Sets the completed flag and sets the completion date to today . | 113 | 20 |
243,347 | def set_creation_date ( self , p_date = date . today ( ) ) : self . fields [ 'creationDate' ] = p_date # not particularly pretty, but inspired by # http://bugs.python.org/issue1519638 non-existent matches trigger # exceptions, hence the lambda self . src = re . sub ( r'^(x \d{4}-\d{2}-\d{2} |\([A-Z]\) )?(\d{4}-\d{2}-\d{2} )?(.*)$' , lambda m : u"{}{} {}" . format ( m . group ( 1 ) or '' , p_date . isoformat ( ) , m . group ( 3 ) ) , self . src ) | Sets the creation date of a todo . Should be passed a date object . | 173 | 17 |
243,348 | def update ( self ) : old_focus_position = self . todolist . focus id_length = max_id_length ( self . view . todolist . count ( ) ) del self . todolist [ : ] for group , todos in self . view . groups . items ( ) : if len ( self . view . groups ) > 1 : grouplabel = ", " . join ( group ) self . todolist . append ( urwid . Text ( grouplabel ) ) self . todolist . append ( urwid . Divider ( '-' ) ) for todo in todos : todowidget = TodoWidget . create ( todo , id_length ) todowidget . number = self . view . todolist . number ( todo ) self . todolist . append ( todowidget ) self . todolist . append ( urwid . Divider ( '-' ) ) if old_focus_position : try : self . todolist . set_focus ( old_focus_position ) except IndexError : # scroll to the bottom if the last item disappeared from column # -2 for the same reason as in self._scroll_to_bottom() self . todolist . set_focus ( len ( self . todolist ) - 2 ) | Updates the todo list according to the todos in the view associated with this list . | 291 | 19 |
243,349 | def _execute_on_selected ( self , p_cmd_str , p_execute_signal ) : try : todo = self . listbox . focus . todo todo_id = str ( self . view . todolist . number ( todo ) ) urwid . emit_signal ( self , p_execute_signal , p_cmd_str , todo_id ) # force screen redraw after editing if p_cmd_str . startswith ( 'edit' ) : urwid . emit_signal ( self , 'refresh' ) except AttributeError : # No todo item selected pass | Executes command specified by p_cmd_str on selected todo item . | 138 | 16 |
243,350 | def execute_builtin_action ( self , p_action_str , p_size = None ) : column_actions = [ 'first_column' , 'last_column' , 'prev_column' , 'next_column' , 'append_column' , 'insert_column' , 'edit_column' , 'delete_column' , 'copy_column' , 'swap_left' , 'swap_right' , 'reset' , ] if p_action_str in column_actions : urwid . emit_signal ( self , 'column_action' , p_action_str ) elif p_action_str in [ 'up' , 'down' ] : self . listbox . keypress ( p_size , p_action_str ) elif p_action_str == 'home' : self . _scroll_to_top ( p_size ) elif p_action_str == 'end' : self . _scroll_to_bottom ( p_size ) elif p_action_str in [ 'postpone' , 'postpone_s' ] : pass elif p_action_str == 'pri' : pass elif p_action_str == 'mark' : self . _toggle_marked_status ( ) elif p_action_str == 'mark_all' : self . _mark_all ( ) elif p_action_str == 'repeat' : self . _repeat_cmd ( ) | Executes built - in action specified in p_action_str . | 322 | 14 |
243,351 | def _add_pending_action ( self , p_action , p_size ) : def generate_callback ( ) : def callback ( * args ) : self . resolve_action ( p_action , p_size ) self . keystate = None return callback urwid . emit_signal ( self , 'add_pending_action' , generate_callback ( ) ) | Creates action waiting for execution and forwards it to the mainloop . | 81 | 14 |
243,352 | def read ( self ) : todos = [ ] try : todofile = codecs . open ( self . path , 'r' , encoding = "utf-8" ) todos = todofile . readlines ( ) todofile . close ( ) except IOError : pass return todos | Reads the todo . txt file and returns a list of todo items . | 67 | 18 |
243,353 | def write ( self , p_todos ) : todofile = codecs . open ( self . path , 'w' , encoding = "utf-8" ) if p_todos is list : for todo in p_todos : todofile . write ( str ( todo ) ) else : todofile . write ( p_todos ) todofile . write ( "\n" ) todofile . close ( ) | Writes all the todo items to the todo . txt file . | 104 | 16 |
243,354 | def main ( ) : try : args = sys . argv [ 1 : ] try : _ , args = getopt . getopt ( args , MAIN_OPTS , MAIN_LONG_OPTS ) except getopt . GetoptError as e : error ( str ( e ) ) sys . exit ( 1 ) if args [ 0 ] == 'prompt' : try : from topydo . ui . prompt . Prompt import PromptApplication PromptApplication ( ) . run ( ) except ImportError : error ( "Some additional dependencies for prompt mode were not installed, please install with 'pip3 install topydo[prompt]'" ) elif args [ 0 ] == 'columns' : try : from topydo . ui . columns . Main import UIApplication UIApplication ( ) . run ( ) except ImportError : error ( "Some additional dependencies for column mode were not installed, please install with 'pip3 install topydo[columns]'" ) except NameError as err : if _WINDOWS : error ( "Column mode is not supported on Windows." ) else : error ( "Could not load column mode: {}" . format ( err ) ) else : CLIApplication ( ) . run ( ) except IndexError : CLIApplication ( ) . run ( ) | Main entry point of the CLI . | 279 | 7 |
243,355 | def importance ( p_todo , p_ignore_weekend = config ( ) . ignore_weekends ( ) ) : result = 2 priority = p_todo . priority ( ) result += IMPORTANCE_VALUE [ priority ] if priority in IMPORTANCE_VALUE else 0 if p_todo . has_tag ( config ( ) . tag_due ( ) ) : days_left = p_todo . days_till_due ( ) if days_left >= 7 and days_left < 14 : result += 1 elif days_left >= 2 and days_left < 7 : result += 2 elif days_left >= 1 and days_left < 2 : result += 3 elif days_left >= 0 and days_left < 1 : result += 5 elif days_left < 0 : result += 6 if p_ignore_weekend and is_due_next_monday ( p_todo ) : result += 1 if p_todo . has_tag ( config ( ) . tag_star ( ) ) : result += 1 return result if not p_todo . is_completed ( ) else 0 | Calculates the importance of the given task . Returns an importance of zero when the task has been completed . | 243 | 22 |
243,356 | def _maintain_dep_graph ( self , p_todo ) : dep_id = p_todo . tag_value ( 'id' ) # maintain dependency graph if dep_id : self . _parentdict [ dep_id ] = p_todo self . _depgraph . add_node ( hash ( p_todo ) ) # connect all tasks we have in memory so far that refer to this # task for dep in [ dep for dep in self . _todos if dep . has_tag ( 'p' , dep_id ) ] : self . _add_edge ( p_todo , dep , dep_id ) for dep_id in p_todo . tag_values ( 'p' ) : try : parent = self . _parentdict [ dep_id ] self . _add_edge ( parent , p_todo , dep_id ) except KeyError : pass | Makes sure that the dependency graph is consistent according to the given todo . | 197 | 16 |
243,357 | def add_dependency ( self , p_from_todo , p_to_todo ) : def find_next_id ( ) : """ Find a new unused ID. Unused means that no task has it as an 'id' value or as a 'p' value. """ def id_exists ( p_id ) : """ Returns True if there exists a todo with the given parent ID. """ for todo in self . _todos : number = str ( p_id ) if todo . has_tag ( 'id' , number ) or todo . has_tag ( 'p' , number ) : return True return False new_id = 1 while id_exists ( new_id ) : new_id += 1 return str ( new_id ) def append_projects_to_subtodo ( ) : """ Appends projects in the parent todo item that are not present in the sub todo item. """ if config ( ) . append_parent_projects ( ) : for project in p_from_todo . projects ( ) - p_to_todo . projects ( ) : self . append ( p_to_todo , "+{}" . format ( project ) ) def append_contexts_to_subtodo ( ) : """ Appends contexts in the parent todo item that are not present in the sub todo item. """ if config ( ) . append_parent_contexts ( ) : for context in p_from_todo . contexts ( ) - p_to_todo . contexts ( ) : self . append ( p_to_todo , "@{}" . format ( context ) ) if p_from_todo != p_to_todo and not self . _depgraph . has_edge ( hash ( p_from_todo ) , hash ( p_to_todo ) ) : dep_id = None if p_from_todo . has_tag ( 'id' ) : dep_id = p_from_todo . tag_value ( 'id' ) else : dep_id = find_next_id ( ) p_from_todo . set_tag ( 'id' , dep_id ) p_to_todo . add_tag ( 'p' , dep_id ) self . _add_edge ( p_from_todo , p_to_todo , dep_id ) append_projects_to_subtodo ( ) append_contexts_to_subtodo ( ) self . dirty = True | Adds a dependency from task 1 to task 2 . | 549 | 10 |
243,358 | def remove_dependency ( self , p_from_todo , p_to_todo , p_leave_tags = False ) : dep_id = p_from_todo . tag_value ( 'id' ) if dep_id : self . _depgraph . remove_edge ( hash ( p_from_todo ) , hash ( p_to_todo ) ) self . dirty = True # clean dangling dependency tags if dep_id and not p_leave_tags : p_to_todo . remove_tag ( 'p' , dep_id ) if not self . children ( p_from_todo , True ) : p_from_todo . remove_tag ( 'id' ) del self . _parentdict [ dep_id ] | Removes a dependency between two todos . | 168 | 9 |
243,359 | def clean_dependencies ( self ) : def remove_tag ( p_todo , p_tag , p_value ) : """ Removes a tag from a todo item. """ p_todo . remove_tag ( p_tag , p_value ) self . dirty = True def clean_parent_relations ( ) : """ Remove id: tags for todos without child todo items. """ for todo in [ todo for todo in self . _todos if todo . has_tag ( 'id' ) ] : value = todo . tag_value ( 'id' ) if not self . _depgraph . has_edge_id ( value ) : remove_tag ( todo , 'id' , value ) del self . _parentdict [ value ] def clean_orphan_relations ( ) : """ Remove p: tags for todos referring to a parent that is not in the dependency graph anymore. """ for todo in [ todo for todo in self . _todos if todo . has_tag ( 'p' ) ] : for value in todo . tag_values ( 'p' ) : parent = self . todo_by_dep_id ( value ) if not self . _depgraph . has_edge ( hash ( parent ) , hash ( todo ) ) : remove_tag ( todo , 'p' , value ) self . _depgraph . transitively_reduce ( ) clean_parent_relations ( ) clean_orphan_relations ( ) | Cleans the dependency graph . | 328 | 6 |
243,360 | def _convert_todo ( p_todo ) : creation_date = p_todo . creation_date ( ) completion_date = p_todo . completion_date ( ) result = { 'source' : p_todo . source ( ) , 'text' : p_todo . text ( ) , 'priority' : p_todo . priority ( ) , 'completed' : p_todo . is_completed ( ) , 'tags' : p_todo . tags ( ) , 'projects' : list ( p_todo . projects ( ) ) , 'contexts' : list ( p_todo . contexts ( ) ) , 'creation_date' : creation_date . isoformat ( ) if creation_date else None , 'completion_date' : completion_date . isoformat ( ) if completion_date else None } return result | Converts a Todo instance to a dictionary . | 192 | 10 |
243,361 | def get_backup_path ( ) : dirname , filename = path . split ( path . splitext ( config ( ) . todotxt ( ) ) [ 0 ] ) filename = '.' + filename + '.bak' return path . join ( dirname , filename ) | Returns full path and filename of backup file | 60 | 8 |
243,362 | def _read ( self ) : self . json_file . seek ( 0 ) try : data = zlib . decompress ( self . json_file . read ( ) ) self . backup_dict = json . loads ( data . decode ( 'utf-8' ) ) except ( EOFError , zlib . error ) : self . backup_dict = { } | Reads backup file from json_file property and sets backup_dict property with data decompressed and deserialized from that file . If no usable data is found backup_dict is set to the empty dict . | 78 | 43 |
243,363 | def _write ( self ) : self . json_file . seek ( 0 ) self . json_file . truncate ( ) dump = json . dumps ( self . backup_dict ) dump_c = zlib . compress ( dump . encode ( 'utf-8' ) ) self . json_file . write ( dump_c ) | Writes data from backup_dict property in serialized and compressed form to backup file pointed in json_file property . | 71 | 24 |
243,364 | def save ( self , p_todolist ) : self . _trim ( ) current_hash = hash_todolist ( p_todolist ) list_todo = ( self . todolist . print_todos ( ) + '\n' ) . splitlines ( True ) try : list_archive = ( self . archive . print_todos ( ) + '\n' ) . splitlines ( True ) except AttributeError : list_archive = [ ] self . backup_dict [ self . timestamp ] = ( list_todo , list_archive , self . label ) index = self . _get_index ( ) index . insert ( 0 , ( self . timestamp , current_hash ) ) self . _save_index ( index ) self . _write ( ) self . close ( ) | Saves a tuple with archive todolist and command with its arguments into the backup file with unix timestamp as the key . Tuple is then indexed in backup file with combination of hash calculated from p_todolist and unix timestamp . Backup file is closed afterwards . | 182 | 58 |
243,365 | def delete ( self , p_timestamp = None , p_write = True ) : timestamp = p_timestamp or self . timestamp index = self . _get_index ( ) try : del self . backup_dict [ timestamp ] index . remove ( index [ [ change [ 0 ] for change in index ] . index ( timestamp ) ] ) self . _save_index ( index ) if p_write : self . _write ( ) except KeyError : pass | Removes backup from the backup file . | 98 | 8 |
243,366 | def _trim ( self ) : index = self . _get_index ( ) backup_limit = config ( ) . backup_count ( ) - 1 for changeset in index [ backup_limit : ] : self . delete ( changeset [ 0 ] , p_write = False ) | Removes oldest backups that exceed the limit configured in backup_count option . | 61 | 15 |
243,367 | def apply ( self , p_todolist , p_archive ) : if self . todolist and p_todolist : p_todolist . replace ( self . todolist . todos ( ) ) if self . archive and p_archive : p_archive . replace ( self . archive . todos ( ) ) | Applies backup on supplied p_todolist . | 77 | 12 |
243,368 | def pretty_printer_factory ( p_todolist , p_additional_filters = None ) : p_additional_filters = p_additional_filters or [ ] printer = PrettyPrinter ( ) printer . add_filter ( PrettyPrinterNumbers ( p_todolist ) ) for ppf in p_additional_filters : printer . add_filter ( ppf ) # apply colors at the last step, the ANSI codes may confuse the # preceding filters. printer . add_filter ( PrettyPrinterColorFilter ( ) ) return printer | Returns a pretty printer suitable for the ls and dep subcommands . | 127 | 14 |
243,369 | def print_todo ( self , p_todo ) : todo_str = p_todo . source ( ) for ppf in self . filters : todo_str = ppf . filter ( todo_str , p_todo ) return TopydoString ( todo_str ) | Given a todo item pretty print it . | 66 | 9 |
243,370 | def group ( self , p_todos ) : # preorder todos for the group sort p_todos = _apply_sort_functions ( p_todos , self . pregroupfunctions ) # initialize result with a single group result = OrderedDict ( [ ( ( ) , p_todos ) ] ) for ( function , label ) , _ in self . groupfunctions : oldresult = result result = OrderedDict ( ) for oldkey , oldgroup in oldresult . items ( ) : for key , _group in groupby ( oldgroup , function ) : newgroup = list ( _group ) if not isinstance ( key , list ) : key = [ key ] for subkey in key : subkey = "{}: {}" . format ( label , subkey ) newkey = oldkey + ( subkey , ) if newkey in result : result [ newkey ] = result [ newkey ] + newgroup else : result [ newkey ] = newgroup # sort all groups for key , _group in result . items ( ) : result [ key ] = self . sort ( _group ) return result | Groups the todos according to the given group string . | 246 | 12 |
243,371 | def _strip_placeholder_braces ( p_matchobj ) : before = p_matchobj . group ( 'before' ) or '' placeholder = p_matchobj . group ( 'placeholder' ) after = p_matchobj . group ( 'after' ) or '' whitespace = p_matchobj . group ( 'whitespace' ) or '' return before + '%' + placeholder + after + whitespace | Returns string with conditional braces around placeholder stripped and percent sign glued into placeholder character . | 91 | 16 |
243,372 | def _truncate ( p_str , p_repl ) : # 4 is for '...' and an extra space at the end text_lim = _columns ( ) - len ( escape_ansi ( p_str ) ) - 4 truncated_str = re . sub ( re . escape ( p_repl ) , p_repl [ : text_lim ] + '...' , p_str ) return truncated_str | Returns p_str with truncated and ended with ... version of p_repl . | 94 | 17 |
243,373 | def _preprocess_format ( self ) : format_split = re . split ( r'(?<!\\)%' , self . format_string ) preprocessed_format = [ ] for idx , substr in enumerate ( format_split ) : if idx == 0 : getter = None placeholder = None else : pattern = MAIN_PATTERN . format ( ph = r'\S' ) try : placeholder = re . match ( pattern , substr ) . group ( 'placeholder' ) . strip ( '[]' ) except AttributeError : placeholder = None if placeholder == 'S' : self . one_line = True try : getter = self . placeholders [ placeholder ] except KeyError : getter = None substr = re . sub ( pattern , '' , substr ) format_elem = ( substr , placeholder , getter ) preprocessed_format . append ( format_elem ) return preprocessed_format | Preprocess the format_string attribute . | 204 | 8 |
243,374 | def parse ( self , p_todo ) : parsed_list = [ ] repl_trunc = None for substr , placeholder , getter in self . format_list : repl = getter ( p_todo ) if getter else '' pattern = MAIN_PATTERN . format ( ph = placeholder ) if placeholder == 'S' : repl_trunc = repl try : if repl == '' : substr = re . sub ( pattern , '' , substr ) else : substr = re . sub ( pattern , _strip_placeholder_braces , substr ) substr = re . sub ( r'(?<!\\)%({ph}|\[{ph}\])' . format ( ph = placeholder ) , repl , substr ) except re . error : raise ListFormatError parsed_list . append ( substr ) parsed_str = _unescape_percent_sign ( '' . join ( parsed_list ) ) parsed_str = _remove_redundant_spaces ( parsed_str ) if self . one_line and len ( escape_ansi ( parsed_str ) ) >= _columns ( ) : parsed_str = _truncate ( parsed_str , repl_trunc ) if re . search ( '.*\t' , parsed_str ) : parsed_str = _right_align ( parsed_str ) return parsed_str . rstrip ( ) | Returns fully parsed string from format_string attribute with all placeholders properly substituted by content obtained from p_todo . | 296 | 24 |
243,375 | def _load_file ( self ) : self . todolist . erase ( ) self . todolist . add_list ( self . todofile . read ( ) ) self . completer = PromptCompleter ( self . todolist ) | Reads the configured todo . txt file and loads it into the todo list instance . | 58 | 20 |
243,376 | 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 . | 48 | 18 |
243,377 | 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 . | 34 | 14 |
243,378 | 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 . | 87 | 6 |
243,379 | 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 : colors = lookup [ self . cp . get ( 'topydo' , 'colors' ) . lower ( ) ] # pylint: disable=no-member except ValueError : colors = lookup [ self . defaults [ 'topydo' ] [ 'colors' ] . lower ( ) ] # pylint: disable=no-member except KeyError : # for invalid values or 'auto' colors = 16 if p_hint_possible else 0 # disable colors when no colors are enforced on the commandline and # color support is determined automatically return 0 if not forced and not p_hint_possible else colors | Returns 0 16 or 256 representing the number of colors that should be used in the output . | 260 | 18 |
243,380 | def hidden_tags ( self ) : hidden_tags = self . cp . get ( 'ls' , 'hide_tags' ) # pylint: disable=no-member 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 . | 67 | 13 |
243,381 | def hidden_item_tags ( self ) : hidden_item_tags = self . cp . get ( 'ls' , 'hidden_item_tags' ) # pylint: disable=no-member 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 . | 77 | 14 |
243,382 | 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_colors' ) if pri_colors_str == '' : pri_colors_dict = _str_to_dict ( 'A:-1,B:-1,C:-1' ) else : pri_colors_dict = _str_to_dict ( pri_colors_str ) except ValueError : pri_colors_dict = _str_to_dict ( self . defaults [ 'colorscheme' ] [ 'priority_colors' ] ) return pri_colors_dict [ p_priority ] if p_priority in pri_colors_dict else Color ( 'NEUTRAL' ) | Returns a dict with priorities as keys and color numbers as value . | 242 | 13 |
243,383 | 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 [ alias ] = str ( verr ) return alias_dict | Returns dict with aliases names as keys and pairs of actual subcommand and alias args as values . | 102 | 19 |
243,384 | def column_keymap ( self ) : keystates = set ( ) shortcuts = self . cp . items ( 'column_keymap' ) keymap_dict = dict ( shortcuts ) for combo , action in shortcuts : # add all possible prefixes to keystates combo_as_list = re . split ( '(<[A-Z].+?>|.)' , combo ) [ 1 : : 2 ] if len ( combo_as_list ) > 1 : keystates |= set ( accumulate ( combo_as_list [ : - 1 ] ) ) if action in [ 'pri' , 'postpone' , 'postpone_s' ] : keystates . add ( combo ) if action == 'pri' : for c in ascii_lowercase : keymap_dict [ combo + c ] = 'cmd pri {} ' + c return ( keymap_dict , keystates ) | Returns keymap and keystates used in column mode | 193 | 10 |
243,385 | 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' ] : result = os . environ [ 'EDITOR' ] return shlex . split ( result ) | Returns the editor to invoke . It returns a list with the command in the first position and its arguments in the remainder . | 130 | 24 |
243,386 | 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 ) : self . error ( 'File not found: ' + self . from_file ) else : if self . text : self . _add_todo ( self . text ) else : self . error ( self . usage ( ) ) | Adds a todo item to the list . | 155 | 9 |
243,387 | 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 # strip off the + pattern = pattern [ 1 : ] if p_strict : offset = p_todo . due_date ( ) or p_offset or date . today ( ) else : offset = p_offset or date . today ( ) length = todo . length ( ) new_due = relative_date_to_date ( pattern , offset ) if not new_due : raise NoRecurrenceException ( ) # pylint: disable=E1103 todo . set_tag ( config ( ) . tag_due ( ) , new_due . isoformat ( ) ) if todo . start_date ( ) : new_start = new_due - timedelta ( length ) todo . set_tag ( config ( ) . tag_start ( ) , new_start . isoformat ( ) ) todo . set_creation_date ( date . today ( ) ) return todo | Given a Todo item return a new instance of a Todo item with the dates shifted according to the recurrence rule . | 279 | 25 |
243,388 | 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 . | 86 | 55 |
243,389 | def hash_list_values ( p_list , p_key = lambda i : i ) : # pragma: no branch def to_base ( p_alphabet , p_value ) : """ Converts integer to text ID with characters from the given alphabet. Based on answer at https://stackoverflow.com/questions/1181919/python-base-36-encoding """ 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 ( ) try : _ , size = _get_table_size ( alphabet , len ( p_list ) ) except _TableSizeException : alphabet = _DEFAULT_ALPHABET _ , size = _get_table_size ( alphabet , len ( p_list ) ) for item in p_list : # obtain the to-be-hashed value raw_value = p_key ( item ) # hash hasher = sha1 ( ) hasher . update ( raw_value . encode ( 'utf-8' ) ) hash_value = int ( hasher . hexdigest ( ) , 16 ) % size # resolve possible collisions while hash_value in used : hash_value = ( hash_value + 1 ) % size used . add ( hash_value ) result . append ( ( item , to_base ( alphabet , hash_value ) ) ) return result | Calculates a unique value for each item in the list these can be used as identifiers . | 340 | 19 |
243,390 | 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 . | 75 | 24 |
243,391 | 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' , AbstractColor . META ) , ( r'(^|\s)(\w+:){1}(//\S+)' , AbstractColor . LINK ) , ] # color by priority p_todo_str . set_color ( 0 , priority_color ) for pattern , color in colors : for match in re . finditer ( pattern , p_todo_str . data ) : p_todo_str . set_color ( match . start ( ) , color ) p_todo_str . set_color ( match . end ( ) , priority_color ) p_todo_str . append ( '' , AbstractColor . NEUTRAL ) return p_todo_str | Applies the colors . | 287 | 5 |
243,392 | def get_filter_list ( p_expression ) : result = [ ] for arg in p_expression : # when a word starts with -, it should be negated 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 = GrepFilter ( arg ) if is_negated : argfilter = NegationFilter ( argfilter ) result . append ( argfilter ) return result | Returns a list of GrepFilters OrdinalTagFilters or NegationFilters based on the given filter expression . | 141 | 25 |
243,393 | 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 . | 54 | 13 |
243,394 | 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 . | 33 | 16 |
243,395 | 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 . | 78 | 18 |
243,396 | 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 . operator == '>' : return p_operand1 > p_operand2 elif self . operator == '!' : return p_operand1 != p_operand2 return False | Returns True if conditional constructed from both operands and self . operator is valid . Returns False otherwise . | 152 | 20 |
243,397 | 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 . | 50 | 12 |
243,398 | def date_suggestions ( ) : # don't use strftime, prevent locales to kick in days_of_week = { 0 : "Monday" , 1 : "Tuesday" , 2 : "Wednesday" , 3 : "Thursday" , 4 : "Friday" , 5 : "Saturday" , 6 : "Sunday" } dates = [ 'today' , 'tomorrow' , ] # show days of week up to next week dow = datetime . date . today ( ) . weekday ( ) for i in range ( dow + 2 % 7 , dow + 7 ) : dates . append ( days_of_week [ i % 7 ] ) # and some more relative days starting from next week dates += [ "1w" , "2w" , "1m" , "2m" , "3m" , "1y" ] return dates | Returns a list of relative date that is presented to the user as auto complete suggestions . | 182 | 17 |
243,399 | 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 . | 63 | 16 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.