Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def feature_assert(*feas):
fav = APIVersion()
for fea in feas:
fn = feature_needs(fea)
if fav < fn:
raise FuseError(
"FUSE API version %d is required for feature `%s' but only %d is available" % \
(fn, st... | [
"\n Takes some feature patterns (like in `feature_needs`).\n Raises a fuse.FuseError if your underlying FUSE lib fails\n to have some of the matching features.\n\n (Note: use a ``has_foo`` type feature assertion only if lib support\n for method ``foo`` is *necessary* for your fs. Don't use this asser... |
Please provide a description of the function:def assemble(self):
self.canonify()
args = [sys.argv and sys.argv[0] or "python"]
if self.mountpoint:
args.append(self.mountpoint)
for m, v in self.modifiers.items():
if v:
args.append(self.fus... | [
"Mangle self into an argument array"
] |
Please provide a description of the function:def filter(self, other=None):
if not other:
other = Fuse.fuseoptref()
return SubOptsHive.filter(self, other) | [
"\n Same as for SubOptsHive, with the following difference:\n if other is not specified, `Fuse.fuseoptref()` is run and its result\n will be used.\n "
] |
Please provide a description of the function:def parse(self, *args, **kw):
ev = 'errex' in kw and kw.pop('errex')
if ev and not isinstance(ev, int):
raise TypeError("error exit value should be an integer")
try:
self.cmdline = self.parser.parse_args(*args, **kw)... | [
"Parse command line, fill `fuse_args` attribute."
] |
Please provide a description of the function:def main(self, args=None):
if get_compat_0_1():
args = self.main_0_1_preamble()
d = {'multithreaded': self.multithreaded and 1 or 0}
d['fuse_args'] = args or self.fuse_args.assemble()
for t in 'file_class', 'dir_class':... | [
"Enter filesystem service loop."
] |
Please provide a description of the function:def lowwrap(self, fname):
fun = getattr(self, fname)
if fname in ('open', 'create'):
def wrap(*a, **kw):
res = fun(*a, **kw)
if not res or type(res) == type(0):
return res
... | [
"\n Wraps the fname method when the C code expects a different kind of\n callback than we have in the fusepy API. (The wrapper is usually for\n performing some checks or transfromations which could be done in C but\n is simpler if done in Python.)\n\n Currently `open` and `create`... |
Please provide a description of the function:def fuseoptref(cls):
import os, re
pr, pw = os.pipe()
pid = os.fork()
if pid == 0:
os.dup2(pw, 2)
os.close(pr)
fh = cls()
fh.fuse_args = FuseArgs()
fh.fuse_args.setmo... | [
"\n Find out which options are recognized by the library.\n Result is a `FuseArgs` instance with the list of supported\n options, suitable for passing on to the `filter` method of\n another `FuseArgs` instance.\n "
] |
Please provide a description of the function:def canonify(self):
for k, v in self.optdict.items():
if v == False:
self.optdict.pop(k)
elif v == True:
self.optdict.pop(k)
self.optlist.add(v)
else:
self.o... | [
"\n Transform self to an equivalent canonical form:\n delete optdict keys with False value, move optdict keys\n with True value to optlist, stringify other values.\n "
] |
Please provide a description of the function:def filter(self, other):
self.canonify()
other.canonify()
rej = self.__class__()
rej.optlist = self.optlist.difference(other.optlist)
self.optlist.difference_update(rej.optlist)
for x in self.optdict.copy():
... | [
"\n Throw away those options which are not in the other one.\n Returns a new instance with the rejected options.\n "
] |
Please provide a description of the function:def add(self, opt, val=None):
ov = opt.split('=', 1)
o = ov[0]
v = len(ov) > 1 and ov[1] or None
if (v):
if val != None:
raise AttributeError("ambiguous option value")
val = v
if val ... | [
"Add a suboption."
] |
Please provide a description of the function:def register_sub(self, o):
if o.subopt in self.subopt_map:
raise OptionConflictError(
"conflicting suboption handlers for `%s'" % o.subopt,
o)
self.subopt_map[o.subopt] = o | [
"Register argument a suboption for `self`."
] |
Please provide a description of the function:def __return_json(url):
with try_URL():
response = requests.get(url)
if response.status_code == 200:
return response.json()
else:
return False | [
"\n Returns JSON data which is returned by querying the API service\n Called by\n - meaning()\n - synonym()\n\n :param url: the complete formatted url which is then queried using requests\n :returns: json content being fed by the API\n "
] |
Please provide a description of the function:def __parse_content(tuc_content, content_to_be_parsed):
initial_parsed_content = {}
i = 0
for content_dict in tuc_content:
if content_to_be_parsed in content_dict.keys():
contents_raw = content_dict[content_to_be_... | [
"\n parses the passed \"tuc_content\" for\n - meanings\n - synonym\n received by querying the glosbe API\n\n Called by\n - meaning()\n - synonym()\n\n :param tuc_content: passed on the calling Function. A list object\n :param content_to_be_parsed: d... |
Please provide a description of the function:def __clean_dict(dictionary):
key_dict = {}
value_dict = {}
final_list = []
for key in dictionary.keys():
key_dict[key] = "seq"
for value in dictionary.values():
value_dict[value] = "text"
for... | [
"\n Takes the dictionary from __parse_content() and creates a well formatted list\n\n :param dictionary: unformatted dict\n :returns: a list which contains dict's as it's elements\n "
] |
Please provide a description of the function: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)
... | [
"\n make calls to the glosbe API\n\n :param phrase: word for which meaning is to be found\n :param source_lang: Defaults to : \"en\"\n :param dest_lang: Defaults to : \"en\" For eg: \"fr\" for french\n :param format: response structure type. Defaults to: \"json\"\n :returns... |
Please provide a description of the function:def antonym(phrase, format="json"):
base_url = Vocabulary.__get_api_link("bighugelabs")
url = base_url.format(word=phrase)
json_obj = Vocabulary.__return_json(url)
if not json_obj:
return False
result = []
... | [
"\n queries the bighugelabs API for the antonym. The results include\n - \"syn\" (synonym)\n - \"ant\" (antonym)\n - \"rel\" (related terms)\n - \"sim\" (similar terms)\n - \"usr\" (user suggestions)\n\n But currently parsing only the antonym as I have already d... |
Please provide a description of the function: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:
... | [
"Takes the source phrase and queries it to the urbandictionary API\n\n :params phrase: word for which usage_example is to be found\n :param format: response structure type. Defaults to: \"json\"\n :returns: returns a json object as str, False if invalid phrase\n "
] |
Please provide a description of the function: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:
'''
... | [
"\n Gets the pronunciation from the Wordnik API\n\n :params phrase: word for which pronunciation is to be found\n :param format: response structure type. Defaults to: \"json\"\n :returns: returns a list object, False if invalid phrase\n "
] |
Please provide a description of the function: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.d... | [
"\n Returns back the stress points in the \"phrase\" passed\n\n :param phrase: word for which hyphenation is to be found\n :param format: response structure type. Defaults to: \"json\"\n :returns: returns a json object as str, False if invalid phrase\n "
] |
Please provide a description of the function: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 inde... | [
"\n Builds a python dictionary from a json object\n\n :param data: the json object\n :returns: a nested dictionary\n "
] |
Please provide a description of the function: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 isins... | [
"\n Builds a python list from a json object\n\n :param data: the json object\n :returns: a nested list\n "
] |
Please provide a description of the function: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 d... | [
"\n Converts a json object to a python datastructure based on\n specified format\n\n :param data: the json object\n :param format: python datastructure type. Defaults to: \"json\"\n :returns: a python specified object\n "
] |
Please provide a description of the function:def _process_flags(self):
super()._process_flags()
if len(self.args) == 0:
self.multi_mode = False | [
"\n Override to add an additional check after processing the flags: when\n there are no flags left after argument parsing, then it means we'll be\n editing the whole todo.txt file as a whole and therefore we're not in\n multi mode.\n "
] |
Please provide a description of the function: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 numb... | [
" Gets todo objects from supplied todo IDs. "
] |
Please provide a description of the function: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... | [
"\n Returns an attribute spec for the colors that correspond to the given todo\n item.\n "
] |
Please provide a description of the function:def create(p_class, p_todo, p_id_width=4):
def parent_progress_may_have_changed(p_todo):
return p_todo.has_tag('p') and not p_todo.has_tag('due')
source = p_todo.source()
if source in p_class.cache:
wid... | [
"\n Creates a TodoWidget instance for the given todo. Widgets are\n cached, the same object is returned for the same todo item.\n ",
"\n Returns True when a todo's progress should be updated because it is\n dependent on the parent's progress.\n "
] |
Please provide a description of the function:def _history_move(self, p_step):
if len(self.history) > 0:
# don't pollute real history - use temporary storage
self.history_tmp[self.history_pos] = self.edit_text
self.history_pos = self.history_pos + p_step
s... | [
"\n Changes current value of the command-line to the value obtained from\n history_tmp list with index calculated by addition of p_step to the\n current position in the command history (history_pos attribute).\n\n Also saves value of the command-line (before changing it) to history_tmp\n... |
Please provide a description of the function:def insert_completion(self, p_insert):
start, end = self._surrounding_text
final_text = start + p_insert + end
self.set_edit_text(final_text)
self.set_edit_pos(len(start) + len(p_insert)) | [
"\n Inserts currently chosen completion (p_insert parameter) into proper\n place in edit_text and adjusts cursor position accordingly.\n "
] |
Please provide a description of the function:def _complete(self):
def find_word_start(p_text, 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[... | [
"\n Main completion function.\n\n Gets list of potential completion candidates for currently edited word,\n completes it to the longest common part, and shows convenient completion\n widget (if multiple completions are returned) with currently selected\n candidate highlighted.\n ... |
Please provide a description of the function:def _completion_move(self, p_step, p_size):
current_position = self.completion_box.focus_position
try:
self.completion_box.set_focus(current_position + p_step)
except IndexError:
position = 0 if p_step > 0 else len(se... | [
"\n Visually selects completion specified by p_step (positive numbers\n forwards, negative numbers backwards) and inserts it into edit_text.\n\n If p_step results in value out of range of currently evaluated\n completion candidates, list is rewinded to the start (if cycling\n forw... |
Please provide a description of the function: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 "
] |
Please provide a description of the function:def _end_del(self):
text = self.edit_text[:self.edit_pos]
self.set_edit_text(text) | [
" Deletes the line content after the cursor "
] |
Please provide a description of the function:def add_node(self, p_id):
if not self.has_node(p_id):
self._edges[p_id] = set() | [
" Adds a node to the graph. "
] |
Please provide a description of the function: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._e... | [
"\n Adds an edge to the graph. The nodes will be added if they don't exist.\n\n The p_id is the id of the edge, if the client wishes to maintain this.\n "
] |
Please provide a description of the function: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:
... | [
"\n Returns the set of all neighbors that the given node can reach.\n\n If recursive, it will also return the neighbor's neighbors, etc.\n If reverse, the arrows are reversed and then the reachable neighbors\n are located.\n "
] |
Please provide a description of the function: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. "
] |
Please provide a description of the function: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... | [
" Removes a node from the graph. "
] |
Please provide a description of the function:def is_isolated(self, p_id):
return(len(self.incoming_neighbors(p_id)) == 0
and len(self.outgoing_neighbors(p_id)) == 0) | [
"\n Returns True iff the given node has no incoming or outgoing edges.\n "
] |
Please provide a description of the function: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. "
] |
Please provide a description of the function: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 No... | [
"\n Removes an edge from the graph.\n\n When remove_unconnected_nodes is True, then the nodes are also removed\n if they become isolated.\n "
] |
Please provide a description of the function: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:... | [
"\n Performs a transitive reduction on the graph.\n "
] |
Please provide a description of the function: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 += " {} -> {}".form... | [
" Prints the graph in Dot format. "
] |
Please provide a description of the function:def _filters(self):
filters = super()._filters()
if self.ids:
def get_todo(p_id):
try:
return self.todolist.todo(p_id)
except InvalidTodoException:
... | [
"\n Additional filters to:\n - select particular todo items given with the -i flag,\n - hide appropriately tagged items in the absense of the -x flag.\n ",
"\n Safely obtains a todo item given the user-supplied ID.\n Returns None if an invalid ID w... |
Please provide a description of the function: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(Pretty... | [
"\n Prints the todos in the right format.\n\n Defaults to normal text output (with possible colors and other pretty\n printing). If a format was specified on the commandline, this format is\n sent to the output.\n "
] |
Please provide a description of the function:def _N_lines():
''' Determine how many lines to print, such that the number of items
displayed will fit on the terminal (i.e one 'screen-ful' of items)
This looks at the environmental prompt variable, and tries to determine
how ma... | [] |
Please provide a description of the function:def parse_line(p_string):
result = {
'completed': False,
'completionDate': None,
'priority': None,
'creationDate': None,
'text': "",
'projects': [],
'contexts': [],
'tags': {},
}
completed_head... | [
"\n Parses a single line as can be encountered in a todo.txt file.\n First checks whether the standard elements are present, such as priority,\n creation date, completeness check and the completion date.\n\n Then the rest of the analyzed for any occurrences of contexts, projects or\n tags.\n\n Ret... |
Please provide a description of the function: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... | [
" Generator for date completion. "
] |
Please provide a description of the function: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(compl... | [
"\n Creates proper urwid.Text widgets for all completion candidates from\n p_completions list, and populates them into the items attribute.\n "
] |
Please provide a description of the function: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. "
] |
Please provide a description of the function: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. "
] |
Please provide a description of the function: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. "
] |
Please provide a description of the function: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.gr... | [
"\n Given a date in YYYY-MM-DD, returns a Python date object. Throws a\n ValueError if the date is invalid.\n "
] |
Please provide a description of the function: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 | [
"\n Translates urwid key event to form understandable by topydo config parser.\n "
] |
Please provide a description of the function: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. "
] |
Please provide a description of the function: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)
... | [
"\n Checks if there are any invalid todo IDs in p_ids list.\n\n Returns proper error message if any ID is invalid and None otherwise.\n "
] |
Please provide a description of the function: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(... | [
"\n Executes a command, given as a string.\n "
] |
Please provide a description of the function: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())
... | [
"\n Converts a dictionary describing a view to an actual UIView instance.\n "
] |
Please provide a description of the function: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._ad... | [
" Creates a view from the data entered in the view widget. "
] |
Please provide a description of the function: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_sign... | [
"\n Given an UIView, adds a new column widget with the todos in that view.\n\n When no position is given, it is added to the end, otherwise inserted\n before that position.\n "
] |
Please provide a description of the function: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':
se... | [
"\n Adds p_todo_id to marked_todos attribute and returns True if p_todo_id\n is not already marked. Removes p_todo_id from marked_todos and returns\n False otherwise.\n\n p_force parameter accepting 'mark' or 'unmark' values, if set, can force\n desired action without checking p_t... |
Please provide a description of the function: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. "
] |
Please provide a description of the function:def _convert_priority(p_priority):
result = 0
prio_map = {
'A': 1,
'B': 5,
'C': 6,
'D': 7,
'E': 8,
'F': 9,
}
try:
result = prio_map[p_priority]
except KeyError:
if p_priority:
... | [
"\n Converts todo.txt priority to an iCalendar priority (RFC 2445).\n\n Priority A gets priority 1, priority B gets priority 5 and priority C-F get\n priorities 6-9. This scheme makes sure that clients that use \"high\",\n \"medium\" and \"low\" show the correct priority.\n "
] |
Please provide a description of the function:def _convert_todo(self, p_todo):
def _get_uid(p_todo):
def generate_uid(p_length=4):
return ''.join(
random.choice(string.ascii_letters + string.digits)
for i... | [
" Converts a Todo instance (Topydo) to an icalendar Todo instance. ",
"\n Gets a unique ID from a todo item, stored by the ical tag. If the\n tag is not present, a random value is assigned to it and returned.\n ",
"\n Generates a random string of the given length,... |
Please provide a description of the function:def tag_value(self, p_key, p_default=None):
return self.tag_values(p_key)[0] if p_key in self.fields['tags'] else p_default | [
"\n Returns a tag value associated with p_key. Returns p_default if p_key\n does not exist (which defaults to None).\n "
] |
Please provide a description of the function: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]) | [
"\n Returns true when there is at least one tag with the given key. If a\n value is passed, it will only return true when there exists a tag with\n the given key-value combination.\n "
] |
Please provide a description of the function: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 K... | [
"\n Removes a tag from the internal todo dictionary. Only those instances\n with the given value are removed. If the value is empty, all tags with\n the given key are removed.\n "
] |
Please provide a description of the function: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... | [
"\n Sets a occurrence of the tag identified by p_key. Sets an arbitrary\n instance of the tag when the todo contains multiple tags with this key.\n When p_key does not exist, the tag is added.\n\n When p_value is not set, the tag will be removed.\n\n When p_force_add is true, a ta... |
Please provide a description of the function:def remove_tag(self, p_key, p_value=""):
self._remove_tag_helper(p_key, p_value)
# when value == "", match any value having key p_key
value = p_value if p_value != "" else r'\S+'
self.src = re.sub(r'\s?\b' + p_key + ':' + value + r'\... | [
"\n Removes a tag from the todo.\n When the value is empty (default), all occurrences of the tag will be\n removed.\n Else, only those tags with the value will be removed.\n "
] |
Please provide a description of the function:def tags(self):
tags = self.fields['tags']
return [(t, v) for t in tags for v in tags[t]] | [
"\n Returns a list of tuples with key-value pairs representing tags in\n this todo item.\n "
] |
Please provide a description of the function:def set_priority(self, p_priority):
if not self.is_completed() and (p_priority is None or
is_valid_priority(p_priority)):
self.fields['priority'] = p_priority
priority_str = '' if p_priority is... | [
"\n Sets the priority of the todo. Must be a single capital letter [A-Z],\n or None to unset the priority.\n Priority remains unchanged when an invalid priority is given, or when\n the task was completed.\n "
] |
Please provide a description of the function: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. "
] |
Please provide a description of the function: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... | [
"\n Marks the todo as complete.\n Sets the completed flag and sets the completion date to today.\n "
] |
Please provide a description of the function: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
... | [
"\n Sets the creation date of a todo. Should be passed a date object.\n "
] |
Please provide a description of the function: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:
... | [
"\n Updates the todo list according to the todos in the view associated\n with this list.\n "
] |
Please provide a description of the function: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)
# ... | [
"\n Executes command specified by p_cmd_str on selected todo item.\n\n p_cmd_str should be a string with one replacement field ('{}') which\n will be substituted by id of the selected todo item.\n\n p_execute_signal is the signal name passed to the main loop. It should\n be one of... |
Please provide a description of the function:def resolve_action(self, p_action_str, p_size=None):
if p_action_str.startswith(('cmd ', 'cmdv ')):
prefix, cmd = p_action_str.split(' ', 1)
execute_signal = get_execute_signal(prefix)
if '{}' in cmd:
self... | [
"\n Checks whether action specified in p_action_str is \"built-in\" or\n contains topydo command (i.e. starts with 'cmd') and forwards it to\n proper executing methods.\n\n p_size should be specified for some of the builtin actions like 'up' or\n 'home' as they can interact with u... |
Please provide a description of the function:def execute_builtin_action(self, p_action_str, p_size=None):
column_actions = ['first_column',
'last_column',
'prev_column',
'next_column',
'append_column... | [
"\n Executes built-in action specified in p_action_str.\n\n Currently supported actions are: 'up', 'down', 'home', 'end',\n 'first_column', 'last_column', 'prev_column', 'next_column',\n 'append_column', 'insert_column', 'edit_column', 'delete_column',\n 'copy_column', swap_right'... |
Please provide a description of the function: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... | [
"\n Creates action waiting for execution and forwards it to the mainloop.\n "
] |
Please provide a description of the function:def _postpone_selected(self, p_pattern, p_mode):
if p_pattern.isdigit():
if not self._pp_offset:
self._pp_offset = ''
self._pp_offset += p_pattern
result = None
else:
if p_pattern in ['d... | [
"\n Postpones selected todo item by <COUNT><PERIOD>.\n\n Returns True after 'postpone' command is called (i.e. p_pattern is valid\n <PERIOD>), False when p_pattern is invalid and None if p_pattern is\n digit (i.e. part of <COUNT>).\n\n p_pattern accepts digit (<COUNT>) or one of t... |
Please provide a description of the function: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. "
] |
Please provide a description of the function: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.wr... | [
"\n Writes all the todo items to the todo.txt file.\n\n p_todos can be a list of todo items, or a string that is just written\n to the file.\n "
] |
Please provide a description of the function: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... | [
" Main entry point of the CLI. "
] |
Please provide a description of the function:def _choose(self):
answer = "all"
if not self.force:
for i, value in enumerate(self.current_values):
self.out("{:>2d}. {}".format(i + 1, value))
answer = self.prompt(
'Which value to remove? E... | [
"\n Returns the chosen number of the tag value to process (or \"all\").\n "
] |
Please provide a description of the function:def get_subcommand(p_args):
def import_subcommand(p_subcommand):
classname = SUBCOMMAND_MAP[p_subcommand]
modulename = 'topydo.commands.{}'.format(classname)
__import__(modulename, globals(), locals(), [classname], 0)
return... | [
"\n Retrieves the to-be executed Command and returns a tuple (Command, args).\n\n If args is an empty list, then the Command that corresponds with the\n default command specified in the configuration will be returned.\n\n If the first argument is 'help' and the second a valid subcommand, the\n help t... |
Please provide a description of the function:def is_due_next_monday(p_todo):
today = date.today()
due = p_todo.due_date()
return due and due.weekday() == 0 and today.weekday() >= 4 and \
p_todo.days_till_due() <= 3 | [
" Returns True when today is Friday (or the weekend) and the given task\n is due next Monday.\n "
] |
Please provide a description of the function: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.d... | [
"\n Calculates the importance of the given task.\n Returns an importance of zero when the task has been completed.\n\n If p_ignore_weekend is True, the importance value of the due date will be\n calculated as if Friday is immediately followed by Monday. This in case of\n a todo list at the office and... |
Please provide a description of the function:def _needs_dependencies(p_function):
def build_dependency_information(p_todolist):
for todo in p_todolist._todos:
p_todolist._register_todo(todo)
def inner(self, *args, **kwargs):
if not self._initialized:
self._initializ... | [
"\n A decorator that triggers the population of the dependency tree in a\n TodoList (and other administration). The decorator should be applied to\n methods of TodoList that require dependency information.\n "
] |
Please provide a description of the function: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 ... | [
"\n Makes sure that the dependency graph is consistent according to the\n given todo.\n "
] |
Please provide a description of the function:def delete(self, p_todo, p_leave_tags=False):
try:
number = self._todos.index(p_todo)
if p_todo.has_tag('id'):
for child in self.children(p_todo):
self.remove_dependency(p_todo, child, p_leave_tags... | [
" Deletes a todo item from the list. "
] |
Please provide a description of the function:def add_dependency(self, p_from_todo, p_to_todo):
def find_next_id():
def id_exists(p_id):
for todo in self._todos:
number = str(p_id)
if todo.has_tag('id', num... | [
" Adds a dependency from task 1 to task 2. ",
"\n Find a new unused ID.\n Unused means that no task has it as an 'id' value or as a 'p'\n value.\n ",
"\n Returns True if there exists a todo with the given parent ID.\n ",
"\n ... |
Please provide a description of the function: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 dangli... | [
" Removes a dependency between two todos. "
] |
Please provide a description of the function:def parents(self, p_todo, p_only_direct=False):
parents = self._depgraph.incoming_neighbors(
hash(p_todo), not p_only_direct)
return [self._tododict[parent] for parent in parents] | [
"\n Returns a list of parent todos that (in)directly depend on the\n given todo.\n "
] |
Please provide a description of the function:def children(self, p_todo, p_only_direct=False):
children = \
self._depgraph.outgoing_neighbors(hash(p_todo), not p_only_direct)
return [self._tododict[child] for child in children] | [
"\n Returns a list of child todos that the given todo (in)directly depends\n on.\n "
] |
Please provide a description of the function:def clean_dependencies(self):
def remove_tag(p_todo, p_tag, p_value):
p_todo.remove_tag(p_tag, p_value)
self.dirty = True
def clean_parent_relations():
for todo in [todo for todo in self... | [
"\n Cleans the dependency graph.\n\n This is achieved by performing a transitive reduction on the dependency\n graph and removing unused dependency ids from the graph (in that\n order).\n ",
"\n Removes a tag from a todo item.\n ",
"\n Remove i... |
Please provide a description of the function: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_c... | [
" Converts a Todo instance to a dictionary. "
] |
Please provide a description of the function: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 "
] |
Please provide a description of the function: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 = {} | [
"\n Reads backup file from json_file property and sets backup_dict property\n with data decompressed and deserialized from that file. If no usable\n data is found backup_dict is set to the empty dict.\n "
] |
Please provide a description of the function: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) | [
"\n Writes data from backup_dict property in serialized and compressed form\n to backup file pointed in json_file property.\n "
] |
Please provide a description of the function: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)
... | [
"\n Saves a tuple with archive, todolist and command with its arguments\n into the backup file with unix timestamp as the key. Tuple is then\n indexed in backup file with combination of hash calculated from\n p_todolist and unix timestamp. Backup file is closed afterwards.\n "
] |
Please provide a description of the function: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(times... | [
" Removes backup from the backup file. "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.