id
int32 0
252k
| repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
|
|---|---|---|---|---|---|---|---|---|---|---|---|
11,500
|
bram85/topydo
|
topydo/lib/printers/PrettyPrinter.py
|
PrettyPrinter.print_todo
|
def print_todo(self, p_todo):
""" Given a todo item, pretty print it. """
todo_str = p_todo.source()
for ppf in self.filters:
todo_str = ppf.filter(todo_str, p_todo)
return TopydoString(todo_str)
|
python
|
def print_todo(self, p_todo):
""" Given a todo item, pretty print it. """
todo_str = p_todo.source()
for ppf in self.filters:
todo_str = ppf.filter(todo_str, p_todo)
return TopydoString(todo_str)
|
[
"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.
|
[
"Given",
"a",
"todo",
"item",
"pretty",
"print",
"it",
"."
] |
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/printers/PrettyPrinter.py#L72-L79
|
11,501
|
bram85/topydo
|
topydo/lib/Sorter.py
|
Sorter.group
|
def group(self, p_todos):
"""
Groups the todos according to the given group string.
"""
# 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
|
python
|
def group(self, p_todos):
"""
Groups the todos according to the given group string.
"""
# 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
|
[
"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.
|
[
"Groups",
"the",
"todos",
"according",
"to",
"the",
"given",
"group",
"string",
"."
] |
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/Sorter.py#L237-L270
|
11,502
|
bram85/topydo
|
topydo/lib/ListFormat.py
|
_strip_placeholder_braces
|
def _strip_placeholder_braces(p_matchobj):
"""
Returns string with conditional braces around placeholder stripped and
percent sign glued into placeholder character.
Returned string is composed from 'start', 'before', 'placeholder', 'after',
'whitespace', and 'end' match-groups of p_matchobj. Conditional braces are
stripped from 'before' and 'after' groups. 'whitespace', 'start', and 'end'
groups are preserved without any change.
Using this function as an 'repl' argument in re.sub it is possible to turn:
%{(}B{)}
into:
(%B)
"""
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
|
python
|
def _strip_placeholder_braces(p_matchobj):
"""
Returns string with conditional braces around placeholder stripped and
percent sign glued into placeholder character.
Returned string is composed from 'start', 'before', 'placeholder', 'after',
'whitespace', and 'end' match-groups of p_matchobj. Conditional braces are
stripped from 'before' and 'after' groups. 'whitespace', 'start', and 'end'
groups are preserved without any change.
Using this function as an 'repl' argument in re.sub it is possible to turn:
%{(}B{)}
into:
(%B)
"""
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
|
[
"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.
Returned string is composed from 'start', 'before', 'placeholder', 'after',
'whitespace', and 'end' match-groups of p_matchobj. Conditional braces are
stripped from 'before' and 'after' groups. 'whitespace', 'start', and 'end'
groups are preserved without any change.
Using this function as an 'repl' argument in re.sub it is possible to turn:
%{(}B{)}
into:
(%B)
|
[
"Returns",
"string",
"with",
"conditional",
"braces",
"around",
"placeholder",
"stripped",
"and",
"percent",
"sign",
"glued",
"into",
"placeholder",
"character",
"."
] |
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/ListFormat.py#L65-L85
|
11,503
|
bram85/topydo
|
topydo/lib/ListFormat.py
|
_truncate
|
def _truncate(p_str, p_repl):
"""
Returns p_str with truncated and ended with '...' version of p_repl.
Place of the truncation is calculated depending on p_max_width.
"""
# 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
|
python
|
def _truncate(p_str, p_repl):
"""
Returns p_str with truncated and ended with '...' version of p_repl.
Place of the truncation is calculated depending on p_max_width.
"""
# 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
|
[
"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.
Place of the truncation is calculated depending on p_max_width.
|
[
"Returns",
"p_str",
"with",
"truncated",
"and",
"ended",
"with",
"...",
"version",
"of",
"p_repl",
"."
] |
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/ListFormat.py#L99-L109
|
11,504
|
bram85/topydo
|
topydo/lib/ListFormat.py
|
ListFormatParser._preprocess_format
|
def _preprocess_format(self):
"""
Preprocess the format_string attribute.
Splits the format string on each placeholder and returns a list of
tuples containing substring, placeholder name, and function
retrieving content for placeholder (getter).
Relevant placeholder functions (getters) are taken from
'placeholders' attribute which is a dict. If no matching placeholder
is found in 'placeholders' getter is set to None. Getter and
placeholder are also always set to None in first element of the
returned list, because it never contain a real placeholder (read
re.split documentation for further information).
"""
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
|
python
|
def _preprocess_format(self):
"""
Preprocess the format_string attribute.
Splits the format string on each placeholder and returns a list of
tuples containing substring, placeholder name, and function
retrieving content for placeholder (getter).
Relevant placeholder functions (getters) are taken from
'placeholders' attribute which is a dict. If no matching placeholder
is found in 'placeholders' getter is set to None. Getter and
placeholder are also always set to None in first element of the
returned list, because it never contain a real placeholder (read
re.split documentation for further information).
"""
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
|
[
"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.
Splits the format string on each placeholder and returns a list of
tuples containing substring, placeholder name, and function
retrieving content for placeholder (getter).
Relevant placeholder functions (getters) are taken from
'placeholders' attribute which is a dict. If no matching placeholder
is found in 'placeholders' getter is set to None. Getter and
placeholder are also always set to None in first element of the
returned list, because it never contain a real placeholder (read
re.split documentation for further information).
|
[
"Preprocess",
"the",
"format_string",
"attribute",
"."
] |
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/ListFormat.py#L225-L266
|
11,505
|
bram85/topydo
|
topydo/lib/ListFormat.py
|
ListFormatParser.parse
|
def parse(self, p_todo):
"""
Returns fully parsed string from 'format_string' attribute with all
placeholders properly substituted by content obtained from p_todo.
It uses preprocessed form of 'format_string' (result of
ListFormatParser._preprocess_format) stored in 'format_list'
attribute.
"""
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()
|
python
|
def parse(self, p_todo):
"""
Returns fully parsed string from 'format_string' attribute with all
placeholders properly substituted by content obtained from p_todo.
It uses preprocessed form of 'format_string' (result of
ListFormatParser._preprocess_format) stored in 'format_list'
attribute.
"""
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()
|
[
"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.
It uses preprocessed form of 'format_string' (result of
ListFormatParser._preprocess_format) stored in 'format_list'
attribute.
|
[
"Returns",
"fully",
"parsed",
"string",
"from",
"format_string",
"attribute",
"with",
"all",
"placeholders",
"properly",
"substituted",
"by",
"content",
"obtained",
"from",
"p_todo",
"."
] |
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/ListFormat.py#L268-L307
|
11,506
|
bram85/topydo
|
topydo/ui/prompt/Prompt.py
|
PromptApplication._load_file
|
def _load_file(self):
"""
Reads the configured todo.txt file and loads it into the todo list
instance.
"""
self.todolist.erase()
self.todolist.add_list(self.todofile.read())
self.completer = PromptCompleter(self.todolist)
|
python
|
def _load_file(self):
"""
Reads the configured todo.txt file and loads it into the todo list
instance.
"""
self.todolist.erase()
self.todolist.add_list(self.todofile.read())
self.completer = PromptCompleter(self.todolist)
|
[
"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.
|
[
"Reads",
"the",
"configured",
"todo",
".",
"txt",
"file",
"and",
"loads",
"it",
"into",
"the",
"todo",
"list",
"instance",
"."
] |
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/ui/prompt/Prompt.py#L56-L63
|
11,507
|
bram85/topydo
|
topydo/lib/Command.py
|
Command.execute
|
def execute(self):
"""
Execute the command. Intercepts the help subsubcommand to show the help
text.
"""
if self.args and self.argument(0) == "help":
self.error(self.usage() + "\n\n" + self.help())
return False
return True
|
python
|
def execute(self):
"""
Execute the command. Intercepts the help subsubcommand to show the help
text.
"""
if self.args and self.argument(0) == "help":
self.error(self.usage() + "\n\n" + self.help())
return False
return True
|
[
"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.
|
[
"Execute",
"the",
"command",
".",
"Intercepts",
"the",
"help",
"subsubcommand",
"to",
"show",
"the",
"help",
"text",
"."
] |
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/Command.py#L59-L68
|
11,508
|
bram85/topydo
|
topydo/lib/Command.py
|
Command.argument
|
def argument(self, p_number):
""" Retrieves a value from the argument list at the given position. """
try:
return self.args[p_number]
except IndexError as ie:
raise InvalidCommandArgument from ie
|
python
|
def argument(self, p_number):
""" Retrieves a value from the argument list at the given position. """
try:
return self.args[p_number]
except IndexError as ie:
raise InvalidCommandArgument from ie
|
[
"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.
|
[
"Retrieves",
"a",
"value",
"from",
"the",
"argument",
"list",
"at",
"the",
"given",
"position",
"."
] |
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/Command.py#L70-L75
|
11,509
|
bram85/topydo
|
topydo/lib/Config.py
|
config
|
def config(p_path=None, p_overrides=None):
"""
Retrieve the config instance.
If a path is given, the instance is overwritten by the one that supplies an
additional filename (for testability). Moreover, no other configuration
files will be read when a path is given.
Overrides will discard a setting in any configuration file and use the
passed value instead. Structure: (section, option) => value
The previous configuration instance will be discarded.
"""
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
|
python
|
def config(p_path=None, p_overrides=None):
"""
Retrieve the config instance.
If a path is given, the instance is overwritten by the one that supplies an
additional filename (for testability). Moreover, no other configuration
files will be read when a path is given.
Overrides will discard a setting in any configuration file and use the
passed value instead. Structure: (section, option) => value
The previous configuration instance will be discarded.
"""
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
|
[
"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.
If a path is given, the instance is overwritten by the one that supplies an
additional filename (for testability). Moreover, no other configuration
files will be read when a path is given.
Overrides will discard a setting in any configuration file and use the
passed value instead. Structure: (section, option) => value
The previous configuration instance will be discarded.
|
[
"Retrieve",
"the",
"config",
"instance",
"."
] |
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/Config.py#L486-L504
|
11,510
|
bram85/topydo
|
topydo/lib/Config.py
|
_Config.colors
|
def colors(self, p_hint_possible=True):
"""
Returns 0, 16 or 256 representing the number of colors that should be
used in the output.
A hint can be passed whether the device that will output the text
supports colors.
"""
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
|
python
|
def colors(self, p_hint_possible=True):
"""
Returns 0, 16 or 256 representing the number of colors that should be
used in the output.
A hint can be passed whether the device that will output the text
supports colors.
"""
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
|
[
"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.
A hint can be passed whether the device that will output the text
supports colors.
|
[
"Returns",
"0",
"16",
"or",
"256",
"representing",
"the",
"number",
"of",
"colors",
"that",
"should",
"be",
"used",
"in",
"the",
"output",
"."
] |
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/Config.py#L209-L243
|
11,511
|
bram85/topydo
|
topydo/lib/Config.py
|
_Config.hidden_tags
|
def hidden_tags(self):
""" Returns a list of tags to be hidden from the 'ls' output. """
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(',')]
|
python
|
def hidden_tags(self):
""" Returns a list of tags to be hidden from the 'ls' output. """
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(',')]
|
[
"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.
|
[
"Returns",
"a",
"list",
"of",
"tags",
"to",
"be",
"hidden",
"from",
"the",
"ls",
"output",
"."
] |
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/Config.py#L322-L327
|
11,512
|
bram85/topydo
|
topydo/lib/Config.py
|
_Config.hidden_item_tags
|
def hidden_item_tags(self):
""" Returns a list of tags which hide an item from the 'ls' output. """
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(',')]
|
python
|
def hidden_item_tags(self):
""" Returns a list of tags which hide an item from the 'ls' output. """
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(',')]
|
[
"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.
|
[
"Returns",
"a",
"list",
"of",
"tags",
"which",
"hide",
"an",
"item",
"from",
"the",
"ls",
"output",
"."
] |
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/Config.py#L329-L334
|
11,513
|
bram85/topydo
|
topydo/lib/Config.py
|
_Config.priority_color
|
def priority_color(self, p_priority):
"""
Returns a dict with priorities as keys and color numbers as value.
"""
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')
|
python
|
def priority_color(self, p_priority):
"""
Returns a dict with priorities as keys and color numbers as value.
"""
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')
|
[
"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.
|
[
"Returns",
"a",
"dict",
"with",
"priorities",
"as",
"keys",
"and",
"color",
"numbers",
"as",
"value",
"."
] |
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/Config.py#L337-L359
|
11,514
|
bram85/topydo
|
topydo/lib/Config.py
|
_Config.aliases
|
def aliases(self):
"""
Returns dict with aliases names as keys and pairs of actual
subcommand and alias args as values.
"""
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
|
python
|
def aliases(self):
"""
Returns dict with aliases names as keys and pairs of actual
subcommand and alias args as values.
"""
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
|
[
"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.
|
[
"Returns",
"dict",
"with",
"aliases",
"names",
"as",
"keys",
"and",
"pairs",
"of",
"actual",
"subcommand",
"and",
"alias",
"args",
"as",
"values",
"."
] |
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/Config.py#L404-L421
|
11,515
|
bram85/topydo
|
topydo/lib/Config.py
|
_Config.column_keymap
|
def column_keymap(self):
""" Returns keymap and keystates used in column mode """
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)
|
python
|
def column_keymap(self):
""" Returns keymap and keystates used in column mode """
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)
|
[
"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
|
[
"Returns",
"keymap",
"and",
"keystates",
"used",
"in",
"column",
"mode"
] |
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/Config.py#L440-L460
|
11,516
|
bram85/topydo
|
topydo/lib/Config.py
|
_Config.editor
|
def editor(self):
"""
Returns the editor to invoke. It returns a list with the command in
the first position and its arguments in the remainder.
"""
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)
|
python
|
def editor(self):
"""
Returns the editor to invoke. It returns a list with the command in
the first position and its arguments in the remainder.
"""
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)
|
[
"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.
|
[
"Returns",
"the",
"editor",
"to",
"invoke",
".",
"It",
"returns",
"a",
"list",
"with",
"the",
"command",
"in",
"the",
"first",
"position",
"and",
"its",
"arguments",
"in",
"the",
"remainder",
"."
] |
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/Config.py#L462-L477
|
11,517
|
bram85/topydo
|
topydo/commands/AddCommand.py
|
AddCommand.execute
|
def execute(self):
""" Adds a todo item to the list. """
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())
|
python
|
def execute(self):
""" Adds a todo item to the list. """
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())
|
[
"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.
|
[
"Adds",
"a",
"todo",
"item",
"to",
"the",
"list",
"."
] |
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/commands/AddCommand.py#L80-L100
|
11,518
|
bram85/topydo
|
topydo/lib/Recurrence.py
|
advance_recurring_todo
|
def advance_recurring_todo(p_todo, p_offset=None, p_strict=False):
"""
Given a Todo item, return a new instance of a Todo item with the dates
shifted according to the recurrence rule.
Strict means that the real due date is taken as a offset, not today or a
future date to determine the offset.
When the todo item has no due date, then the date is used passed by the
caller (defaulting to today).
When no recurrence tag is present, an exception is raised.
"""
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
|
python
|
def advance_recurring_todo(p_todo, p_offset=None, p_strict=False):
"""
Given a Todo item, return a new instance of a Todo item with the dates
shifted according to the recurrence rule.
Strict means that the real due date is taken as a offset, not today or a
future date to determine the offset.
When the todo item has no due date, then the date is used passed by the
caller (defaulting to today).
When no recurrence tag is present, an exception is raised.
"""
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
|
[
"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.
Strict means that the real due date is taken as a offset, not today or a
future date to determine the offset.
When the todo item has no due date, then the date is used passed by the
caller (defaulting to today).
When no recurrence tag is present, an exception is raised.
|
[
"Given",
"a",
"Todo",
"item",
"return",
"a",
"new",
"instance",
"of",
"a",
"Todo",
"item",
"with",
"the",
"dates",
"shifted",
"according",
"to",
"the",
"recurrence",
"rule",
"."
] |
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/Recurrence.py#L30-L73
|
11,519
|
bram85/topydo
|
topydo/lib/HashListValues.py
|
_get_table_size
|
def _get_table_size(p_alphabet, p_num):
"""
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.
When the alphabet is too little or too large, then _TableSizeException is
raised. Currently an alphabet of 10 to 40 characters is supported.
"""
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')
|
python
|
def _get_table_size(p_alphabet, p_num):
"""
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.
When the alphabet is too little or too large, then _TableSizeException is
raised. Currently an alphabet of 10 to 40 characters is supported.
"""
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')
|
[
"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.
When the alphabet is too little or too large, then _TableSizeException is
raised. Currently an alphabet of 10 to 40 characters is supported.
|
[
"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",
"."
] |
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/HashListValues.py#L79-L96
|
11,520
|
bram85/topydo
|
topydo/lib/HashListValues.py
|
hash_list_values
|
def hash_list_values(p_list, p_key=lambda i: i): # pragma: no branch
"""
Calculates a unique value for each item in the list, these can be used as
identifiers.
The value is based on hashing an item using the p_key function.
Suitable for lists not larger than approx. 16K items.
Returns a tuple with the status and a list of tuples where each item is
combined with the ID.
"""
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
|
python
|
def hash_list_values(p_list, p_key=lambda i: i): # pragma: no branch
"""
Calculates a unique value for each item in the list, these can be used as
identifiers.
The value is based on hashing an item using the p_key function.
Suitable for lists not larger than approx. 16K items.
Returns a tuple with the status and a list of tuples where each item is
combined with the ID.
"""
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
|
[
"def",
"hash_list_values",
"(",
"p_list",
",",
"p_key",
"=",
"lambda",
"i",
":",
"i",
")",
":",
"# pragma: no branch",
"def",
"to_base",
"(",
"p_alphabet",
",",
"p_value",
")",
":",
"\"\"\"\n Converts integer to text ID with characters from the given alphabet.\n\n Based on answer at\n https://stackoverflow.com/questions/1181919/python-base-36-encoding\n \"\"\"",
"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.
The value is based on hashing an item using the p_key function.
Suitable for lists not larger than approx. 16K items.
Returns a tuple with the status and a list of tuples where each item is
combined with the ID.
|
[
"Calculates",
"a",
"unique",
"value",
"for",
"each",
"item",
"in",
"the",
"list",
"these",
"can",
"be",
"used",
"as",
"identifiers",
"."
] |
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/HashListValues.py#L98-L150
|
11,521
|
bram85/topydo
|
topydo/lib/HashListValues.py
|
max_id_length
|
def max_id_length(p_num):
"""
Returns the length of the IDs used, given the number of items that are
assigned an ID. Used for padding in lists.
"""
try:
alphabet = config().identifier_alphabet()
length, _ = _get_table_size(alphabet, p_num)
except _TableSizeException:
length, _ = _get_table_size(_DEFAULT_ALPHABET, p_num)
return length
|
python
|
def max_id_length(p_num):
"""
Returns the length of the IDs used, given the number of items that are
assigned an ID. Used for padding in lists.
"""
try:
alphabet = config().identifier_alphabet()
length, _ = _get_table_size(alphabet, p_num)
except _TableSizeException:
length, _ = _get_table_size(_DEFAULT_ALPHABET, p_num)
return length
|
[
"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.
|
[
"Returns",
"the",
"length",
"of",
"the",
"IDs",
"used",
"given",
"the",
"number",
"of",
"items",
"that",
"are",
"assigned",
"an",
"ID",
".",
"Used",
"for",
"padding",
"in",
"lists",
"."
] |
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/HashListValues.py#L152-L163
|
11,522
|
bram85/topydo
|
topydo/lib/prettyprinters/Colors.py
|
PrettyPrinterColorFilter.filter
|
def filter(self, p_todo_str, p_todo):
""" Applies the colors. """
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
|
python
|
def filter(self, p_todo_str, p_todo):
""" Applies the colors. """
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
|
[
"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.
|
[
"Applies",
"the",
"colors",
"."
] |
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/prettyprinters/Colors.py#L34-L58
|
11,523
|
bram85/topydo
|
topydo/lib/Filter.py
|
get_filter_list
|
def get_filter_list(p_expression):
"""
Returns a list of GrepFilters, OrdinalTagFilters or NegationFilters based
on the given filter expression.
The filter expression is a list of strings.
"""
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
|
python
|
def get_filter_list(p_expression):
"""
Returns a list of GrepFilters, OrdinalTagFilters or NegationFilters based
on the given filter expression.
The filter expression is a list of strings.
"""
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
|
[
"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.
The filter expression is a list of strings.
|
[
"Returns",
"a",
"list",
"of",
"GrepFilters",
"OrdinalTagFilters",
"or",
"NegationFilters",
"based",
"on",
"the",
"given",
"filter",
"expression",
"."
] |
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/Filter.py#L377-L404
|
11,524
|
bram85/topydo
|
topydo/lib/Filter.py
|
DependencyFilter.match
|
def match(self, p_todo):
"""
Returns True when there are no children that are uncompleted yet.
"""
children = self.todolist.children(p_todo)
uncompleted = [todo for todo in children if not todo.is_completed()]
return not uncompleted
|
python
|
def match(self, p_todo):
"""
Returns True when there are no children that are uncompleted yet.
"""
children = self.todolist.children(p_todo)
uncompleted = [todo for todo in children if not todo.is_completed()]
return not uncompleted
|
[
"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.
|
[
"Returns",
"True",
"when",
"there",
"are",
"no",
"children",
"that",
"are",
"uncompleted",
"yet",
"."
] |
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/Filter.py#L135-L142
|
11,525
|
bram85/topydo
|
topydo/lib/Filter.py
|
InstanceFilter.match
|
def match(self, p_todo):
"""
Returns True when p_todo appears in the list of given todos.
"""
try:
self.todos.index(p_todo)
return True
except ValueError:
return False
|
python
|
def match(self, p_todo):
"""
Returns True when p_todo appears in the list of given todos.
"""
try:
self.todos.index(p_todo)
return True
except ValueError:
return False
|
[
"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.
|
[
"Returns",
"True",
"when",
"p_todo",
"appears",
"in",
"the",
"list",
"of",
"given",
"todos",
"."
] |
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/Filter.py#L166-L174
|
11,526
|
bram85/topydo
|
topydo/lib/Filter.py
|
HiddenTagFilter.match
|
def match(self, p_todo):
"""
Returns True when p_todo doesn't have a tag to mark it as hidden.
"""
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
|
python
|
def match(self, p_todo):
"""
Returns True when p_todo doesn't have a tag to mark it as hidden.
"""
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
|
[
"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.
|
[
"Returns",
"True",
"when",
"p_todo",
"doesn",
"t",
"have",
"a",
"tag",
"to",
"mark",
"it",
"as",
"hidden",
"."
] |
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/Filter.py#L186-L196
|
11,527
|
bram85/topydo
|
topydo/lib/Filter.py
|
OrdinalFilter.compare_operands
|
def compare_operands(self, p_operand1, p_operand2):
"""
Returns True if conditional constructed from both operands and
self.operator is valid. Returns False otherwise.
"""
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
|
python
|
def compare_operands(self, p_operand1, p_operand2):
"""
Returns True if conditional constructed from both operands and
self.operator is valid. Returns False otherwise.
"""
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
|
[
"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.
|
[
"Returns",
"True",
"if",
"conditional",
"constructed",
"from",
"both",
"operands",
"and",
"self",
".",
"operator",
"is",
"valid",
".",
"Returns",
"False",
"otherwise",
"."
] |
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/Filter.py#L232-L250
|
11,528
|
bram85/topydo
|
topydo/lib/Filter.py
|
PriorityFilter.match
|
def match(self, p_todo):
"""
Performs a match on a priority in the todo.
It gets priority from p_todo and compares it with user-entered
expression based on the given operator (default ==). It does that however
in reversed order to obtain more intuitive result. Example: (>B) will
match todos with priority (A).
Items without priority are designated with corresponding operand set to
'ZZ', because python doesn't allow NoneType() and str() comparisons.
"""
operand1 = self.value
operand2 = p_todo.priority() or 'ZZ'
return self.compare_operands(operand1, operand2)
|
python
|
def match(self, p_todo):
"""
Performs a match on a priority in the todo.
It gets priority from p_todo and compares it with user-entered
expression based on the given operator (default ==). It does that however
in reversed order to obtain more intuitive result. Example: (>B) will
match todos with priority (A).
Items without priority are designated with corresponding operand set to
'ZZ', because python doesn't allow NoneType() and str() comparisons.
"""
operand1 = self.value
operand2 = p_todo.priority() or 'ZZ'
return self.compare_operands(operand1, operand2)
|
[
"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.
It gets priority from p_todo and compares it with user-entered
expression based on the given operator (default ==). It does that however
in reversed order to obtain more intuitive result. Example: (>B) will
match todos with priority (A).
Items without priority are designated with corresponding operand set to
'ZZ', because python doesn't allow NoneType() and str() comparisons.
|
[
"Performs",
"a",
"match",
"on",
"a",
"priority",
"in",
"the",
"todo",
"."
] |
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/Filter.py#L354-L368
|
11,529
|
bram85/topydo
|
topydo/ui/CompleterBase.py
|
date_suggestions
|
def date_suggestions():
"""
Returns a list of relative date that is presented to the user as auto
complete 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
|
python
|
def date_suggestions():
"""
Returns a list of relative date that is presented to the user as auto
complete 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
|
[
"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.
|
[
"Returns",
"a",
"list",
"of",
"relative",
"date",
"that",
"is",
"presented",
"to",
"the",
"user",
"as",
"auto",
"complete",
"suggestions",
"."
] |
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/ui/CompleterBase.py#L32-L61
|
11,530
|
bram85/topydo
|
topydo/ui/CLIApplicationBase.py
|
write
|
def write(p_file, p_string):
"""
Write p_string to file p_file, trailed by a newline character.
ANSI codes are removed when the file is not a TTY (and colors are
automatically determined).
"""
if not config().colors(p_file.isatty()):
p_string = escape_ansi(p_string)
if p_string:
p_file.write(p_string + "\n")
|
python
|
def write(p_file, p_string):
"""
Write p_string to file p_file, trailed by a newline character.
ANSI codes are removed when the file is not a TTY (and colors are
automatically determined).
"""
if not config().colors(p_file.isatty()):
p_string = escape_ansi(p_string)
if p_string:
p_file.write(p_string + "\n")
|
[
"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.
ANSI codes are removed when the file is not a TTY (and colors are
automatically determined).
|
[
"Write",
"p_string",
"to",
"file",
"p_file",
"trailed",
"by",
"a",
"newline",
"character",
"."
] |
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/ui/CLIApplicationBase.py#L72-L83
|
11,531
|
bram85/topydo
|
topydo/ui/CLIApplicationBase.py
|
lookup_color
|
def lookup_color(p_color):
"""
Converts an AbstractColor to a normal Color. Returns the Color itself
when a normal color is passed.
"""
if not lookup_color.colors:
lookup_color.colors[AbstractColor.NEUTRAL] = Color('NEUTRAL')
lookup_color.colors[AbstractColor.PROJECT] = config().project_color()
lookup_color.colors[AbstractColor.CONTEXT] = config().context_color()
lookup_color.colors[AbstractColor.META] = config().metadata_color()
lookup_color.colors[AbstractColor.LINK] = config().link_color()
try:
return lookup_color.colors[p_color]
except KeyError:
return p_color
|
python
|
def lookup_color(p_color):
"""
Converts an AbstractColor to a normal Color. Returns the Color itself
when a normal color is passed.
"""
if not lookup_color.colors:
lookup_color.colors[AbstractColor.NEUTRAL] = Color('NEUTRAL')
lookup_color.colors[AbstractColor.PROJECT] = config().project_color()
lookup_color.colors[AbstractColor.CONTEXT] = config().context_color()
lookup_color.colors[AbstractColor.META] = config().metadata_color()
lookup_color.colors[AbstractColor.LINK] = config().link_color()
try:
return lookup_color.colors[p_color]
except KeyError:
return p_color
|
[
"def",
"lookup_color",
"(",
"p_color",
")",
":",
"if",
"not",
"lookup_color",
".",
"colors",
":",
"lookup_color",
".",
"colors",
"[",
"AbstractColor",
".",
"NEUTRAL",
"]",
"=",
"Color",
"(",
"'NEUTRAL'",
")",
"lookup_color",
".",
"colors",
"[",
"AbstractColor",
".",
"PROJECT",
"]",
"=",
"config",
"(",
")",
".",
"project_color",
"(",
")",
"lookup_color",
".",
"colors",
"[",
"AbstractColor",
".",
"CONTEXT",
"]",
"=",
"config",
"(",
")",
".",
"context_color",
"(",
")",
"lookup_color",
".",
"colors",
"[",
"AbstractColor",
".",
"META",
"]",
"=",
"config",
"(",
")",
".",
"metadata_color",
"(",
")",
"lookup_color",
".",
"colors",
"[",
"AbstractColor",
".",
"LINK",
"]",
"=",
"config",
"(",
")",
".",
"link_color",
"(",
")",
"try",
":",
"return",
"lookup_color",
".",
"colors",
"[",
"p_color",
"]",
"except",
"KeyError",
":",
"return",
"p_color"
] |
Converts an AbstractColor to a normal Color. Returns the Color itself
when a normal color is passed.
|
[
"Converts",
"an",
"AbstractColor",
"to",
"a",
"normal",
"Color",
".",
"Returns",
"the",
"Color",
"itself",
"when",
"a",
"normal",
"color",
"is",
"passed",
"."
] |
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/ui/CLIApplicationBase.py#L86-L101
|
11,532
|
bram85/topydo
|
topydo/ui/CLIApplicationBase.py
|
insert_ansi
|
def insert_ansi(p_string):
""" Returns a string with color information at the right positions. """
result = p_string.data
for pos, color in sorted(p_string.colors.items(), reverse=True):
color = lookup_color(color)
result = result[:pos] + color.as_ansi() + result[pos:]
return result
|
python
|
def insert_ansi(p_string):
""" Returns a string with color information at the right positions. """
result = p_string.data
for pos, color in sorted(p_string.colors.items(), reverse=True):
color = lookup_color(color)
result = result[:pos] + color.as_ansi() + result[pos:]
return result
|
[
"def",
"insert_ansi",
"(",
"p_string",
")",
":",
"result",
"=",
"p_string",
".",
"data",
"for",
"pos",
",",
"color",
"in",
"sorted",
"(",
"p_string",
".",
"colors",
".",
"items",
"(",
")",
",",
"reverse",
"=",
"True",
")",
":",
"color",
"=",
"lookup_color",
"(",
"color",
")",
"result",
"=",
"result",
"[",
":",
"pos",
"]",
"+",
"color",
".",
"as_ansi",
"(",
")",
"+",
"result",
"[",
"pos",
":",
"]",
"return",
"result"
] |
Returns a string with color information at the right positions.
|
[
"Returns",
"a",
"string",
"with",
"color",
"information",
"at",
"the",
"right",
"positions",
"."
] |
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/ui/CLIApplicationBase.py#L105-L114
|
11,533
|
bram85/topydo
|
topydo/ui/CLIApplicationBase.py
|
version
|
def version():
""" Print the current version and exit. """
from topydo.lib.Version import VERSION, LICENSE
print("topydo {}\n".format(VERSION))
print(LICENSE)
sys.exit(0)
|
python
|
def version():
""" Print the current version and exit. """
from topydo.lib.Version import VERSION, LICENSE
print("topydo {}\n".format(VERSION))
print(LICENSE)
sys.exit(0)
|
[
"def",
"version",
"(",
")",
":",
"from",
"topydo",
".",
"lib",
".",
"Version",
"import",
"VERSION",
",",
"LICENSE",
"print",
"(",
"\"topydo {}\\n\"",
".",
"format",
"(",
"VERSION",
")",
")",
"print",
"(",
"LICENSE",
")",
"sys",
".",
"exit",
"(",
"0",
")"
] |
Print the current version and exit.
|
[
"Print",
"the",
"current",
"version",
"and",
"exit",
"."
] |
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/ui/CLIApplicationBase.py#L130-L135
|
11,534
|
bram85/topydo
|
topydo/ui/CLIApplicationBase.py
|
CLIApplicationBase._archive
|
def _archive(self):
"""
Performs an archive action on the todolist.
This means that all completed tasks are moved to the archive file
(defaults to done.txt).
"""
archive, archive_file = _retrieve_archive()
if self.backup:
self.backup.add_archive(archive)
if archive:
from topydo.commands.ArchiveCommand import ArchiveCommand
command = ArchiveCommand(self.todolist, archive)
command.execute()
if archive.dirty:
archive_file.write(archive.print_todos())
|
python
|
def _archive(self):
"""
Performs an archive action on the todolist.
This means that all completed tasks are moved to the archive file
(defaults to done.txt).
"""
archive, archive_file = _retrieve_archive()
if self.backup:
self.backup.add_archive(archive)
if archive:
from topydo.commands.ArchiveCommand import ArchiveCommand
command = ArchiveCommand(self.todolist, archive)
command.execute()
if archive.dirty:
archive_file.write(archive.print_todos())
|
[
"def",
"_archive",
"(",
"self",
")",
":",
"archive",
",",
"archive_file",
"=",
"_retrieve_archive",
"(",
")",
"if",
"self",
".",
"backup",
":",
"self",
".",
"backup",
".",
"add_archive",
"(",
"archive",
")",
"if",
"archive",
":",
"from",
"topydo",
".",
"commands",
".",
"ArchiveCommand",
"import",
"ArchiveCommand",
"command",
"=",
"ArchiveCommand",
"(",
"self",
".",
"todolist",
",",
"archive",
")",
"command",
".",
"execute",
"(",
")",
"if",
"archive",
".",
"dirty",
":",
"archive_file",
".",
"write",
"(",
"archive",
".",
"print_todos",
"(",
")",
")"
] |
Performs an archive action on the todolist.
This means that all completed tasks are moved to the archive file
(defaults to done.txt).
|
[
"Performs",
"an",
"archive",
"action",
"on",
"the",
"todolist",
"."
] |
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/ui/CLIApplicationBase.py#L221-L239
|
11,535
|
bram85/topydo
|
topydo/ui/CLIApplicationBase.py
|
CLIApplicationBase.is_read_only
|
def is_read_only(p_command):
""" Returns True when the given command class is read-only. """
read_only_commands = tuple(cmd for cmd
in ('revert', ) + READ_ONLY_COMMANDS)
return p_command.name() in read_only_commands
|
python
|
def is_read_only(p_command):
""" Returns True when the given command class is read-only. """
read_only_commands = tuple(cmd for cmd
in ('revert', ) + READ_ONLY_COMMANDS)
return p_command.name() in read_only_commands
|
[
"def",
"is_read_only",
"(",
"p_command",
")",
":",
"read_only_commands",
"=",
"tuple",
"(",
"cmd",
"for",
"cmd",
"in",
"(",
"'revert'",
",",
")",
"+",
"READ_ONLY_COMMANDS",
")",
"return",
"p_command",
".",
"name",
"(",
")",
"in",
"read_only_commands"
] |
Returns True when the given command class is read-only.
|
[
"Returns",
"True",
"when",
"the",
"given",
"command",
"class",
"is",
"read",
"-",
"only",
"."
] |
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/ui/CLIApplicationBase.py#L242-L246
|
11,536
|
bram85/topydo
|
topydo/ui/CLIApplicationBase.py
|
CLIApplicationBase._post_execute
|
def _post_execute(self):
"""
Should be called when executing the user requested command has been
completed. It will do some maintenance and write out the final result
to the todo.txt file.
"""
if self.todolist.dirty:
# do not archive when the value of the filename is an empty string
# (i.e. explicitly left empty in the configuration
if self.do_archive and config().archive():
self._archive()
elif config().archive() and self.backup:
archive = _retrieve_archive()[0]
self.backup.add_archive(archive)
self._post_archive_action()
if config().keep_sorted():
from topydo.commands.SortCommand import SortCommand
self._execute(SortCommand, [])
if self.backup:
self.backup.save(self.todolist)
self.todofile.write(self.todolist.print_todos())
self.todolist.dirty = False
self.backup = None
|
python
|
def _post_execute(self):
"""
Should be called when executing the user requested command has been
completed. It will do some maintenance and write out the final result
to the todo.txt file.
"""
if self.todolist.dirty:
# do not archive when the value of the filename is an empty string
# (i.e. explicitly left empty in the configuration
if self.do_archive and config().archive():
self._archive()
elif config().archive() and self.backup:
archive = _retrieve_archive()[0]
self.backup.add_archive(archive)
self._post_archive_action()
if config().keep_sorted():
from topydo.commands.SortCommand import SortCommand
self._execute(SortCommand, [])
if self.backup:
self.backup.save(self.todolist)
self.todofile.write(self.todolist.print_todos())
self.todolist.dirty = False
self.backup = None
|
[
"def",
"_post_execute",
"(",
"self",
")",
":",
"if",
"self",
".",
"todolist",
".",
"dirty",
":",
"# do not archive when the value of the filename is an empty string",
"# (i.e. explicitly left empty in the configuration",
"if",
"self",
".",
"do_archive",
"and",
"config",
"(",
")",
".",
"archive",
"(",
")",
":",
"self",
".",
"_archive",
"(",
")",
"elif",
"config",
"(",
")",
".",
"archive",
"(",
")",
"and",
"self",
".",
"backup",
":",
"archive",
"=",
"_retrieve_archive",
"(",
")",
"[",
"0",
"]",
"self",
".",
"backup",
".",
"add_archive",
"(",
"archive",
")",
"self",
".",
"_post_archive_action",
"(",
")",
"if",
"config",
"(",
")",
".",
"keep_sorted",
"(",
")",
":",
"from",
"topydo",
".",
"commands",
".",
"SortCommand",
"import",
"SortCommand",
"self",
".",
"_execute",
"(",
"SortCommand",
",",
"[",
"]",
")",
"if",
"self",
".",
"backup",
":",
"self",
".",
"backup",
".",
"save",
"(",
"self",
".",
"todolist",
")",
"self",
".",
"todofile",
".",
"write",
"(",
"self",
".",
"todolist",
".",
"print_todos",
"(",
")",
")",
"self",
".",
"todolist",
".",
"dirty",
"=",
"False",
"self",
".",
"backup",
"=",
"None"
] |
Should be called when executing the user requested command has been
completed. It will do some maintenance and write out the final result
to the todo.txt file.
|
[
"Should",
"be",
"called",
"when",
"executing",
"the",
"user",
"requested",
"command",
"has",
"been",
"completed",
".",
"It",
"will",
"do",
"some",
"maintenance",
"and",
"write",
"out",
"the",
"final",
"result",
"to",
"the",
"todo",
".",
"txt",
"file",
"."
] |
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/ui/CLIApplicationBase.py#L277-L305
|
11,537
|
bram85/topydo
|
topydo/lib/Todo.py
|
Todo.get_date
|
def get_date(self, p_tag):
""" Given a date tag, return a date object. """
string = self.tag_value(p_tag)
result = None
try:
result = date_string_to_date(string) if string else None
except ValueError:
pass
return result
|
python
|
def get_date(self, p_tag):
""" Given a date tag, return a date object. """
string = self.tag_value(p_tag)
result = None
try:
result = date_string_to_date(string) if string else None
except ValueError:
pass
return result
|
[
"def",
"get_date",
"(",
"self",
",",
"p_tag",
")",
":",
"string",
"=",
"self",
".",
"tag_value",
"(",
"p_tag",
")",
"result",
"=",
"None",
"try",
":",
"result",
"=",
"date_string_to_date",
"(",
"string",
")",
"if",
"string",
"else",
"None",
"except",
"ValueError",
":",
"pass",
"return",
"result"
] |
Given a date tag, return a date object.
|
[
"Given",
"a",
"date",
"tag",
"return",
"a",
"date",
"object",
"."
] |
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/Todo.py#L38-L48
|
11,538
|
bram85/topydo
|
topydo/lib/Todo.py
|
Todo.is_active
|
def is_active(self):
"""
Returns True when the start date is today or in the past and the
task has not yet been completed.
"""
start = self.start_date()
return not self.is_completed() and (not start or start <= date.today())
|
python
|
def is_active(self):
"""
Returns True when the start date is today or in the past and the
task has not yet been completed.
"""
start = self.start_date()
return not self.is_completed() and (not start or start <= date.today())
|
[
"def",
"is_active",
"(",
"self",
")",
":",
"start",
"=",
"self",
".",
"start_date",
"(",
")",
"return",
"not",
"self",
".",
"is_completed",
"(",
")",
"and",
"(",
"not",
"start",
"or",
"start",
"<=",
"date",
".",
"today",
"(",
")",
")"
] |
Returns True when the start date is today or in the past and the
task has not yet been completed.
|
[
"Returns",
"True",
"when",
"the",
"start",
"date",
"is",
"today",
"or",
"in",
"the",
"past",
"and",
"the",
"task",
"has",
"not",
"yet",
"been",
"completed",
"."
] |
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/Todo.py#L58-L64
|
11,539
|
bram85/topydo
|
topydo/lib/Todo.py
|
Todo.days_till_due
|
def days_till_due(self):
"""
Returns the number of days till the due date. Returns a negative number
of days when the due date is in the past.
Returns 0 when the task has no due date.
"""
due = self.due_date()
if due:
diff = due - date.today()
return diff.days
return 0
|
python
|
def days_till_due(self):
"""
Returns the number of days till the due date. Returns a negative number
of days when the due date is in the past.
Returns 0 when the task has no due date.
"""
due = self.due_date()
if due:
diff = due - date.today()
return diff.days
return 0
|
[
"def",
"days_till_due",
"(",
"self",
")",
":",
"due",
"=",
"self",
".",
"due_date",
"(",
")",
"if",
"due",
":",
"diff",
"=",
"due",
"-",
"date",
".",
"today",
"(",
")",
"return",
"diff",
".",
"days",
"return",
"0"
] |
Returns the number of days till the due date. Returns a negative number
of days when the due date is in the past.
Returns 0 when the task has no due date.
|
[
"Returns",
"the",
"number",
"of",
"days",
"till",
"the",
"due",
"date",
".",
"Returns",
"a",
"negative",
"number",
"of",
"days",
"when",
"the",
"due",
"date",
"is",
"in",
"the",
"past",
".",
"Returns",
"0",
"when",
"the",
"task",
"has",
"no",
"due",
"date",
"."
] |
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/Todo.py#L73-L83
|
11,540
|
bram85/topydo
|
topydo/commands/DepCommand.py
|
DepCommand._handle_ls
|
def _handle_ls(self):
""" Handles the ls subsubcommand. """
try:
arg1 = self.argument(1)
arg2 = self.argument(2)
todos = []
if arg2 == 'to' or arg1 == 'before':
# dep ls 1 to OR dep ls before 1
number = arg1 if arg2 == 'to' else arg2
todo = self.todolist.todo(number)
todos = self.todolist.children(todo)
elif arg1 in {'to', 'after'}:
# dep ls to 1 OR dep ls after 1
number = arg2
todo = self.todolist.todo(number)
todos = self.todolist.parents(todo)
else:
raise InvalidCommandArgument
sorter = Sorter(config().sort_string())
instance_filter = Filter.InstanceFilter(todos)
view = View(sorter, [instance_filter], self.todolist)
self.out(self.printer.print_list(view.todos))
except InvalidTodoException:
self.error("Invalid todo number given.")
except InvalidCommandArgument:
self.error(self.usage())
|
python
|
def _handle_ls(self):
""" Handles the ls subsubcommand. """
try:
arg1 = self.argument(1)
arg2 = self.argument(2)
todos = []
if arg2 == 'to' or arg1 == 'before':
# dep ls 1 to OR dep ls before 1
number = arg1 if arg2 == 'to' else arg2
todo = self.todolist.todo(number)
todos = self.todolist.children(todo)
elif arg1 in {'to', 'after'}:
# dep ls to 1 OR dep ls after 1
number = arg2
todo = self.todolist.todo(number)
todos = self.todolist.parents(todo)
else:
raise InvalidCommandArgument
sorter = Sorter(config().sort_string())
instance_filter = Filter.InstanceFilter(todos)
view = View(sorter, [instance_filter], self.todolist)
self.out(self.printer.print_list(view.todos))
except InvalidTodoException:
self.error("Invalid todo number given.")
except InvalidCommandArgument:
self.error(self.usage())
|
[
"def",
"_handle_ls",
"(",
"self",
")",
":",
"try",
":",
"arg1",
"=",
"self",
".",
"argument",
"(",
"1",
")",
"arg2",
"=",
"self",
".",
"argument",
"(",
"2",
")",
"todos",
"=",
"[",
"]",
"if",
"arg2",
"==",
"'to'",
"or",
"arg1",
"==",
"'before'",
":",
"# dep ls 1 to OR dep ls before 1",
"number",
"=",
"arg1",
"if",
"arg2",
"==",
"'to'",
"else",
"arg2",
"todo",
"=",
"self",
".",
"todolist",
".",
"todo",
"(",
"number",
")",
"todos",
"=",
"self",
".",
"todolist",
".",
"children",
"(",
"todo",
")",
"elif",
"arg1",
"in",
"{",
"'to'",
",",
"'after'",
"}",
":",
"# dep ls to 1 OR dep ls after 1",
"number",
"=",
"arg2",
"todo",
"=",
"self",
".",
"todolist",
".",
"todo",
"(",
"number",
")",
"todos",
"=",
"self",
".",
"todolist",
".",
"parents",
"(",
"todo",
")",
"else",
":",
"raise",
"InvalidCommandArgument",
"sorter",
"=",
"Sorter",
"(",
"config",
"(",
")",
".",
"sort_string",
"(",
")",
")",
"instance_filter",
"=",
"Filter",
".",
"InstanceFilter",
"(",
"todos",
")",
"view",
"=",
"View",
"(",
"sorter",
",",
"[",
"instance_filter",
"]",
",",
"self",
".",
"todolist",
")",
"self",
".",
"out",
"(",
"self",
".",
"printer",
".",
"print_list",
"(",
"view",
".",
"todos",
")",
")",
"except",
"InvalidTodoException",
":",
"self",
".",
"error",
"(",
"\"Invalid todo number given.\"",
")",
"except",
"InvalidCommandArgument",
":",
"self",
".",
"error",
"(",
"self",
".",
"usage",
"(",
")",
")"
] |
Handles the ls subsubcommand.
|
[
"Handles",
"the",
"ls",
"subsubcommand",
"."
] |
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/commands/DepCommand.py#L104-L131
|
11,541
|
bram85/topydo
|
topydo/commands/DepCommand.py
|
DepCommand._handle_dot
|
def _handle_dot(self):
""" Handles the dot subsubcommand. """
self.printer = DotPrinter(self.todolist)
try:
arg = self.argument(1)
todo = self.todolist.todo(arg)
arg = self.argument(1)
todos = set([self.todolist.todo(arg)])
todos |= set(self.todolist.children(todo))
todos |= set(self.todolist.parents(todo))
todos = sorted(todos, key=lambda t: t.text())
self.out(self.printer.print_list(todos))
except InvalidTodoException:
self.error("Invalid todo number given.")
except InvalidCommandArgument:
self.error(self.usage())
|
python
|
def _handle_dot(self):
""" Handles the dot subsubcommand. """
self.printer = DotPrinter(self.todolist)
try:
arg = self.argument(1)
todo = self.todolist.todo(arg)
arg = self.argument(1)
todos = set([self.todolist.todo(arg)])
todos |= set(self.todolist.children(todo))
todos |= set(self.todolist.parents(todo))
todos = sorted(todos, key=lambda t: t.text())
self.out(self.printer.print_list(todos))
except InvalidTodoException:
self.error("Invalid todo number given.")
except InvalidCommandArgument:
self.error(self.usage())
|
[
"def",
"_handle_dot",
"(",
"self",
")",
":",
"self",
".",
"printer",
"=",
"DotPrinter",
"(",
"self",
".",
"todolist",
")",
"try",
":",
"arg",
"=",
"self",
".",
"argument",
"(",
"1",
")",
"todo",
"=",
"self",
".",
"todolist",
".",
"todo",
"(",
"arg",
")",
"arg",
"=",
"self",
".",
"argument",
"(",
"1",
")",
"todos",
"=",
"set",
"(",
"[",
"self",
".",
"todolist",
".",
"todo",
"(",
"arg",
")",
"]",
")",
"todos",
"|=",
"set",
"(",
"self",
".",
"todolist",
".",
"children",
"(",
"todo",
")",
")",
"todos",
"|=",
"set",
"(",
"self",
".",
"todolist",
".",
"parents",
"(",
"todo",
")",
")",
"todos",
"=",
"sorted",
"(",
"todos",
",",
"key",
"=",
"lambda",
"t",
":",
"t",
".",
"text",
"(",
")",
")",
"self",
".",
"out",
"(",
"self",
".",
"printer",
".",
"print_list",
"(",
"todos",
")",
")",
"except",
"InvalidTodoException",
":",
"self",
".",
"error",
"(",
"\"Invalid todo number given.\"",
")",
"except",
"InvalidCommandArgument",
":",
"self",
".",
"error",
"(",
"self",
".",
"usage",
"(",
")",
")"
] |
Handles the dot subsubcommand.
|
[
"Handles",
"the",
"dot",
"subsubcommand",
"."
] |
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/commands/DepCommand.py#L133-L150
|
11,542
|
bram85/topydo
|
topydo/lib/TodoListBase.py
|
TodoListBase.todo
|
def todo(self, p_identifier):
"""
The _todos list has the same order as in the backend store (usually
a todo.txt file. The user refers to the first task as number 1, so use
index 0, etc.
Alternative ways to identify a todo is using a hashed version based on
the todo's text, or a regexp that matches the todo's source. The regexp
match is a fallback.
Returns None when the todo couldn't be found.
"""
result = None
def todo_by_uid(p_identifier):
""" Returns the todo that corresponds to the unique ID. """
result = None
if config().identifiers() == 'text':
try:
result = self._id_todo_map[p_identifier]
except KeyError:
pass # we'll try something else
return result
def todo_by_linenumber(p_identifier):
"""
Attempts to find the todo on the given line number.
When the identifier is a number but has leading zeros, the result
will be None.
"""
result = None
if config().identifiers() != 'text':
try:
if re.match('[1-9]\d*', p_identifier):
# the expression is a string and no leading zeroes,
# treat it as an integer
raise TypeError
except TypeError as te:
try:
result = self._todos[int(p_identifier) - 1]
except (ValueError, IndexError):
raise InvalidTodoException from te
return result
def todo_by_regexp(p_identifier):
"""
Returns the todo that is (uniquely) identified by the given regexp.
If the regexp matches more than one item, no result is returned.
"""
result = None
candidates = Filter.GrepFilter(p_identifier).filter(self._todos)
if len(candidates) == 1:
result = candidates[0]
else:
raise InvalidTodoException
return result
result = todo_by_uid(p_identifier)
if not result:
result = todo_by_linenumber(p_identifier)
if not result:
# convert integer to text so we pass on a valid regex
result = todo_by_regexp(str(p_identifier))
return result
|
python
|
def todo(self, p_identifier):
"""
The _todos list has the same order as in the backend store (usually
a todo.txt file. The user refers to the first task as number 1, so use
index 0, etc.
Alternative ways to identify a todo is using a hashed version based on
the todo's text, or a regexp that matches the todo's source. The regexp
match is a fallback.
Returns None when the todo couldn't be found.
"""
result = None
def todo_by_uid(p_identifier):
""" Returns the todo that corresponds to the unique ID. """
result = None
if config().identifiers() == 'text':
try:
result = self._id_todo_map[p_identifier]
except KeyError:
pass # we'll try something else
return result
def todo_by_linenumber(p_identifier):
"""
Attempts to find the todo on the given line number.
When the identifier is a number but has leading zeros, the result
will be None.
"""
result = None
if config().identifiers() != 'text':
try:
if re.match('[1-9]\d*', p_identifier):
# the expression is a string and no leading zeroes,
# treat it as an integer
raise TypeError
except TypeError as te:
try:
result = self._todos[int(p_identifier) - 1]
except (ValueError, IndexError):
raise InvalidTodoException from te
return result
def todo_by_regexp(p_identifier):
"""
Returns the todo that is (uniquely) identified by the given regexp.
If the regexp matches more than one item, no result is returned.
"""
result = None
candidates = Filter.GrepFilter(p_identifier).filter(self._todos)
if len(candidates) == 1:
result = candidates[0]
else:
raise InvalidTodoException
return result
result = todo_by_uid(p_identifier)
if not result:
result = todo_by_linenumber(p_identifier)
if not result:
# convert integer to text so we pass on a valid regex
result = todo_by_regexp(str(p_identifier))
return result
|
[
"def",
"todo",
"(",
"self",
",",
"p_identifier",
")",
":",
"result",
"=",
"None",
"def",
"todo_by_uid",
"(",
"p_identifier",
")",
":",
"\"\"\" Returns the todo that corresponds to the unique ID. \"\"\"",
"result",
"=",
"None",
"if",
"config",
"(",
")",
".",
"identifiers",
"(",
")",
"==",
"'text'",
":",
"try",
":",
"result",
"=",
"self",
".",
"_id_todo_map",
"[",
"p_identifier",
"]",
"except",
"KeyError",
":",
"pass",
"# we'll try something else",
"return",
"result",
"def",
"todo_by_linenumber",
"(",
"p_identifier",
")",
":",
"\"\"\"\n Attempts to find the todo on the given line number.\n\n When the identifier is a number but has leading zeros, the result\n will be None.\n \"\"\"",
"result",
"=",
"None",
"if",
"config",
"(",
")",
".",
"identifiers",
"(",
")",
"!=",
"'text'",
":",
"try",
":",
"if",
"re",
".",
"match",
"(",
"'[1-9]\\d*'",
",",
"p_identifier",
")",
":",
"# the expression is a string and no leading zeroes,",
"# treat it as an integer",
"raise",
"TypeError",
"except",
"TypeError",
"as",
"te",
":",
"try",
":",
"result",
"=",
"self",
".",
"_todos",
"[",
"int",
"(",
"p_identifier",
")",
"-",
"1",
"]",
"except",
"(",
"ValueError",
",",
"IndexError",
")",
":",
"raise",
"InvalidTodoException",
"from",
"te",
"return",
"result",
"def",
"todo_by_regexp",
"(",
"p_identifier",
")",
":",
"\"\"\"\n Returns the todo that is (uniquely) identified by the given regexp.\n If the regexp matches more than one item, no result is returned.\n \"\"\"",
"result",
"=",
"None",
"candidates",
"=",
"Filter",
".",
"GrepFilter",
"(",
"p_identifier",
")",
".",
"filter",
"(",
"self",
".",
"_todos",
")",
"if",
"len",
"(",
"candidates",
")",
"==",
"1",
":",
"result",
"=",
"candidates",
"[",
"0",
"]",
"else",
":",
"raise",
"InvalidTodoException",
"return",
"result",
"result",
"=",
"todo_by_uid",
"(",
"p_identifier",
")",
"if",
"not",
"result",
":",
"result",
"=",
"todo_by_linenumber",
"(",
"p_identifier",
")",
"if",
"not",
"result",
":",
"# convert integer to text so we pass on a valid regex",
"result",
"=",
"todo_by_regexp",
"(",
"str",
"(",
"p_identifier",
")",
")",
"return",
"result"
] |
The _todos list has the same order as in the backend store (usually
a todo.txt file. The user refers to the first task as number 1, so use
index 0, etc.
Alternative ways to identify a todo is using a hashed version based on
the todo's text, or a regexp that matches the todo's source. The regexp
match is a fallback.
Returns None when the todo couldn't be found.
|
[
"The",
"_todos",
"list",
"has",
"the",
"same",
"order",
"as",
"in",
"the",
"backend",
"store",
"(",
"usually",
"a",
"todo",
".",
"txt",
"file",
".",
"The",
"user",
"refers",
"to",
"the",
"first",
"task",
"as",
"number",
"1",
"so",
"use",
"index",
"0",
"etc",
"."
] |
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/TodoListBase.py#L64-L138
|
11,543
|
bram85/topydo
|
topydo/lib/TodoListBase.py
|
TodoListBase.add
|
def add(self, p_src):
"""
Given a todo string, parse it and put it to the end of the list.
"""
todos = self.add_list([p_src])
return todos[0] if len(todos) else None
|
python
|
def add(self, p_src):
"""
Given a todo string, parse it and put it to the end of the list.
"""
todos = self.add_list([p_src])
return todos[0] if len(todos) else None
|
[
"def",
"add",
"(",
"self",
",",
"p_src",
")",
":",
"todos",
"=",
"self",
".",
"add_list",
"(",
"[",
"p_src",
"]",
")",
"return",
"todos",
"[",
"0",
"]",
"if",
"len",
"(",
"todos",
")",
"else",
"None"
] |
Given a todo string, parse it and put it to the end of the list.
|
[
"Given",
"a",
"todo",
"string",
"parse",
"it",
"and",
"put",
"it",
"to",
"the",
"end",
"of",
"the",
"list",
"."
] |
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/TodoListBase.py#L140-L146
|
11,544
|
bram85/topydo
|
topydo/lib/TodoListBase.py
|
TodoListBase.replace
|
def replace(self, p_todos):
""" Replaces whole todolist with todo objects supplied as p_todos. """
self.erase()
self.add_todos(p_todos)
self.dirty = True
|
python
|
def replace(self, p_todos):
""" Replaces whole todolist with todo objects supplied as p_todos. """
self.erase()
self.add_todos(p_todos)
self.dirty = True
|
[
"def",
"replace",
"(",
"self",
",",
"p_todos",
")",
":",
"self",
".",
"erase",
"(",
")",
"self",
".",
"add_todos",
"(",
"p_todos",
")",
"self",
".",
"dirty",
"=",
"True"
] |
Replaces whole todolist with todo objects supplied as p_todos.
|
[
"Replaces",
"whole",
"todolist",
"with",
"todo",
"objects",
"supplied",
"as",
"p_todos",
"."
] |
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/TodoListBase.py#L181-L185
|
11,545
|
bram85/topydo
|
topydo/lib/TodoListBase.py
|
TodoListBase.append
|
def append(self, p_todo, p_string):
"""
Appends a text to the todo, specified by its number.
The todo will be parsed again, such that tags and projects in de
appended string are processed.
"""
if len(p_string) > 0:
new_text = p_todo.source() + ' ' + p_string
p_todo.set_source_text(new_text)
self._update_todo_ids()
self.dirty = True
|
python
|
def append(self, p_todo, p_string):
"""
Appends a text to the todo, specified by its number.
The todo will be parsed again, such that tags and projects in de
appended string are processed.
"""
if len(p_string) > 0:
new_text = p_todo.source() + ' ' + p_string
p_todo.set_source_text(new_text)
self._update_todo_ids()
self.dirty = True
|
[
"def",
"append",
"(",
"self",
",",
"p_todo",
",",
"p_string",
")",
":",
"if",
"len",
"(",
"p_string",
")",
">",
"0",
":",
"new_text",
"=",
"p_todo",
".",
"source",
"(",
")",
"+",
"' '",
"+",
"p_string",
"p_todo",
".",
"set_source_text",
"(",
"new_text",
")",
"self",
".",
"_update_todo_ids",
"(",
")",
"self",
".",
"dirty",
"=",
"True"
] |
Appends a text to the todo, specified by its number.
The todo will be parsed again, such that tags and projects in de
appended string are processed.
|
[
"Appends",
"a",
"text",
"to",
"the",
"todo",
"specified",
"by",
"its",
"number",
".",
"The",
"todo",
"will",
"be",
"parsed",
"again",
"such",
"that",
"tags",
"and",
"projects",
"in",
"de",
"appended",
"string",
"are",
"processed",
"."
] |
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/TodoListBase.py#L191-L201
|
11,546
|
bram85/topydo
|
topydo/lib/TodoListBase.py
|
TodoListBase.projects
|
def projects(self):
""" Returns a set of all projects in this list. """
result = set()
for todo in self._todos:
projects = todo.projects()
result = result.union(projects)
return result
|
python
|
def projects(self):
""" Returns a set of all projects in this list. """
result = set()
for todo in self._todos:
projects = todo.projects()
result = result.union(projects)
return result
|
[
"def",
"projects",
"(",
"self",
")",
":",
"result",
"=",
"set",
"(",
")",
"for",
"todo",
"in",
"self",
".",
"_todos",
":",
"projects",
"=",
"todo",
".",
"projects",
"(",
")",
"result",
"=",
"result",
".",
"union",
"(",
"projects",
")",
"return",
"result"
] |
Returns a set of all projects in this list.
|
[
"Returns",
"a",
"set",
"of",
"all",
"projects",
"in",
"this",
"list",
"."
] |
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/TodoListBase.py#L203-L210
|
11,547
|
bram85/topydo
|
topydo/lib/TodoListBase.py
|
TodoListBase.contexts
|
def contexts(self):
""" Returns a set of all contexts in this list. """
result = set()
for todo in self._todos:
contexts = todo.contexts()
result = result.union(contexts)
return result
|
python
|
def contexts(self):
""" Returns a set of all contexts in this list. """
result = set()
for todo in self._todos:
contexts = todo.contexts()
result = result.union(contexts)
return result
|
[
"def",
"contexts",
"(",
"self",
")",
":",
"result",
"=",
"set",
"(",
")",
"for",
"todo",
"in",
"self",
".",
"_todos",
":",
"contexts",
"=",
"todo",
".",
"contexts",
"(",
")",
"result",
"=",
"result",
".",
"union",
"(",
"contexts",
")",
"return",
"result"
] |
Returns a set of all contexts in this list.
|
[
"Returns",
"a",
"set",
"of",
"all",
"contexts",
"in",
"this",
"list",
"."
] |
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/TodoListBase.py#L212-L219
|
11,548
|
bram85/topydo
|
topydo/lib/TodoListBase.py
|
TodoListBase.linenumber
|
def linenumber(self, p_todo):
"""
Returns the line number of the todo item.
"""
try:
return self._todos.index(p_todo) + 1
except ValueError as ex:
raise InvalidTodoException from ex
|
python
|
def linenumber(self, p_todo):
"""
Returns the line number of the todo item.
"""
try:
return self._todos.index(p_todo) + 1
except ValueError as ex:
raise InvalidTodoException from ex
|
[
"def",
"linenumber",
"(",
"self",
",",
"p_todo",
")",
":",
"try",
":",
"return",
"self",
".",
"_todos",
".",
"index",
"(",
"p_todo",
")",
"+",
"1",
"except",
"ValueError",
"as",
"ex",
":",
"raise",
"InvalidTodoException",
"from",
"ex"
] |
Returns the line number of the todo item.
|
[
"Returns",
"the",
"line",
"number",
"of",
"the",
"todo",
"item",
"."
] |
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/TodoListBase.py#L251-L258
|
11,549
|
bram85/topydo
|
topydo/lib/TodoListBase.py
|
TodoListBase.uid
|
def uid(self, p_todo):
"""
Returns the unique text-based ID for a todo item.
"""
try:
return self._todo_id_map[p_todo]
except KeyError as ex:
raise InvalidTodoException from ex
|
python
|
def uid(self, p_todo):
"""
Returns the unique text-based ID for a todo item.
"""
try:
return self._todo_id_map[p_todo]
except KeyError as ex:
raise InvalidTodoException from ex
|
[
"def",
"uid",
"(",
"self",
",",
"p_todo",
")",
":",
"try",
":",
"return",
"self",
".",
"_todo_id_map",
"[",
"p_todo",
"]",
"except",
"KeyError",
"as",
"ex",
":",
"raise",
"InvalidTodoException",
"from",
"ex"
] |
Returns the unique text-based ID for a todo item.
|
[
"Returns",
"the",
"unique",
"text",
"-",
"based",
"ID",
"for",
"a",
"todo",
"item",
"."
] |
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/TodoListBase.py#L260-L267
|
11,550
|
bram85/topydo
|
topydo/lib/TodoListBase.py
|
TodoListBase.number
|
def number(self, p_todo):
"""
Returns the line number or text ID of a todo (depends on the
configuration.
"""
if config().identifiers() == "text":
return self.uid(p_todo)
else:
return self.linenumber(p_todo)
|
python
|
def number(self, p_todo):
"""
Returns the line number or text ID of a todo (depends on the
configuration.
"""
if config().identifiers() == "text":
return self.uid(p_todo)
else:
return self.linenumber(p_todo)
|
[
"def",
"number",
"(",
"self",
",",
"p_todo",
")",
":",
"if",
"config",
"(",
")",
".",
"identifiers",
"(",
")",
"==",
"\"text\"",
":",
"return",
"self",
".",
"uid",
"(",
"p_todo",
")",
"else",
":",
"return",
"self",
".",
"linenumber",
"(",
"p_todo",
")"
] |
Returns the line number or text ID of a todo (depends on the
configuration.
|
[
"Returns",
"the",
"line",
"number",
"or",
"text",
"ID",
"of",
"a",
"todo",
"(",
"depends",
"on",
"the",
"configuration",
"."
] |
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/TodoListBase.py#L269-L277
|
11,551
|
bram85/topydo
|
topydo/lib/TodoListBase.py
|
TodoListBase.max_id_length
|
def max_id_length(self):
"""
Returns the maximum length of a todo ID, used for formatting purposes.
"""
if config().identifiers() == "text":
return max_id_length(len(self._todos))
else:
try:
return math.ceil(math.log(len(self._todos), 10))
except ValueError:
return 0
|
python
|
def max_id_length(self):
"""
Returns the maximum length of a todo ID, used for formatting purposes.
"""
if config().identifiers() == "text":
return max_id_length(len(self._todos))
else:
try:
return math.ceil(math.log(len(self._todos), 10))
except ValueError:
return 0
|
[
"def",
"max_id_length",
"(",
"self",
")",
":",
"if",
"config",
"(",
")",
".",
"identifiers",
"(",
")",
"==",
"\"text\"",
":",
"return",
"max_id_length",
"(",
"len",
"(",
"self",
".",
"_todos",
")",
")",
"else",
":",
"try",
":",
"return",
"math",
".",
"ceil",
"(",
"math",
".",
"log",
"(",
"len",
"(",
"self",
".",
"_todos",
")",
",",
"10",
")",
")",
"except",
"ValueError",
":",
"return",
"0"
] |
Returns the maximum length of a todo ID, used for formatting purposes.
|
[
"Returns",
"the",
"maximum",
"length",
"of",
"a",
"todo",
"ID",
"used",
"for",
"formatting",
"purposes",
"."
] |
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/TodoListBase.py#L279-L289
|
11,552
|
bram85/topydo
|
topydo/lib/TodoListBase.py
|
TodoListBase.ids
|
def ids(self):
""" Returns set with all todo IDs. """
if config().identifiers() == 'text':
ids = self._id_todo_map.keys()
else:
ids = [str(i + 1) for i in range(self.count())]
return set(ids)
|
python
|
def ids(self):
""" Returns set with all todo IDs. """
if config().identifiers() == 'text':
ids = self._id_todo_map.keys()
else:
ids = [str(i + 1) for i in range(self.count())]
return set(ids)
|
[
"def",
"ids",
"(",
"self",
")",
":",
"if",
"config",
"(",
")",
".",
"identifiers",
"(",
")",
"==",
"'text'",
":",
"ids",
"=",
"self",
".",
"_id_todo_map",
".",
"keys",
"(",
")",
"else",
":",
"ids",
"=",
"[",
"str",
"(",
"i",
"+",
"1",
")",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"count",
"(",
")",
")",
"]",
"return",
"set",
"(",
"ids",
")"
] |
Returns set with all todo IDs.
|
[
"Returns",
"set",
"with",
"all",
"todo",
"IDs",
"."
] |
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/TodoListBase.py#L313-L319
|
11,553
|
bram85/topydo
|
topydo/ui/columns/Transaction.py
|
Transaction.prepare
|
def prepare(self, p_args):
"""
Prepares list of operations to execute based on p_args, list of
todo items contained in _todo_ids attribute and _subcommand
attribute.
"""
if self._todo_ids:
id_position = p_args.index('{}')
# Not using MultiCommand abilities would make EditCommand awkward
if self._multi:
p_args[id_position:id_position + 1] = self._todo_ids
self._operations.append(p_args)
else:
for todo_id in self._todo_ids:
operation_args = p_args[:]
operation_args[id_position] = todo_id
self._operations.append(operation_args)
else:
self._operations.append(p_args)
self._create_label()
|
python
|
def prepare(self, p_args):
"""
Prepares list of operations to execute based on p_args, list of
todo items contained in _todo_ids attribute and _subcommand
attribute.
"""
if self._todo_ids:
id_position = p_args.index('{}')
# Not using MultiCommand abilities would make EditCommand awkward
if self._multi:
p_args[id_position:id_position + 1] = self._todo_ids
self._operations.append(p_args)
else:
for todo_id in self._todo_ids:
operation_args = p_args[:]
operation_args[id_position] = todo_id
self._operations.append(operation_args)
else:
self._operations.append(p_args)
self._create_label()
|
[
"def",
"prepare",
"(",
"self",
",",
"p_args",
")",
":",
"if",
"self",
".",
"_todo_ids",
":",
"id_position",
"=",
"p_args",
".",
"index",
"(",
"'{}'",
")",
"# Not using MultiCommand abilities would make EditCommand awkward",
"if",
"self",
".",
"_multi",
":",
"p_args",
"[",
"id_position",
":",
"id_position",
"+",
"1",
"]",
"=",
"self",
".",
"_todo_ids",
"self",
".",
"_operations",
".",
"append",
"(",
"p_args",
")",
"else",
":",
"for",
"todo_id",
"in",
"self",
".",
"_todo_ids",
":",
"operation_args",
"=",
"p_args",
"[",
":",
"]",
"operation_args",
"[",
"id_position",
"]",
"=",
"todo_id",
"self",
".",
"_operations",
".",
"append",
"(",
"operation_args",
")",
"else",
":",
"self",
".",
"_operations",
".",
"append",
"(",
"p_args",
")",
"self",
".",
"_create_label",
"(",
")"
] |
Prepares list of operations to execute based on p_args, list of
todo items contained in _todo_ids attribute and _subcommand
attribute.
|
[
"Prepares",
"list",
"of",
"operations",
"to",
"execute",
"based",
"on",
"p_args",
"list",
"of",
"todo",
"items",
"contained",
"in",
"_todo_ids",
"attribute",
"and",
"_subcommand",
"attribute",
"."
] |
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/ui/columns/Transaction.py#L34-L55
|
11,554
|
bram85/topydo
|
topydo/ui/columns/Transaction.py
|
Transaction.execute
|
def execute(self):
"""
Executes each operation from _operations attribute.
"""
last_operation = len(self._operations) - 1
for i, operation in enumerate(self._operations):
command = self._cmd(operation)
if command.execute() is False:
return False
else:
action = command.execute_post_archive_actions
self._post_archive_actions.append(action)
if i == last_operation:
return True
|
python
|
def execute(self):
"""
Executes each operation from _operations attribute.
"""
last_operation = len(self._operations) - 1
for i, operation in enumerate(self._operations):
command = self._cmd(operation)
if command.execute() is False:
return False
else:
action = command.execute_post_archive_actions
self._post_archive_actions.append(action)
if i == last_operation:
return True
|
[
"def",
"execute",
"(",
"self",
")",
":",
"last_operation",
"=",
"len",
"(",
"self",
".",
"_operations",
")",
"-",
"1",
"for",
"i",
",",
"operation",
"in",
"enumerate",
"(",
"self",
".",
"_operations",
")",
":",
"command",
"=",
"self",
".",
"_cmd",
"(",
"operation",
")",
"if",
"command",
".",
"execute",
"(",
")",
"is",
"False",
":",
"return",
"False",
"else",
":",
"action",
"=",
"command",
".",
"execute_post_archive_actions",
"self",
".",
"_post_archive_actions",
".",
"append",
"(",
"action",
")",
"if",
"i",
"==",
"last_operation",
":",
"return",
"True"
] |
Executes each operation from _operations attribute.
|
[
"Executes",
"each",
"operation",
"from",
"_operations",
"attribute",
"."
] |
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/ui/columns/Transaction.py#L66-L81
|
11,555
|
bram85/topydo
|
topydo/lib/RelativeDate.py
|
_add_months
|
def _add_months(p_sourcedate, p_months):
"""
Adds a number of months to the source date.
Takes into account shorter months and leap years and such.
https://stackoverflow.com/questions/4130922/how-to-increment-datetime-month-in-python
"""
month = p_sourcedate.month - 1 + p_months
year = p_sourcedate.year + month // 12
month = month % 12 + 1
day = min(p_sourcedate.day, calendar.monthrange(year, month)[1])
return date(year, month, day)
|
python
|
def _add_months(p_sourcedate, p_months):
"""
Adds a number of months to the source date.
Takes into account shorter months and leap years and such.
https://stackoverflow.com/questions/4130922/how-to-increment-datetime-month-in-python
"""
month = p_sourcedate.month - 1 + p_months
year = p_sourcedate.year + month // 12
month = month % 12 + 1
day = min(p_sourcedate.day, calendar.monthrange(year, month)[1])
return date(year, month, day)
|
[
"def",
"_add_months",
"(",
"p_sourcedate",
",",
"p_months",
")",
":",
"month",
"=",
"p_sourcedate",
".",
"month",
"-",
"1",
"+",
"p_months",
"year",
"=",
"p_sourcedate",
".",
"year",
"+",
"month",
"//",
"12",
"month",
"=",
"month",
"%",
"12",
"+",
"1",
"day",
"=",
"min",
"(",
"p_sourcedate",
".",
"day",
",",
"calendar",
".",
"monthrange",
"(",
"year",
",",
"month",
")",
"[",
"1",
"]",
")",
"return",
"date",
"(",
"year",
",",
"month",
",",
"day",
")"
] |
Adds a number of months to the source date.
Takes into account shorter months and leap years and such.
https://stackoverflow.com/questions/4130922/how-to-increment-datetime-month-in-python
|
[
"Adds",
"a",
"number",
"of",
"months",
"to",
"the",
"source",
"date",
"."
] |
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/RelativeDate.py#L24-L37
|
11,556
|
bram85/topydo
|
topydo/lib/RelativeDate.py
|
_add_business_days
|
def _add_business_days(p_sourcedate, p_bdays):
""" Adds a number of business days to the source date. """
result = p_sourcedate
delta = 1 if p_bdays > 0 else -1
while abs(p_bdays) > 0:
result += timedelta(delta)
weekday = result.weekday()
if weekday >= 5:
continue
p_bdays = p_bdays - 1 if delta > 0 else p_bdays + 1
return result
|
python
|
def _add_business_days(p_sourcedate, p_bdays):
""" Adds a number of business days to the source date. """
result = p_sourcedate
delta = 1 if p_bdays > 0 else -1
while abs(p_bdays) > 0:
result += timedelta(delta)
weekday = result.weekday()
if weekday >= 5:
continue
p_bdays = p_bdays - 1 if delta > 0 else p_bdays + 1
return result
|
[
"def",
"_add_business_days",
"(",
"p_sourcedate",
",",
"p_bdays",
")",
":",
"result",
"=",
"p_sourcedate",
"delta",
"=",
"1",
"if",
"p_bdays",
">",
"0",
"else",
"-",
"1",
"while",
"abs",
"(",
"p_bdays",
")",
">",
"0",
":",
"result",
"+=",
"timedelta",
"(",
"delta",
")",
"weekday",
"=",
"result",
".",
"weekday",
"(",
")",
"if",
"weekday",
">=",
"5",
":",
"continue",
"p_bdays",
"=",
"p_bdays",
"-",
"1",
"if",
"delta",
">",
"0",
"else",
"p_bdays",
"+",
"1",
"return",
"result"
] |
Adds a number of business days to the source date.
|
[
"Adds",
"a",
"number",
"of",
"business",
"days",
"to",
"the",
"source",
"date",
"."
] |
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/RelativeDate.py#L40-L54
|
11,557
|
bram85/topydo
|
topydo/lib/RelativeDate.py
|
_convert_weekday_pattern
|
def _convert_weekday_pattern(p_weekday):
"""
Converts a weekday name to an absolute date.
When today's day of the week is entered, it will return next week's date.
"""
day_value = {
'mo': 0,
'tu': 1,
'we': 2,
'th': 3,
'fr': 4,
'sa': 5,
'su': 6
}
target_day_string = p_weekday[:2].lower()
target_day = day_value[target_day_string]
day = date.today().weekday()
shift = 7 - (day - target_day) % 7
return date.today() + timedelta(shift)
|
python
|
def _convert_weekday_pattern(p_weekday):
"""
Converts a weekday name to an absolute date.
When today's day of the week is entered, it will return next week's date.
"""
day_value = {
'mo': 0,
'tu': 1,
'we': 2,
'th': 3,
'fr': 4,
'sa': 5,
'su': 6
}
target_day_string = p_weekday[:2].lower()
target_day = day_value[target_day_string]
day = date.today().weekday()
shift = 7 - (day - target_day) % 7
return date.today() + timedelta(shift)
|
[
"def",
"_convert_weekday_pattern",
"(",
"p_weekday",
")",
":",
"day_value",
"=",
"{",
"'mo'",
":",
"0",
",",
"'tu'",
":",
"1",
",",
"'we'",
":",
"2",
",",
"'th'",
":",
"3",
",",
"'fr'",
":",
"4",
",",
"'sa'",
":",
"5",
",",
"'su'",
":",
"6",
"}",
"target_day_string",
"=",
"p_weekday",
"[",
":",
"2",
"]",
".",
"lower",
"(",
")",
"target_day",
"=",
"day_value",
"[",
"target_day_string",
"]",
"day",
"=",
"date",
".",
"today",
"(",
")",
".",
"weekday",
"(",
")",
"shift",
"=",
"7",
"-",
"(",
"day",
"-",
"target_day",
")",
"%",
"7",
"return",
"date",
".",
"today",
"(",
")",
"+",
"timedelta",
"(",
"shift",
")"
] |
Converts a weekday name to an absolute date.
When today's day of the week is entered, it will return next week's date.
|
[
"Converts",
"a",
"weekday",
"name",
"to",
"an",
"absolute",
"date",
"."
] |
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/RelativeDate.py#L81-L103
|
11,558
|
bram85/topydo
|
topydo/lib/RelativeDate.py
|
relative_date_to_date
|
def relative_date_to_date(p_date, p_offset=None):
"""
Transforms a relative date into a date object.
The following formats are understood:
* [0-9][dwmy]
* 'yesterday', 'today' or 'tomorrow'
* days of the week (in full or abbreviated)
"""
result = None
p_date = p_date.lower()
p_offset = p_offset or date.today()
relative = re.match('(?P<length>-?[0-9]+)(?P<period>[dwmyb])$',
p_date, re.I)
monday = 'mo(n(day)?)?$'
tuesday = 'tu(e(sday)?)?$'
wednesday = 'we(d(nesday)?)?$'
thursday = 'th(u(rsday)?)?$'
friday = 'fr(i(day)?)?$'
saturday = 'sa(t(urday)?)?$'
sunday = 'su(n(day)?)?$'
weekday = re.match('|'.join(
[monday, tuesday, wednesday, thursday, friday, saturday, sunday]),
p_date)
if relative:
length = relative.group('length')
period = relative.group('period')
result = _convert_pattern(length, period, p_offset)
elif weekday:
result = _convert_weekday_pattern(weekday.group(0))
elif re.match('tod(ay)?$', p_date):
result = _convert_pattern('0', 'd')
elif re.match('tom(orrow)?$', p_date):
result = _convert_pattern('1', 'd')
elif re.match('yes(terday)?$', p_date):
result = _convert_pattern('-1', 'd')
return result
|
python
|
def relative_date_to_date(p_date, p_offset=None):
"""
Transforms a relative date into a date object.
The following formats are understood:
* [0-9][dwmy]
* 'yesterday', 'today' or 'tomorrow'
* days of the week (in full or abbreviated)
"""
result = None
p_date = p_date.lower()
p_offset = p_offset or date.today()
relative = re.match('(?P<length>-?[0-9]+)(?P<period>[dwmyb])$',
p_date, re.I)
monday = 'mo(n(day)?)?$'
tuesday = 'tu(e(sday)?)?$'
wednesday = 'we(d(nesday)?)?$'
thursday = 'th(u(rsday)?)?$'
friday = 'fr(i(day)?)?$'
saturday = 'sa(t(urday)?)?$'
sunday = 'su(n(day)?)?$'
weekday = re.match('|'.join(
[monday, tuesday, wednesday, thursday, friday, saturday, sunday]),
p_date)
if relative:
length = relative.group('length')
period = relative.group('period')
result = _convert_pattern(length, period, p_offset)
elif weekday:
result = _convert_weekday_pattern(weekday.group(0))
elif re.match('tod(ay)?$', p_date):
result = _convert_pattern('0', 'd')
elif re.match('tom(orrow)?$', p_date):
result = _convert_pattern('1', 'd')
elif re.match('yes(terday)?$', p_date):
result = _convert_pattern('-1', 'd')
return result
|
[
"def",
"relative_date_to_date",
"(",
"p_date",
",",
"p_offset",
"=",
"None",
")",
":",
"result",
"=",
"None",
"p_date",
"=",
"p_date",
".",
"lower",
"(",
")",
"p_offset",
"=",
"p_offset",
"or",
"date",
".",
"today",
"(",
")",
"relative",
"=",
"re",
".",
"match",
"(",
"'(?P<length>-?[0-9]+)(?P<period>[dwmyb])$'",
",",
"p_date",
",",
"re",
".",
"I",
")",
"monday",
"=",
"'mo(n(day)?)?$'",
"tuesday",
"=",
"'tu(e(sday)?)?$'",
"wednesday",
"=",
"'we(d(nesday)?)?$'",
"thursday",
"=",
"'th(u(rsday)?)?$'",
"friday",
"=",
"'fr(i(day)?)?$'",
"saturday",
"=",
"'sa(t(urday)?)?$'",
"sunday",
"=",
"'su(n(day)?)?$'",
"weekday",
"=",
"re",
".",
"match",
"(",
"'|'",
".",
"join",
"(",
"[",
"monday",
",",
"tuesday",
",",
"wednesday",
",",
"thursday",
",",
"friday",
",",
"saturday",
",",
"sunday",
"]",
")",
",",
"p_date",
")",
"if",
"relative",
":",
"length",
"=",
"relative",
".",
"group",
"(",
"'length'",
")",
"period",
"=",
"relative",
".",
"group",
"(",
"'period'",
")",
"result",
"=",
"_convert_pattern",
"(",
"length",
",",
"period",
",",
"p_offset",
")",
"elif",
"weekday",
":",
"result",
"=",
"_convert_weekday_pattern",
"(",
"weekday",
".",
"group",
"(",
"0",
")",
")",
"elif",
"re",
".",
"match",
"(",
"'tod(ay)?$'",
",",
"p_date",
")",
":",
"result",
"=",
"_convert_pattern",
"(",
"'0'",
",",
"'d'",
")",
"elif",
"re",
".",
"match",
"(",
"'tom(orrow)?$'",
",",
"p_date",
")",
":",
"result",
"=",
"_convert_pattern",
"(",
"'1'",
",",
"'d'",
")",
"elif",
"re",
".",
"match",
"(",
"'yes(terday)?$'",
",",
"p_date",
")",
":",
"result",
"=",
"_convert_pattern",
"(",
"'-1'",
",",
"'d'",
")",
"return",
"result"
] |
Transforms a relative date into a date object.
The following formats are understood:
* [0-9][dwmy]
* 'yesterday', 'today' or 'tomorrow'
* days of the week (in full or abbreviated)
|
[
"Transforms",
"a",
"relative",
"date",
"into",
"a",
"date",
"object",
"."
] |
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/RelativeDate.py#L106-L152
|
11,559
|
bram85/topydo
|
topydo/lib/prettyprinters/Numbers.py
|
PrettyPrinterNumbers.filter
|
def filter(self, p_todo_str, p_todo):
""" Prepends the number to the todo string. """
return "|{:>3}| {}".format(self.todolist.number(p_todo), p_todo_str)
|
python
|
def filter(self, p_todo_str, p_todo):
""" Prepends the number to the todo string. """
return "|{:>3}| {}".format(self.todolist.number(p_todo), p_todo_str)
|
[
"def",
"filter",
"(",
"self",
",",
"p_todo_str",
",",
"p_todo",
")",
":",
"return",
"\"|{:>3}| {}\"",
".",
"format",
"(",
"self",
".",
"todolist",
".",
"number",
"(",
"p_todo",
")",
",",
"p_todo_str",
")"
] |
Prepends the number to the todo string.
|
[
"Prepends",
"the",
"number",
"to",
"the",
"todo",
"string",
"."
] |
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/prettyprinters/Numbers.py#L29-L31
|
11,560
|
bram85/topydo
|
topydo/lib/WriteCommand.py
|
WriteCommand.postprocess_input_todo
|
def postprocess_input_todo(self, p_todo):
"""
Post-processes a parsed todo when adding it to the list.
* It converts relative dates to absolute ones.
* Automatically inserts a creation date if not present.
* Handles more user-friendly dependencies with before:, partof: and
after: tags
"""
def convert_date(p_tag):
value = p_todo.tag_value(p_tag)
if value:
dateobj = relative_date_to_date(value)
if dateobj:
p_todo.set_tag(p_tag, dateobj.isoformat())
def add_dependencies(p_tag):
for value in p_todo.tag_values(p_tag):
try:
dep = self.todolist.todo(value)
if p_tag == 'after':
self.todolist.add_dependency(p_todo, dep)
elif p_tag == 'before' or p_tag == 'partof':
self.todolist.add_dependency(dep, p_todo)
elif p_tag.startswith('parent'):
for parent in self.todolist.parents(dep):
self.todolist.add_dependency(parent, p_todo)
elif p_tag.startswith('child'):
for child in self.todolist.children(dep):
self.todolist.add_dependency(p_todo, child)
except InvalidTodoException:
pass
p_todo.remove_tag(p_tag, value)
convert_date(config().tag_start())
convert_date(config().tag_due())
keywords = [
'after',
'before',
'child-of',
'childof',
'children-of',
'childrenof',
'parent-of',
'parentof',
'parents-of',
'parentsof',
'partof',
]
for keyword in keywords:
add_dependencies(keyword)
|
python
|
def postprocess_input_todo(self, p_todo):
"""
Post-processes a parsed todo when adding it to the list.
* It converts relative dates to absolute ones.
* Automatically inserts a creation date if not present.
* Handles more user-friendly dependencies with before:, partof: and
after: tags
"""
def convert_date(p_tag):
value = p_todo.tag_value(p_tag)
if value:
dateobj = relative_date_to_date(value)
if dateobj:
p_todo.set_tag(p_tag, dateobj.isoformat())
def add_dependencies(p_tag):
for value in p_todo.tag_values(p_tag):
try:
dep = self.todolist.todo(value)
if p_tag == 'after':
self.todolist.add_dependency(p_todo, dep)
elif p_tag == 'before' or p_tag == 'partof':
self.todolist.add_dependency(dep, p_todo)
elif p_tag.startswith('parent'):
for parent in self.todolist.parents(dep):
self.todolist.add_dependency(parent, p_todo)
elif p_tag.startswith('child'):
for child in self.todolist.children(dep):
self.todolist.add_dependency(p_todo, child)
except InvalidTodoException:
pass
p_todo.remove_tag(p_tag, value)
convert_date(config().tag_start())
convert_date(config().tag_due())
keywords = [
'after',
'before',
'child-of',
'childof',
'children-of',
'childrenof',
'parent-of',
'parentof',
'parents-of',
'parentsof',
'partof',
]
for keyword in keywords:
add_dependencies(keyword)
|
[
"def",
"postprocess_input_todo",
"(",
"self",
",",
"p_todo",
")",
":",
"def",
"convert_date",
"(",
"p_tag",
")",
":",
"value",
"=",
"p_todo",
".",
"tag_value",
"(",
"p_tag",
")",
"if",
"value",
":",
"dateobj",
"=",
"relative_date_to_date",
"(",
"value",
")",
"if",
"dateobj",
":",
"p_todo",
".",
"set_tag",
"(",
"p_tag",
",",
"dateobj",
".",
"isoformat",
"(",
")",
")",
"def",
"add_dependencies",
"(",
"p_tag",
")",
":",
"for",
"value",
"in",
"p_todo",
".",
"tag_values",
"(",
"p_tag",
")",
":",
"try",
":",
"dep",
"=",
"self",
".",
"todolist",
".",
"todo",
"(",
"value",
")",
"if",
"p_tag",
"==",
"'after'",
":",
"self",
".",
"todolist",
".",
"add_dependency",
"(",
"p_todo",
",",
"dep",
")",
"elif",
"p_tag",
"==",
"'before'",
"or",
"p_tag",
"==",
"'partof'",
":",
"self",
".",
"todolist",
".",
"add_dependency",
"(",
"dep",
",",
"p_todo",
")",
"elif",
"p_tag",
".",
"startswith",
"(",
"'parent'",
")",
":",
"for",
"parent",
"in",
"self",
".",
"todolist",
".",
"parents",
"(",
"dep",
")",
":",
"self",
".",
"todolist",
".",
"add_dependency",
"(",
"parent",
",",
"p_todo",
")",
"elif",
"p_tag",
".",
"startswith",
"(",
"'child'",
")",
":",
"for",
"child",
"in",
"self",
".",
"todolist",
".",
"children",
"(",
"dep",
")",
":",
"self",
".",
"todolist",
".",
"add_dependency",
"(",
"p_todo",
",",
"child",
")",
"except",
"InvalidTodoException",
":",
"pass",
"p_todo",
".",
"remove_tag",
"(",
"p_tag",
",",
"value",
")",
"convert_date",
"(",
"config",
"(",
")",
".",
"tag_start",
"(",
")",
")",
"convert_date",
"(",
"config",
"(",
")",
".",
"tag_due",
"(",
")",
")",
"keywords",
"=",
"[",
"'after'",
",",
"'before'",
",",
"'child-of'",
",",
"'childof'",
",",
"'children-of'",
",",
"'childrenof'",
",",
"'parent-of'",
",",
"'parentof'",
",",
"'parents-of'",
",",
"'parentsof'",
",",
"'partof'",
",",
"]",
"for",
"keyword",
"in",
"keywords",
":",
"add_dependencies",
"(",
"keyword",
")"
] |
Post-processes a parsed todo when adding it to the list.
* It converts relative dates to absolute ones.
* Automatically inserts a creation date if not present.
* Handles more user-friendly dependencies with before:, partof: and
after: tags
|
[
"Post",
"-",
"processes",
"a",
"parsed",
"todo",
"when",
"adding",
"it",
"to",
"the",
"list",
"."
] |
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/WriteCommand.py#L22-L77
|
11,561
|
bram85/topydo
|
topydo/ui/columns/ColumnLayout.py
|
columns
|
def columns(p_alt_layout_path=None):
"""
Returns list with complete column configuration dicts.
"""
def _get_column_dict(p_cp, p_column):
column_dict = dict()
filterexpr = p_cp.get(p_column, 'filterexpr')
try:
title = p_cp.get(p_column, 'title')
except NoOptionError:
title = filterexpr
column_dict['title'] = title or 'Yet another column'
column_dict['filterexpr'] = filterexpr
column_dict['sortexpr'] = p_cp.get(p_column, 'sortexpr')
column_dict['groupexpr'] = p_cp.get(p_column, 'groupexpr')
column_dict['show_all'] = p_cp.getboolean(p_column, 'show_all')
return column_dict
defaults = {
'filterexpr': '',
'sortexpr': config().sort_string(),
'groupexpr': config().group_string(),
'show_all': '0',
}
cp = RawConfigParser(defaults, strict=False)
files = [
"topydo_columns.ini",
"topydo_columns.conf",
".topydo_columns",
home_config_path('.topydo_columns'),
home_config_path('.config/topydo/columns'),
"/etc/topydo_columns.conf",
]
if p_alt_layout_path is not None:
files.insert(0, expanduser(p_alt_layout_path))
for filename in files:
if cp.read(filename):
break
column_list = []
for column in cp.sections():
column_list.append(_get_column_dict(cp, column))
return column_list
|
python
|
def columns(p_alt_layout_path=None):
"""
Returns list with complete column configuration dicts.
"""
def _get_column_dict(p_cp, p_column):
column_dict = dict()
filterexpr = p_cp.get(p_column, 'filterexpr')
try:
title = p_cp.get(p_column, 'title')
except NoOptionError:
title = filterexpr
column_dict['title'] = title or 'Yet another column'
column_dict['filterexpr'] = filterexpr
column_dict['sortexpr'] = p_cp.get(p_column, 'sortexpr')
column_dict['groupexpr'] = p_cp.get(p_column, 'groupexpr')
column_dict['show_all'] = p_cp.getboolean(p_column, 'show_all')
return column_dict
defaults = {
'filterexpr': '',
'sortexpr': config().sort_string(),
'groupexpr': config().group_string(),
'show_all': '0',
}
cp = RawConfigParser(defaults, strict=False)
files = [
"topydo_columns.ini",
"topydo_columns.conf",
".topydo_columns",
home_config_path('.topydo_columns'),
home_config_path('.config/topydo/columns'),
"/etc/topydo_columns.conf",
]
if p_alt_layout_path is not None:
files.insert(0, expanduser(p_alt_layout_path))
for filename in files:
if cp.read(filename):
break
column_list = []
for column in cp.sections():
column_list.append(_get_column_dict(cp, column))
return column_list
|
[
"def",
"columns",
"(",
"p_alt_layout_path",
"=",
"None",
")",
":",
"def",
"_get_column_dict",
"(",
"p_cp",
",",
"p_column",
")",
":",
"column_dict",
"=",
"dict",
"(",
")",
"filterexpr",
"=",
"p_cp",
".",
"get",
"(",
"p_column",
",",
"'filterexpr'",
")",
"try",
":",
"title",
"=",
"p_cp",
".",
"get",
"(",
"p_column",
",",
"'title'",
")",
"except",
"NoOptionError",
":",
"title",
"=",
"filterexpr",
"column_dict",
"[",
"'title'",
"]",
"=",
"title",
"or",
"'Yet another column'",
"column_dict",
"[",
"'filterexpr'",
"]",
"=",
"filterexpr",
"column_dict",
"[",
"'sortexpr'",
"]",
"=",
"p_cp",
".",
"get",
"(",
"p_column",
",",
"'sortexpr'",
")",
"column_dict",
"[",
"'groupexpr'",
"]",
"=",
"p_cp",
".",
"get",
"(",
"p_column",
",",
"'groupexpr'",
")",
"column_dict",
"[",
"'show_all'",
"]",
"=",
"p_cp",
".",
"getboolean",
"(",
"p_column",
",",
"'show_all'",
")",
"return",
"column_dict",
"defaults",
"=",
"{",
"'filterexpr'",
":",
"''",
",",
"'sortexpr'",
":",
"config",
"(",
")",
".",
"sort_string",
"(",
")",
",",
"'groupexpr'",
":",
"config",
"(",
")",
".",
"group_string",
"(",
")",
",",
"'show_all'",
":",
"'0'",
",",
"}",
"cp",
"=",
"RawConfigParser",
"(",
"defaults",
",",
"strict",
"=",
"False",
")",
"files",
"=",
"[",
"\"topydo_columns.ini\"",
",",
"\"topydo_columns.conf\"",
",",
"\".topydo_columns\"",
",",
"home_config_path",
"(",
"'.topydo_columns'",
")",
",",
"home_config_path",
"(",
"'.config/topydo/columns'",
")",
",",
"\"/etc/topydo_columns.conf\"",
",",
"]",
"if",
"p_alt_layout_path",
"is",
"not",
"None",
":",
"files",
".",
"insert",
"(",
"0",
",",
"expanduser",
"(",
"p_alt_layout_path",
")",
")",
"for",
"filename",
"in",
"files",
":",
"if",
"cp",
".",
"read",
"(",
"filename",
")",
":",
"break",
"column_list",
"=",
"[",
"]",
"for",
"column",
"in",
"cp",
".",
"sections",
"(",
")",
":",
"column_list",
".",
"append",
"(",
"_get_column_dict",
"(",
"cp",
",",
"column",
")",
")",
"return",
"column_list"
] |
Returns list with complete column configuration dicts.
|
[
"Returns",
"list",
"with",
"complete",
"column",
"configuration",
"dicts",
"."
] |
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/ui/columns/ColumnLayout.py#L23-L73
|
11,562
|
bram85/topydo
|
topydo/lib/DCommand.py
|
DCommand._active_todos
|
def _active_todos(self):
"""
Returns a list of active todos, taking uncompleted subtodos into
account.
The stored length of the todolist is taken into account, to prevent new
todos created by recurrence to pop up as newly activated tasks.
Since these todos pop up at the end of the list, we cut off the list
just before that point.
"""
return [todo for todo in self.todolist.todos()
if not self._uncompleted_children(todo) and todo.is_active()]
|
python
|
def _active_todos(self):
"""
Returns a list of active todos, taking uncompleted subtodos into
account.
The stored length of the todolist is taken into account, to prevent new
todos created by recurrence to pop up as newly activated tasks.
Since these todos pop up at the end of the list, we cut off the list
just before that point.
"""
return [todo for todo in self.todolist.todos()
if not self._uncompleted_children(todo) and todo.is_active()]
|
[
"def",
"_active_todos",
"(",
"self",
")",
":",
"return",
"[",
"todo",
"for",
"todo",
"in",
"self",
".",
"todolist",
".",
"todos",
"(",
")",
"if",
"not",
"self",
".",
"_uncompleted_children",
"(",
"todo",
")",
"and",
"todo",
".",
"is_active",
"(",
")",
"]"
] |
Returns a list of active todos, taking uncompleted subtodos into
account.
The stored length of the todolist is taken into account, to prevent new
todos created by recurrence to pop up as newly activated tasks.
Since these todos pop up at the end of the list, we cut off the list
just before that point.
|
[
"Returns",
"a",
"list",
"of",
"active",
"todos",
"taking",
"uncompleted",
"subtodos",
"into",
"account",
"."
] |
b59fcfca5361869a6b78d4c9808c7c6cd0a18b58
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/DCommand.py#L84-L95
|
11,563
|
indygreg/python-zstandard
|
zstandard/cffi.py
|
ZstdDecompressionReader._decompress_into_buffer
|
def _decompress_into_buffer(self, out_buffer):
"""Decompress available input into an output buffer.
Returns True if data in output buffer should be emitted.
"""
zresult = lib.ZSTD_decompressStream(self._decompressor._dctx,
out_buffer, self._in_buffer)
if self._in_buffer.pos == self._in_buffer.size:
self._in_buffer.src = ffi.NULL
self._in_buffer.pos = 0
self._in_buffer.size = 0
self._source_buffer = None
if not hasattr(self._source, 'read'):
self._finished_input = True
if lib.ZSTD_isError(zresult):
raise ZstdError('zstd decompress error: %s' %
_zstd_error(zresult))
# Emit data if there is data AND either:
# a) output buffer is full (read amount is satisfied)
# b) we're at end of a frame and not in frame spanning mode
return (out_buffer.pos and
(out_buffer.pos == out_buffer.size or
zresult == 0 and not self._read_across_frames))
|
python
|
def _decompress_into_buffer(self, out_buffer):
"""Decompress available input into an output buffer.
Returns True if data in output buffer should be emitted.
"""
zresult = lib.ZSTD_decompressStream(self._decompressor._dctx,
out_buffer, self._in_buffer)
if self._in_buffer.pos == self._in_buffer.size:
self._in_buffer.src = ffi.NULL
self._in_buffer.pos = 0
self._in_buffer.size = 0
self._source_buffer = None
if not hasattr(self._source, 'read'):
self._finished_input = True
if lib.ZSTD_isError(zresult):
raise ZstdError('zstd decompress error: %s' %
_zstd_error(zresult))
# Emit data if there is data AND either:
# a) output buffer is full (read amount is satisfied)
# b) we're at end of a frame and not in frame spanning mode
return (out_buffer.pos and
(out_buffer.pos == out_buffer.size or
zresult == 0 and not self._read_across_frames))
|
[
"def",
"_decompress_into_buffer",
"(",
"self",
",",
"out_buffer",
")",
":",
"zresult",
"=",
"lib",
".",
"ZSTD_decompressStream",
"(",
"self",
".",
"_decompressor",
".",
"_dctx",
",",
"out_buffer",
",",
"self",
".",
"_in_buffer",
")",
"if",
"self",
".",
"_in_buffer",
".",
"pos",
"==",
"self",
".",
"_in_buffer",
".",
"size",
":",
"self",
".",
"_in_buffer",
".",
"src",
"=",
"ffi",
".",
"NULL",
"self",
".",
"_in_buffer",
".",
"pos",
"=",
"0",
"self",
".",
"_in_buffer",
".",
"size",
"=",
"0",
"self",
".",
"_source_buffer",
"=",
"None",
"if",
"not",
"hasattr",
"(",
"self",
".",
"_source",
",",
"'read'",
")",
":",
"self",
".",
"_finished_input",
"=",
"True",
"if",
"lib",
".",
"ZSTD_isError",
"(",
"zresult",
")",
":",
"raise",
"ZstdError",
"(",
"'zstd decompress error: %s'",
"%",
"_zstd_error",
"(",
"zresult",
")",
")",
"# Emit data if there is data AND either:",
"# a) output buffer is full (read amount is satisfied)",
"# b) we're at end of a frame and not in frame spanning mode",
"return",
"(",
"out_buffer",
".",
"pos",
"and",
"(",
"out_buffer",
".",
"pos",
"==",
"out_buffer",
".",
"size",
"or",
"zresult",
"==",
"0",
"and",
"not",
"self",
".",
"_read_across_frames",
")",
")"
] |
Decompress available input into an output buffer.
Returns True if data in output buffer should be emitted.
|
[
"Decompress",
"available",
"input",
"into",
"an",
"output",
"buffer",
"."
] |
74fa5904c3e7df67a4260344bf919356a181487e
|
https://github.com/indygreg/python-zstandard/blob/74fa5904c3e7df67a4260344bf919356a181487e/zstandard/cffi.py#L1864-L1890
|
11,564
|
indygreg/python-zstandard
|
setup_zstd.py
|
get_c_extension
|
def get_c_extension(support_legacy=False, system_zstd=False, name='zstd',
warnings_as_errors=False, root=None):
"""Obtain a distutils.extension.Extension for the C extension.
``support_legacy`` controls whether to compile in legacy zstd format support.
``system_zstd`` controls whether to compile against the system zstd library.
For this to work, the system zstd library and headers must match what
python-zstandard is coded against exactly.
``name`` is the module name of the C extension to produce.
``warnings_as_errors`` controls whether compiler warnings are turned into
compiler errors.
``root`` defines a root path that source should be computed as relative
to. This should be the directory with the main ``setup.py`` that is
being invoked. If not defined, paths will be relative to this file.
"""
actual_root = os.path.abspath(os.path.dirname(__file__))
root = root or actual_root
sources = set([os.path.join(actual_root, p) for p in ext_sources])
if not system_zstd:
sources.update([os.path.join(actual_root, p) for p in zstd_sources])
if support_legacy:
sources.update([os.path.join(actual_root, p)
for p in zstd_sources_legacy])
sources = list(sources)
include_dirs = set([os.path.join(actual_root, d) for d in ext_includes])
if not system_zstd:
include_dirs.update([os.path.join(actual_root, d)
for d in zstd_includes])
if support_legacy:
include_dirs.update([os.path.join(actual_root, d)
for d in zstd_includes_legacy])
include_dirs = list(include_dirs)
depends = [os.path.join(actual_root, p) for p in zstd_depends]
compiler = distutils.ccompiler.new_compiler()
# Needed for MSVC.
if hasattr(compiler, 'initialize'):
compiler.initialize()
if compiler.compiler_type == 'unix':
compiler_type = 'unix'
elif compiler.compiler_type == 'msvc':
compiler_type = 'msvc'
elif compiler.compiler_type == 'mingw32':
compiler_type = 'mingw32'
else:
raise Exception('unhandled compiler type: %s' %
compiler.compiler_type)
extra_args = ['-DZSTD_MULTITHREAD']
if not system_zstd:
extra_args.append('-DZSTDLIB_VISIBILITY=')
extra_args.append('-DZDICTLIB_VISIBILITY=')
extra_args.append('-DZSTDERRORLIB_VISIBILITY=')
if compiler_type == 'unix':
extra_args.append('-fvisibility=hidden')
if not system_zstd and support_legacy:
extra_args.append('-DZSTD_LEGACY_SUPPORT=1')
if warnings_as_errors:
if compiler_type in ('unix', 'mingw32'):
extra_args.append('-Werror')
elif compiler_type == 'msvc':
extra_args.append('/WX')
else:
assert False
libraries = ['zstd'] if system_zstd else []
# Python 3.7 doesn't like absolute paths. So normalize to relative.
sources = [os.path.relpath(p, root) for p in sources]
include_dirs = [os.path.relpath(p, root) for p in include_dirs]
depends = [os.path.relpath(p, root) for p in depends]
# TODO compile with optimizations.
return Extension(name, sources,
include_dirs=include_dirs,
depends=depends,
extra_compile_args=extra_args,
libraries=libraries)
|
python
|
def get_c_extension(support_legacy=False, system_zstd=False, name='zstd',
warnings_as_errors=False, root=None):
"""Obtain a distutils.extension.Extension for the C extension.
``support_legacy`` controls whether to compile in legacy zstd format support.
``system_zstd`` controls whether to compile against the system zstd library.
For this to work, the system zstd library and headers must match what
python-zstandard is coded against exactly.
``name`` is the module name of the C extension to produce.
``warnings_as_errors`` controls whether compiler warnings are turned into
compiler errors.
``root`` defines a root path that source should be computed as relative
to. This should be the directory with the main ``setup.py`` that is
being invoked. If not defined, paths will be relative to this file.
"""
actual_root = os.path.abspath(os.path.dirname(__file__))
root = root or actual_root
sources = set([os.path.join(actual_root, p) for p in ext_sources])
if not system_zstd:
sources.update([os.path.join(actual_root, p) for p in zstd_sources])
if support_legacy:
sources.update([os.path.join(actual_root, p)
for p in zstd_sources_legacy])
sources = list(sources)
include_dirs = set([os.path.join(actual_root, d) for d in ext_includes])
if not system_zstd:
include_dirs.update([os.path.join(actual_root, d)
for d in zstd_includes])
if support_legacy:
include_dirs.update([os.path.join(actual_root, d)
for d in zstd_includes_legacy])
include_dirs = list(include_dirs)
depends = [os.path.join(actual_root, p) for p in zstd_depends]
compiler = distutils.ccompiler.new_compiler()
# Needed for MSVC.
if hasattr(compiler, 'initialize'):
compiler.initialize()
if compiler.compiler_type == 'unix':
compiler_type = 'unix'
elif compiler.compiler_type == 'msvc':
compiler_type = 'msvc'
elif compiler.compiler_type == 'mingw32':
compiler_type = 'mingw32'
else:
raise Exception('unhandled compiler type: %s' %
compiler.compiler_type)
extra_args = ['-DZSTD_MULTITHREAD']
if not system_zstd:
extra_args.append('-DZSTDLIB_VISIBILITY=')
extra_args.append('-DZDICTLIB_VISIBILITY=')
extra_args.append('-DZSTDERRORLIB_VISIBILITY=')
if compiler_type == 'unix':
extra_args.append('-fvisibility=hidden')
if not system_zstd and support_legacy:
extra_args.append('-DZSTD_LEGACY_SUPPORT=1')
if warnings_as_errors:
if compiler_type in ('unix', 'mingw32'):
extra_args.append('-Werror')
elif compiler_type == 'msvc':
extra_args.append('/WX')
else:
assert False
libraries = ['zstd'] if system_zstd else []
# Python 3.7 doesn't like absolute paths. So normalize to relative.
sources = [os.path.relpath(p, root) for p in sources]
include_dirs = [os.path.relpath(p, root) for p in include_dirs]
depends = [os.path.relpath(p, root) for p in depends]
# TODO compile with optimizations.
return Extension(name, sources,
include_dirs=include_dirs,
depends=depends,
extra_compile_args=extra_args,
libraries=libraries)
|
[
"def",
"get_c_extension",
"(",
"support_legacy",
"=",
"False",
",",
"system_zstd",
"=",
"False",
",",
"name",
"=",
"'zstd'",
",",
"warnings_as_errors",
"=",
"False",
",",
"root",
"=",
"None",
")",
":",
"actual_root",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
")",
"root",
"=",
"root",
"or",
"actual_root",
"sources",
"=",
"set",
"(",
"[",
"os",
".",
"path",
".",
"join",
"(",
"actual_root",
",",
"p",
")",
"for",
"p",
"in",
"ext_sources",
"]",
")",
"if",
"not",
"system_zstd",
":",
"sources",
".",
"update",
"(",
"[",
"os",
".",
"path",
".",
"join",
"(",
"actual_root",
",",
"p",
")",
"for",
"p",
"in",
"zstd_sources",
"]",
")",
"if",
"support_legacy",
":",
"sources",
".",
"update",
"(",
"[",
"os",
".",
"path",
".",
"join",
"(",
"actual_root",
",",
"p",
")",
"for",
"p",
"in",
"zstd_sources_legacy",
"]",
")",
"sources",
"=",
"list",
"(",
"sources",
")",
"include_dirs",
"=",
"set",
"(",
"[",
"os",
".",
"path",
".",
"join",
"(",
"actual_root",
",",
"d",
")",
"for",
"d",
"in",
"ext_includes",
"]",
")",
"if",
"not",
"system_zstd",
":",
"include_dirs",
".",
"update",
"(",
"[",
"os",
".",
"path",
".",
"join",
"(",
"actual_root",
",",
"d",
")",
"for",
"d",
"in",
"zstd_includes",
"]",
")",
"if",
"support_legacy",
":",
"include_dirs",
".",
"update",
"(",
"[",
"os",
".",
"path",
".",
"join",
"(",
"actual_root",
",",
"d",
")",
"for",
"d",
"in",
"zstd_includes_legacy",
"]",
")",
"include_dirs",
"=",
"list",
"(",
"include_dirs",
")",
"depends",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"actual_root",
",",
"p",
")",
"for",
"p",
"in",
"zstd_depends",
"]",
"compiler",
"=",
"distutils",
".",
"ccompiler",
".",
"new_compiler",
"(",
")",
"# Needed for MSVC.",
"if",
"hasattr",
"(",
"compiler",
",",
"'initialize'",
")",
":",
"compiler",
".",
"initialize",
"(",
")",
"if",
"compiler",
".",
"compiler_type",
"==",
"'unix'",
":",
"compiler_type",
"=",
"'unix'",
"elif",
"compiler",
".",
"compiler_type",
"==",
"'msvc'",
":",
"compiler_type",
"=",
"'msvc'",
"elif",
"compiler",
".",
"compiler_type",
"==",
"'mingw32'",
":",
"compiler_type",
"=",
"'mingw32'",
"else",
":",
"raise",
"Exception",
"(",
"'unhandled compiler type: %s'",
"%",
"compiler",
".",
"compiler_type",
")",
"extra_args",
"=",
"[",
"'-DZSTD_MULTITHREAD'",
"]",
"if",
"not",
"system_zstd",
":",
"extra_args",
".",
"append",
"(",
"'-DZSTDLIB_VISIBILITY='",
")",
"extra_args",
".",
"append",
"(",
"'-DZDICTLIB_VISIBILITY='",
")",
"extra_args",
".",
"append",
"(",
"'-DZSTDERRORLIB_VISIBILITY='",
")",
"if",
"compiler_type",
"==",
"'unix'",
":",
"extra_args",
".",
"append",
"(",
"'-fvisibility=hidden'",
")",
"if",
"not",
"system_zstd",
"and",
"support_legacy",
":",
"extra_args",
".",
"append",
"(",
"'-DZSTD_LEGACY_SUPPORT=1'",
")",
"if",
"warnings_as_errors",
":",
"if",
"compiler_type",
"in",
"(",
"'unix'",
",",
"'mingw32'",
")",
":",
"extra_args",
".",
"append",
"(",
"'-Werror'",
")",
"elif",
"compiler_type",
"==",
"'msvc'",
":",
"extra_args",
".",
"append",
"(",
"'/WX'",
")",
"else",
":",
"assert",
"False",
"libraries",
"=",
"[",
"'zstd'",
"]",
"if",
"system_zstd",
"else",
"[",
"]",
"# Python 3.7 doesn't like absolute paths. So normalize to relative.",
"sources",
"=",
"[",
"os",
".",
"path",
".",
"relpath",
"(",
"p",
",",
"root",
")",
"for",
"p",
"in",
"sources",
"]",
"include_dirs",
"=",
"[",
"os",
".",
"path",
".",
"relpath",
"(",
"p",
",",
"root",
")",
"for",
"p",
"in",
"include_dirs",
"]",
"depends",
"=",
"[",
"os",
".",
"path",
".",
"relpath",
"(",
"p",
",",
"root",
")",
"for",
"p",
"in",
"depends",
"]",
"# TODO compile with optimizations.",
"return",
"Extension",
"(",
"name",
",",
"sources",
",",
"include_dirs",
"=",
"include_dirs",
",",
"depends",
"=",
"depends",
",",
"extra_compile_args",
"=",
"extra_args",
",",
"libraries",
"=",
"libraries",
")"
] |
Obtain a distutils.extension.Extension for the C extension.
``support_legacy`` controls whether to compile in legacy zstd format support.
``system_zstd`` controls whether to compile against the system zstd library.
For this to work, the system zstd library and headers must match what
python-zstandard is coded against exactly.
``name`` is the module name of the C extension to produce.
``warnings_as_errors`` controls whether compiler warnings are turned into
compiler errors.
``root`` defines a root path that source should be computed as relative
to. This should be the directory with the main ``setup.py`` that is
being invoked. If not defined, paths will be relative to this file.
|
[
"Obtain",
"a",
"distutils",
".",
"extension",
".",
"Extension",
"for",
"the",
"C",
"extension",
"."
] |
74fa5904c3e7df67a4260344bf919356a181487e
|
https://github.com/indygreg/python-zstandard/blob/74fa5904c3e7df67a4260344bf919356a181487e/setup_zstd.py#L100-L190
|
11,565
|
sffjunkie/astral
|
src/astral.py
|
Location.timezone
|
def timezone(self):
"""The name of the time zone for the location.
A list of time zone names can be obtained from pytz. For example.
>>> from pytz import all_timezones
>>> for timezone in all_timezones:
... print(timezone)
"""
if not self._timezone_group and not self._timezone_location:
return None
if self._timezone_location != "":
return "%s/%s" % (self._timezone_group, self._timezone_location)
else:
return self._timezone_group
|
python
|
def timezone(self):
"""The name of the time zone for the location.
A list of time zone names can be obtained from pytz. For example.
>>> from pytz import all_timezones
>>> for timezone in all_timezones:
... print(timezone)
"""
if not self._timezone_group and not self._timezone_location:
return None
if self._timezone_location != "":
return "%s/%s" % (self._timezone_group, self._timezone_location)
else:
return self._timezone_group
|
[
"def",
"timezone",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_timezone_group",
"and",
"not",
"self",
".",
"_timezone_location",
":",
"return",
"None",
"if",
"self",
".",
"_timezone_location",
"!=",
"\"\"",
":",
"return",
"\"%s/%s\"",
"%",
"(",
"self",
".",
"_timezone_group",
",",
"self",
".",
"_timezone_location",
")",
"else",
":",
"return",
"self",
".",
"_timezone_group"
] |
The name of the time zone for the location.
A list of time zone names can be obtained from pytz. For example.
>>> from pytz import all_timezones
>>> for timezone in all_timezones:
... print(timezone)
|
[
"The",
"name",
"of",
"the",
"time",
"zone",
"for",
"the",
"location",
"."
] |
b0aa63fce692357cd33c2bf36c69ed5b6582440c
|
https://github.com/sffjunkie/astral/blob/b0aa63fce692357cd33c2bf36c69ed5b6582440c/src/astral.py#L681-L697
|
11,566
|
sffjunkie/astral
|
src/astral.py
|
Location.tz
|
def tz(self):
"""Time zone information."""
if self.timezone is None:
return None
try:
tz = pytz.timezone(self.timezone)
return tz
except pytz.UnknownTimeZoneError:
raise AstralError("Unknown timezone '%s'" % self.timezone)
|
python
|
def tz(self):
"""Time zone information."""
if self.timezone is None:
return None
try:
tz = pytz.timezone(self.timezone)
return tz
except pytz.UnknownTimeZoneError:
raise AstralError("Unknown timezone '%s'" % self.timezone)
|
[
"def",
"tz",
"(",
"self",
")",
":",
"if",
"self",
".",
"timezone",
"is",
"None",
":",
"return",
"None",
"try",
":",
"tz",
"=",
"pytz",
".",
"timezone",
"(",
"self",
".",
"timezone",
")",
"return",
"tz",
"except",
"pytz",
".",
"UnknownTimeZoneError",
":",
"raise",
"AstralError",
"(",
"\"Unknown timezone '%s'\"",
"%",
"self",
".",
"timezone",
")"
] |
Time zone information.
|
[
"Time",
"zone",
"information",
"."
] |
b0aa63fce692357cd33c2bf36c69ed5b6582440c
|
https://github.com/sffjunkie/astral/blob/b0aa63fce692357cd33c2bf36c69ed5b6582440c/src/astral.py#L716-L726
|
11,567
|
sffjunkie/astral
|
src/astral.py
|
Location.sun
|
def sun(self, date=None, local=True, use_elevation=True):
"""Returns dawn, sunrise, noon, sunset and dusk as a dictionary.
:param date: The date for which to calculate the times.
If no date is specified then the current date will be used.
:type date: :class:`~datetime.date`
:param local: True = Time to be returned in location's time zone;
False = Time to be returned in UTC.
If not specified then the time will be returned in local time
:type local: bool
:param use_elevation: True = Return times that allow for the location's elevation;
False = Return times that don't use elevation.
If not specified then times will take elevation into account.
:type use_elevation: bool
:returns: Dictionary with keys ``dawn``, ``sunrise``, ``noon``,
``sunset`` and ``dusk`` whose values are the results of the
corresponding methods.
:rtype: dict
"""
if local and self.timezone is None:
raise ValueError("Local time requested but Location has no timezone set.")
if self.astral is None:
self.astral = Astral()
if date is None:
date = datetime.date.today()
elevation = self.elevation if use_elevation else 0
sun = self.astral.sun_utc(date, self.latitude, self.longitude, observer_elevation=elevation)
if local:
for key, dt in sun.items():
sun[key] = dt.astimezone(self.tz)
return sun
|
python
|
def sun(self, date=None, local=True, use_elevation=True):
"""Returns dawn, sunrise, noon, sunset and dusk as a dictionary.
:param date: The date for which to calculate the times.
If no date is specified then the current date will be used.
:type date: :class:`~datetime.date`
:param local: True = Time to be returned in location's time zone;
False = Time to be returned in UTC.
If not specified then the time will be returned in local time
:type local: bool
:param use_elevation: True = Return times that allow for the location's elevation;
False = Return times that don't use elevation.
If not specified then times will take elevation into account.
:type use_elevation: bool
:returns: Dictionary with keys ``dawn``, ``sunrise``, ``noon``,
``sunset`` and ``dusk`` whose values are the results of the
corresponding methods.
:rtype: dict
"""
if local and self.timezone is None:
raise ValueError("Local time requested but Location has no timezone set.")
if self.astral is None:
self.astral = Astral()
if date is None:
date = datetime.date.today()
elevation = self.elevation if use_elevation else 0
sun = self.astral.sun_utc(date, self.latitude, self.longitude, observer_elevation=elevation)
if local:
for key, dt in sun.items():
sun[key] = dt.astimezone(self.tz)
return sun
|
[
"def",
"sun",
"(",
"self",
",",
"date",
"=",
"None",
",",
"local",
"=",
"True",
",",
"use_elevation",
"=",
"True",
")",
":",
"if",
"local",
"and",
"self",
".",
"timezone",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Local time requested but Location has no timezone set.\"",
")",
"if",
"self",
".",
"astral",
"is",
"None",
":",
"self",
".",
"astral",
"=",
"Astral",
"(",
")",
"if",
"date",
"is",
"None",
":",
"date",
"=",
"datetime",
".",
"date",
".",
"today",
"(",
")",
"elevation",
"=",
"self",
".",
"elevation",
"if",
"use_elevation",
"else",
"0",
"sun",
"=",
"self",
".",
"astral",
".",
"sun_utc",
"(",
"date",
",",
"self",
".",
"latitude",
",",
"self",
".",
"longitude",
",",
"observer_elevation",
"=",
"elevation",
")",
"if",
"local",
":",
"for",
"key",
",",
"dt",
"in",
"sun",
".",
"items",
"(",
")",
":",
"sun",
"[",
"key",
"]",
"=",
"dt",
".",
"astimezone",
"(",
"self",
".",
"tz",
")",
"return",
"sun"
] |
Returns dawn, sunrise, noon, sunset and dusk as a dictionary.
:param date: The date for which to calculate the times.
If no date is specified then the current date will be used.
:type date: :class:`~datetime.date`
:param local: True = Time to be returned in location's time zone;
False = Time to be returned in UTC.
If not specified then the time will be returned in local time
:type local: bool
:param use_elevation: True = Return times that allow for the location's elevation;
False = Return times that don't use elevation.
If not specified then times will take elevation into account.
:type use_elevation: bool
:returns: Dictionary with keys ``dawn``, ``sunrise``, ``noon``,
``sunset`` and ``dusk`` whose values are the results of the
corresponding methods.
:rtype: dict
|
[
"Returns",
"dawn",
"sunrise",
"noon",
"sunset",
"and",
"dusk",
"as",
"a",
"dictionary",
"."
] |
b0aa63fce692357cd33c2bf36c69ed5b6582440c
|
https://github.com/sffjunkie/astral/blob/b0aa63fce692357cd33c2bf36c69ed5b6582440c/src/astral.py#L756-L795
|
11,568
|
sffjunkie/astral
|
src/astral.py
|
Location.sunrise
|
def sunrise(self, date=None, local=True, use_elevation=True):
"""Return sunrise time.
Calculates the time in the morning when the sun is a 0.833 degrees
below the horizon. This is to account for refraction.
:param date: The date for which to calculate the sunrise time.
If no date is specified then the current date will be used.
:type date: :class:`~datetime.date`
:param local: True = Time to be returned in location's time zone;
False = Time to be returned in UTC.
If not specified then the time will be returned in local time
:type local: bool
:param use_elevation: True = Return times that allow for the location's elevation;
False = Return times that don't use elevation.
If not specified then times will take elevation into account.
:type use_elevation: bool
:returns: The date and time at which sunrise occurs.
:rtype: :class:`~datetime.datetime`
"""
if local and self.timezone is None:
raise ValueError("Local time requested but Location has no timezone set.")
if self.astral is None:
self.astral = Astral()
if date is None:
date = datetime.date.today()
elevation = self.elevation if use_elevation else 0
sunrise = self.astral.sunrise_utc(date, self.latitude, self.longitude, elevation)
if local:
return sunrise.astimezone(self.tz)
else:
return sunrise
|
python
|
def sunrise(self, date=None, local=True, use_elevation=True):
"""Return sunrise time.
Calculates the time in the morning when the sun is a 0.833 degrees
below the horizon. This is to account for refraction.
:param date: The date for which to calculate the sunrise time.
If no date is specified then the current date will be used.
:type date: :class:`~datetime.date`
:param local: True = Time to be returned in location's time zone;
False = Time to be returned in UTC.
If not specified then the time will be returned in local time
:type local: bool
:param use_elevation: True = Return times that allow for the location's elevation;
False = Return times that don't use elevation.
If not specified then times will take elevation into account.
:type use_elevation: bool
:returns: The date and time at which sunrise occurs.
:rtype: :class:`~datetime.datetime`
"""
if local and self.timezone is None:
raise ValueError("Local time requested but Location has no timezone set.")
if self.astral is None:
self.astral = Astral()
if date is None:
date = datetime.date.today()
elevation = self.elevation if use_elevation else 0
sunrise = self.astral.sunrise_utc(date, self.latitude, self.longitude, elevation)
if local:
return sunrise.astimezone(self.tz)
else:
return sunrise
|
[
"def",
"sunrise",
"(",
"self",
",",
"date",
"=",
"None",
",",
"local",
"=",
"True",
",",
"use_elevation",
"=",
"True",
")",
":",
"if",
"local",
"and",
"self",
".",
"timezone",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Local time requested but Location has no timezone set.\"",
")",
"if",
"self",
".",
"astral",
"is",
"None",
":",
"self",
".",
"astral",
"=",
"Astral",
"(",
")",
"if",
"date",
"is",
"None",
":",
"date",
"=",
"datetime",
".",
"date",
".",
"today",
"(",
")",
"elevation",
"=",
"self",
".",
"elevation",
"if",
"use_elevation",
"else",
"0",
"sunrise",
"=",
"self",
".",
"astral",
".",
"sunrise_utc",
"(",
"date",
",",
"self",
".",
"latitude",
",",
"self",
".",
"longitude",
",",
"elevation",
")",
"if",
"local",
":",
"return",
"sunrise",
".",
"astimezone",
"(",
"self",
".",
"tz",
")",
"else",
":",
"return",
"sunrise"
] |
Return sunrise time.
Calculates the time in the morning when the sun is a 0.833 degrees
below the horizon. This is to account for refraction.
:param date: The date for which to calculate the sunrise time.
If no date is specified then the current date will be used.
:type date: :class:`~datetime.date`
:param local: True = Time to be returned in location's time zone;
False = Time to be returned in UTC.
If not specified then the time will be returned in local time
:type local: bool
:param use_elevation: True = Return times that allow for the location's elevation;
False = Return times that don't use elevation.
If not specified then times will take elevation into account.
:type use_elevation: bool
:returns: The date and time at which sunrise occurs.
:rtype: :class:`~datetime.datetime`
|
[
"Return",
"sunrise",
"time",
"."
] |
b0aa63fce692357cd33c2bf36c69ed5b6582440c
|
https://github.com/sffjunkie/astral/blob/b0aa63fce692357cd33c2bf36c69ed5b6582440c/src/astral.py#L837-L876
|
11,569
|
sffjunkie/astral
|
src/astral.py
|
Location.time_at_elevation
|
def time_at_elevation(self, elevation, direction=SUN_RISING, date=None, local=True):
"""Calculate the time when the sun is at the specified elevation.
Note:
This method uses positive elevations for those above the horizon.
Elevations greater than 90 degrees are converted to a setting sun
i.e. an elevation of 110 will calculate a setting sun at 70 degrees.
:param elevation: Elevation in degrees above the horizon to calculate for.
:type elevation: float
:param direction: Determines whether the time is for the sun rising or setting.
Use ``astral.SUN_RISING`` or ``astral.SUN_SETTING``. Default is rising.
:type direction: int
:param date: The date for which to calculate the elevation time.
If no date is specified then the current date will be used.
:type date: :class:`~datetime.date`
:param local: True = Time to be returned in location's time zone;
False = Time to be returned in UTC.
If not specified then the time will be returned in local time
:type local: bool
:returns: The date and time at which dusk occurs.
:rtype: :class:`~datetime.datetime`
"""
if local and self.timezone is None:
raise ValueError("Local time requested but Location has no timezone set.")
if self.astral is None:
self.astral = Astral()
if date is None:
date = datetime.date.today()
if elevation > 90.0:
elevation = 180.0 - elevation
direction = SUN_SETTING
time_ = self.astral.time_at_elevation_utc(
elevation, direction, date, self.latitude, self.longitude
)
if local:
return time_.astimezone(self.tz)
else:
return time_
|
python
|
def time_at_elevation(self, elevation, direction=SUN_RISING, date=None, local=True):
"""Calculate the time when the sun is at the specified elevation.
Note:
This method uses positive elevations for those above the horizon.
Elevations greater than 90 degrees are converted to a setting sun
i.e. an elevation of 110 will calculate a setting sun at 70 degrees.
:param elevation: Elevation in degrees above the horizon to calculate for.
:type elevation: float
:param direction: Determines whether the time is for the sun rising or setting.
Use ``astral.SUN_RISING`` or ``astral.SUN_SETTING``. Default is rising.
:type direction: int
:param date: The date for which to calculate the elevation time.
If no date is specified then the current date will be used.
:type date: :class:`~datetime.date`
:param local: True = Time to be returned in location's time zone;
False = Time to be returned in UTC.
If not specified then the time will be returned in local time
:type local: bool
:returns: The date and time at which dusk occurs.
:rtype: :class:`~datetime.datetime`
"""
if local and self.timezone is None:
raise ValueError("Local time requested but Location has no timezone set.")
if self.astral is None:
self.astral = Astral()
if date is None:
date = datetime.date.today()
if elevation > 90.0:
elevation = 180.0 - elevation
direction = SUN_SETTING
time_ = self.astral.time_at_elevation_utc(
elevation, direction, date, self.latitude, self.longitude
)
if local:
return time_.astimezone(self.tz)
else:
return time_
|
[
"def",
"time_at_elevation",
"(",
"self",
",",
"elevation",
",",
"direction",
"=",
"SUN_RISING",
",",
"date",
"=",
"None",
",",
"local",
"=",
"True",
")",
":",
"if",
"local",
"and",
"self",
".",
"timezone",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Local time requested but Location has no timezone set.\"",
")",
"if",
"self",
".",
"astral",
"is",
"None",
":",
"self",
".",
"astral",
"=",
"Astral",
"(",
")",
"if",
"date",
"is",
"None",
":",
"date",
"=",
"datetime",
".",
"date",
".",
"today",
"(",
")",
"if",
"elevation",
">",
"90.0",
":",
"elevation",
"=",
"180.0",
"-",
"elevation",
"direction",
"=",
"SUN_SETTING",
"time_",
"=",
"self",
".",
"astral",
".",
"time_at_elevation_utc",
"(",
"elevation",
",",
"direction",
",",
"date",
",",
"self",
".",
"latitude",
",",
"self",
".",
"longitude",
")",
"if",
"local",
":",
"return",
"time_",
".",
"astimezone",
"(",
"self",
".",
"tz",
")",
"else",
":",
"return",
"time_"
] |
Calculate the time when the sun is at the specified elevation.
Note:
This method uses positive elevations for those above the horizon.
Elevations greater than 90 degrees are converted to a setting sun
i.e. an elevation of 110 will calculate a setting sun at 70 degrees.
:param elevation: Elevation in degrees above the horizon to calculate for.
:type elevation: float
:param direction: Determines whether the time is for the sun rising or setting.
Use ``astral.SUN_RISING`` or ``astral.SUN_SETTING``. Default is rising.
:type direction: int
:param date: The date for which to calculate the elevation time.
If no date is specified then the current date will be used.
:type date: :class:`~datetime.date`
:param local: True = Time to be returned in location's time zone;
False = Time to be returned in UTC.
If not specified then the time will be returned in local time
:type local: bool
:returns: The date and time at which dusk occurs.
:rtype: :class:`~datetime.datetime`
|
[
"Calculate",
"the",
"time",
"when",
"the",
"sun",
"is",
"at",
"the",
"specified",
"elevation",
"."
] |
b0aa63fce692357cd33c2bf36c69ed5b6582440c
|
https://github.com/sffjunkie/astral/blob/b0aa63fce692357cd33c2bf36c69ed5b6582440c/src/astral.py#L1145-L1194
|
11,570
|
sffjunkie/astral
|
src/astral.py
|
Location.blue_hour
|
def blue_hour(self, direction=SUN_RISING, date=None, local=True, use_elevation=True):
"""Returns the start and end times of the Blue Hour when the sun is traversing
in the specified direction.
This method uses the definition from PhotoPills i.e. the
blue hour is when the sun is between 6 and 4 degrees below the horizon.
:param direction: Determines whether the time is for the sun rising or setting.
Use ``astral.SUN_RISING`` or ``astral.SUN_SETTING``. Default is rising.
:type direction: int
:param date: The date for which to calculate the times.
If no date is specified then the current date will be used.
:type date: :class:`~datetime.date`
:param local: True = Times to be returned in location's time zone;
False = Times to be returned in UTC.
If not specified then the time will be returned in local time
:type local: bool
:param use_elevation: True = Return times that allow for the location's elevation;
False = Return times that don't use elevation.
If not specified then times will take elevation into account.
:type use_elevation: bool
:return: A tuple of the date and time at which the Blue Hour starts and ends.
:rtype: (:class:`~datetime.datetime`, :class:`~datetime.datetime`)
"""
if local and self.timezone is None:
raise ValueError("Local time requested but Location has no timezone set.")
if self.astral is None:
self.astral = Astral()
if date is None:
date = datetime.date.today()
elevation = self.elevation if use_elevation else 0
start, end = self.astral.blue_hour_utc(
direction, date, self.latitude, self.longitude, elevation
)
if local:
start = start.astimezone(self.tz)
end = end.astimezone(self.tz)
return start, end
|
python
|
def blue_hour(self, direction=SUN_RISING, date=None, local=True, use_elevation=True):
"""Returns the start and end times of the Blue Hour when the sun is traversing
in the specified direction.
This method uses the definition from PhotoPills i.e. the
blue hour is when the sun is between 6 and 4 degrees below the horizon.
:param direction: Determines whether the time is for the sun rising or setting.
Use ``astral.SUN_RISING`` or ``astral.SUN_SETTING``. Default is rising.
:type direction: int
:param date: The date for which to calculate the times.
If no date is specified then the current date will be used.
:type date: :class:`~datetime.date`
:param local: True = Times to be returned in location's time zone;
False = Times to be returned in UTC.
If not specified then the time will be returned in local time
:type local: bool
:param use_elevation: True = Return times that allow for the location's elevation;
False = Return times that don't use elevation.
If not specified then times will take elevation into account.
:type use_elevation: bool
:return: A tuple of the date and time at which the Blue Hour starts and ends.
:rtype: (:class:`~datetime.datetime`, :class:`~datetime.datetime`)
"""
if local and self.timezone is None:
raise ValueError("Local time requested but Location has no timezone set.")
if self.astral is None:
self.astral = Astral()
if date is None:
date = datetime.date.today()
elevation = self.elevation if use_elevation else 0
start, end = self.astral.blue_hour_utc(
direction, date, self.latitude, self.longitude, elevation
)
if local:
start = start.astimezone(self.tz)
end = end.astimezone(self.tz)
return start, end
|
[
"def",
"blue_hour",
"(",
"self",
",",
"direction",
"=",
"SUN_RISING",
",",
"date",
"=",
"None",
",",
"local",
"=",
"True",
",",
"use_elevation",
"=",
"True",
")",
":",
"if",
"local",
"and",
"self",
".",
"timezone",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Local time requested but Location has no timezone set.\"",
")",
"if",
"self",
".",
"astral",
"is",
"None",
":",
"self",
".",
"astral",
"=",
"Astral",
"(",
")",
"if",
"date",
"is",
"None",
":",
"date",
"=",
"datetime",
".",
"date",
".",
"today",
"(",
")",
"elevation",
"=",
"self",
".",
"elevation",
"if",
"use_elevation",
"else",
"0",
"start",
",",
"end",
"=",
"self",
".",
"astral",
".",
"blue_hour_utc",
"(",
"direction",
",",
"date",
",",
"self",
".",
"latitude",
",",
"self",
".",
"longitude",
",",
"elevation",
")",
"if",
"local",
":",
"start",
"=",
"start",
".",
"astimezone",
"(",
"self",
".",
"tz",
")",
"end",
"=",
"end",
".",
"astimezone",
"(",
"self",
".",
"tz",
")",
"return",
"start",
",",
"end"
] |
Returns the start and end times of the Blue Hour when the sun is traversing
in the specified direction.
This method uses the definition from PhotoPills i.e. the
blue hour is when the sun is between 6 and 4 degrees below the horizon.
:param direction: Determines whether the time is for the sun rising or setting.
Use ``astral.SUN_RISING`` or ``astral.SUN_SETTING``. Default is rising.
:type direction: int
:param date: The date for which to calculate the times.
If no date is specified then the current date will be used.
:type date: :class:`~datetime.date`
:param local: True = Times to be returned in location's time zone;
False = Times to be returned in UTC.
If not specified then the time will be returned in local time
:type local: bool
:param use_elevation: True = Return times that allow for the location's elevation;
False = Return times that don't use elevation.
If not specified then times will take elevation into account.
:type use_elevation: bool
:return: A tuple of the date and time at which the Blue Hour starts and ends.
:rtype: (:class:`~datetime.datetime`, :class:`~datetime.datetime`)
|
[
"Returns",
"the",
"start",
"and",
"end",
"times",
"of",
"the",
"Blue",
"Hour",
"when",
"the",
"sun",
"is",
"traversing",
"in",
"the",
"specified",
"direction",
"."
] |
b0aa63fce692357cd33c2bf36c69ed5b6582440c
|
https://github.com/sffjunkie/astral/blob/b0aa63fce692357cd33c2bf36c69ed5b6582440c/src/astral.py#L1285-L1332
|
11,571
|
sffjunkie/astral
|
src/astral.py
|
Location.moon_phase
|
def moon_phase(self, date=None, rtype=int):
"""Calculates the moon phase for a specific date.
:param date: The date to calculate the phase for.
If ommitted the current date is used.
:type date: :class:`datetime.date`
:returns:
A number designating the phase
| 0 = New moon
| 7 = First quarter
| 14 = Full moon
| 21 = Last quarter
"""
if self.astral is None:
self.astral = Astral()
if date is None:
date = datetime.date.today()
return self.astral.moon_phase(date, rtype)
|
python
|
def moon_phase(self, date=None, rtype=int):
"""Calculates the moon phase for a specific date.
:param date: The date to calculate the phase for.
If ommitted the current date is used.
:type date: :class:`datetime.date`
:returns:
A number designating the phase
| 0 = New moon
| 7 = First quarter
| 14 = Full moon
| 21 = Last quarter
"""
if self.astral is None:
self.astral = Astral()
if date is None:
date = datetime.date.today()
return self.astral.moon_phase(date, rtype)
|
[
"def",
"moon_phase",
"(",
"self",
",",
"date",
"=",
"None",
",",
"rtype",
"=",
"int",
")",
":",
"if",
"self",
".",
"astral",
"is",
"None",
":",
"self",
".",
"astral",
"=",
"Astral",
"(",
")",
"if",
"date",
"is",
"None",
":",
"date",
"=",
"datetime",
".",
"date",
".",
"today",
"(",
")",
"return",
"self",
".",
"astral",
".",
"moon_phase",
"(",
"date",
",",
"rtype",
")"
] |
Calculates the moon phase for a specific date.
:param date: The date to calculate the phase for.
If ommitted the current date is used.
:type date: :class:`datetime.date`
:returns:
A number designating the phase
| 0 = New moon
| 7 = First quarter
| 14 = Full moon
| 21 = Last quarter
|
[
"Calculates",
"the",
"moon",
"phase",
"for",
"a",
"specific",
"date",
"."
] |
b0aa63fce692357cd33c2bf36c69ed5b6582440c
|
https://github.com/sffjunkie/astral/blob/b0aa63fce692357cd33c2bf36c69ed5b6582440c/src/astral.py#L1390-L1412
|
11,572
|
sffjunkie/astral
|
src/astral.py
|
AstralGeocoder.add_locations
|
def add_locations(self, locations):
"""Add extra locations to AstralGeocoder.
Extra locations can be
* A single string containing one or more locations separated by a newline.
* A list of strings
* A list of lists/tuples that are passed to a :class:`Location` constructor
"""
if isinstance(locations, (str, ustr)):
self._add_from_str(locations)
elif isinstance(locations, (list, tuple)):
self._add_from_list(locations)
|
python
|
def add_locations(self, locations):
"""Add extra locations to AstralGeocoder.
Extra locations can be
* A single string containing one or more locations separated by a newline.
* A list of strings
* A list of lists/tuples that are passed to a :class:`Location` constructor
"""
if isinstance(locations, (str, ustr)):
self._add_from_str(locations)
elif isinstance(locations, (list, tuple)):
self._add_from_list(locations)
|
[
"def",
"add_locations",
"(",
"self",
",",
"locations",
")",
":",
"if",
"isinstance",
"(",
"locations",
",",
"(",
"str",
",",
"ustr",
")",
")",
":",
"self",
".",
"_add_from_str",
"(",
"locations",
")",
"elif",
"isinstance",
"(",
"locations",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"self",
".",
"_add_from_list",
"(",
"locations",
")"
] |
Add extra locations to AstralGeocoder.
Extra locations can be
* A single string containing one or more locations separated by a newline.
* A list of strings
* A list of lists/tuples that are passed to a :class:`Location` constructor
|
[
"Add",
"extra",
"locations",
"to",
"AstralGeocoder",
"."
] |
b0aa63fce692357cd33c2bf36c69ed5b6582440c
|
https://github.com/sffjunkie/astral/blob/b0aa63fce692357cd33c2bf36c69ed5b6582440c/src/astral.py#L1512-L1525
|
11,573
|
sffjunkie/astral
|
src/astral.py
|
AstralGeocoder._add_from_str
|
def _add_from_str(self, s):
"""Add locations from a string"""
if sys.version_info[0] < 3 and isinstance(s, str):
s = s.decode('utf-8')
for line in s.split("\n"):
self._parse_line(line)
|
python
|
def _add_from_str(self, s):
"""Add locations from a string"""
if sys.version_info[0] < 3 and isinstance(s, str):
s = s.decode('utf-8')
for line in s.split("\n"):
self._parse_line(line)
|
[
"def",
"_add_from_str",
"(",
"self",
",",
"s",
")",
":",
"if",
"sys",
".",
"version_info",
"[",
"0",
"]",
"<",
"3",
"and",
"isinstance",
"(",
"s",
",",
"str",
")",
":",
"s",
"=",
"s",
".",
"decode",
"(",
"'utf-8'",
")",
"for",
"line",
"in",
"s",
".",
"split",
"(",
"\"\\n\"",
")",
":",
"self",
".",
"_parse_line",
"(",
"line",
")"
] |
Add locations from a string
|
[
"Add",
"locations",
"from",
"a",
"string"
] |
b0aa63fce692357cd33c2bf36c69ed5b6582440c
|
https://github.com/sffjunkie/astral/blob/b0aa63fce692357cd33c2bf36c69ed5b6582440c/src/astral.py#L1527-L1534
|
11,574
|
sffjunkie/astral
|
src/astral.py
|
AstralGeocoder._add_from_list
|
def _add_from_list(self, l):
"""Add locations from a list of either strings or lists or tuples.
Lists of lists and tuples are passed to the Location constructor
"""
for item in l:
if isinstance(item, (str, ustr)):
self._add_from_str(item)
elif isinstance(item, (list, tuple)):
location = Location(item)
self._add_location(location)
|
python
|
def _add_from_list(self, l):
"""Add locations from a list of either strings or lists or tuples.
Lists of lists and tuples are passed to the Location constructor
"""
for item in l:
if isinstance(item, (str, ustr)):
self._add_from_str(item)
elif isinstance(item, (list, tuple)):
location = Location(item)
self._add_location(location)
|
[
"def",
"_add_from_list",
"(",
"self",
",",
"l",
")",
":",
"for",
"item",
"in",
"l",
":",
"if",
"isinstance",
"(",
"item",
",",
"(",
"str",
",",
"ustr",
")",
")",
":",
"self",
".",
"_add_from_str",
"(",
"item",
")",
"elif",
"isinstance",
"(",
"item",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"location",
"=",
"Location",
"(",
"item",
")",
"self",
".",
"_add_location",
"(",
"location",
")"
] |
Add locations from a list of either strings or lists or tuples.
Lists of lists and tuples are passed to the Location constructor
|
[
"Add",
"locations",
"from",
"a",
"list",
"of",
"either",
"strings",
"or",
"lists",
"or",
"tuples",
"."
] |
b0aa63fce692357cd33c2bf36c69ed5b6582440c
|
https://github.com/sffjunkie/astral/blob/b0aa63fce692357cd33c2bf36c69ed5b6582440c/src/astral.py#L1536-L1547
|
11,575
|
sffjunkie/astral
|
src/astral.py
|
GoogleGeocoder._get_geocoding
|
def _get_geocoding(self, key, location):
"""Lookup the Google geocoding API information for `key`"""
url = self._location_query_base % quote_plus(key)
if self.api_key:
url += "&key=%s" % self.api_key
data = self._read_from_url(url)
response = json.loads(data)
if response["status"] == "OK":
formatted_address = response["results"][0]["formatted_address"]
pos = formatted_address.find(",")
if pos == -1:
location.name = formatted_address
location.region = ""
else:
location.name = formatted_address[:pos].strip()
location.region = formatted_address[pos + 1 :].strip()
geo_location = response["results"][0]["geometry"]["location"]
location.latitude = float(geo_location["lat"])
location.longitude = float(geo_location["lng"])
else:
raise AstralError("GoogleGeocoder: Unable to locate %s. Server Response=%s" %
(key, response["status"]))
|
python
|
def _get_geocoding(self, key, location):
"""Lookup the Google geocoding API information for `key`"""
url = self._location_query_base % quote_plus(key)
if self.api_key:
url += "&key=%s" % self.api_key
data = self._read_from_url(url)
response = json.loads(data)
if response["status"] == "OK":
formatted_address = response["results"][0]["formatted_address"]
pos = formatted_address.find(",")
if pos == -1:
location.name = formatted_address
location.region = ""
else:
location.name = formatted_address[:pos].strip()
location.region = formatted_address[pos + 1 :].strip()
geo_location = response["results"][0]["geometry"]["location"]
location.latitude = float(geo_location["lat"])
location.longitude = float(geo_location["lng"])
else:
raise AstralError("GoogleGeocoder: Unable to locate %s. Server Response=%s" %
(key, response["status"]))
|
[
"def",
"_get_geocoding",
"(",
"self",
",",
"key",
",",
"location",
")",
":",
"url",
"=",
"self",
".",
"_location_query_base",
"%",
"quote_plus",
"(",
"key",
")",
"if",
"self",
".",
"api_key",
":",
"url",
"+=",
"\"&key=%s\"",
"%",
"self",
".",
"api_key",
"data",
"=",
"self",
".",
"_read_from_url",
"(",
"url",
")",
"response",
"=",
"json",
".",
"loads",
"(",
"data",
")",
"if",
"response",
"[",
"\"status\"",
"]",
"==",
"\"OK\"",
":",
"formatted_address",
"=",
"response",
"[",
"\"results\"",
"]",
"[",
"0",
"]",
"[",
"\"formatted_address\"",
"]",
"pos",
"=",
"formatted_address",
".",
"find",
"(",
"\",\"",
")",
"if",
"pos",
"==",
"-",
"1",
":",
"location",
".",
"name",
"=",
"formatted_address",
"location",
".",
"region",
"=",
"\"\"",
"else",
":",
"location",
".",
"name",
"=",
"formatted_address",
"[",
":",
"pos",
"]",
".",
"strip",
"(",
")",
"location",
".",
"region",
"=",
"formatted_address",
"[",
"pos",
"+",
"1",
":",
"]",
".",
"strip",
"(",
")",
"geo_location",
"=",
"response",
"[",
"\"results\"",
"]",
"[",
"0",
"]",
"[",
"\"geometry\"",
"]",
"[",
"\"location\"",
"]",
"location",
".",
"latitude",
"=",
"float",
"(",
"geo_location",
"[",
"\"lat\"",
"]",
")",
"location",
".",
"longitude",
"=",
"float",
"(",
"geo_location",
"[",
"\"lng\"",
"]",
")",
"else",
":",
"raise",
"AstralError",
"(",
"\"GoogleGeocoder: Unable to locate %s. Server Response=%s\"",
"%",
"(",
"key",
",",
"response",
"[",
"\"status\"",
"]",
")",
")"
] |
Lookup the Google geocoding API information for `key`
|
[
"Lookup",
"the",
"Google",
"geocoding",
"API",
"information",
"for",
"key"
] |
b0aa63fce692357cd33c2bf36c69ed5b6582440c
|
https://github.com/sffjunkie/astral/blob/b0aa63fce692357cd33c2bf36c69ed5b6582440c/src/astral.py#L1684-L1707
|
11,576
|
sffjunkie/astral
|
src/astral.py
|
GoogleGeocoder._get_timezone
|
def _get_timezone(self, location):
"""Query the timezone information with the latitude and longitude of
the specified `location`.
This function assumes the timezone of the location has always been
the same as it is now by using time() in the query string.
"""
url = self._timezone_query_base % (
location.latitude,
location.longitude,
int(time()),
)
if self.api_key != "":
url += "&key=%s" % self.api_key
data = self._read_from_url(url)
response = json.loads(data)
if response["status"] == "OK":
location.timezone = response["timeZoneId"]
else:
location.timezone = "UTC"
|
python
|
def _get_timezone(self, location):
"""Query the timezone information with the latitude and longitude of
the specified `location`.
This function assumes the timezone of the location has always been
the same as it is now by using time() in the query string.
"""
url = self._timezone_query_base % (
location.latitude,
location.longitude,
int(time()),
)
if self.api_key != "":
url += "&key=%s" % self.api_key
data = self._read_from_url(url)
response = json.loads(data)
if response["status"] == "OK":
location.timezone = response["timeZoneId"]
else:
location.timezone = "UTC"
|
[
"def",
"_get_timezone",
"(",
"self",
",",
"location",
")",
":",
"url",
"=",
"self",
".",
"_timezone_query_base",
"%",
"(",
"location",
".",
"latitude",
",",
"location",
".",
"longitude",
",",
"int",
"(",
"time",
"(",
")",
")",
",",
")",
"if",
"self",
".",
"api_key",
"!=",
"\"\"",
":",
"url",
"+=",
"\"&key=%s\"",
"%",
"self",
".",
"api_key",
"data",
"=",
"self",
".",
"_read_from_url",
"(",
"url",
")",
"response",
"=",
"json",
".",
"loads",
"(",
"data",
")",
"if",
"response",
"[",
"\"status\"",
"]",
"==",
"\"OK\"",
":",
"location",
".",
"timezone",
"=",
"response",
"[",
"\"timeZoneId\"",
"]",
"else",
":",
"location",
".",
"timezone",
"=",
"\"UTC\""
] |
Query the timezone information with the latitude and longitude of
the specified `location`.
This function assumes the timezone of the location has always been
the same as it is now by using time() in the query string.
|
[
"Query",
"the",
"timezone",
"information",
"with",
"the",
"latitude",
"and",
"longitude",
"of",
"the",
"specified",
"location",
"."
] |
b0aa63fce692357cd33c2bf36c69ed5b6582440c
|
https://github.com/sffjunkie/astral/blob/b0aa63fce692357cd33c2bf36c69ed5b6582440c/src/astral.py#L1709-L1729
|
11,577
|
sffjunkie/astral
|
src/astral.py
|
GoogleGeocoder._get_elevation
|
def _get_elevation(self, location):
"""Query the elevation information with the latitude and longitude of
the specified `location`.
"""
url = self._elevation_query_base % (location.latitude, location.longitude)
if self.api_key != "":
url += "&key=%s" % self.api_key
data = self._read_from_url(url)
response = json.loads(data)
if response["status"] == "OK":
location.elevation = int(float(response["results"][0]["elevation"]))
else:
location.elevation = 0
|
python
|
def _get_elevation(self, location):
"""Query the elevation information with the latitude and longitude of
the specified `location`.
"""
url = self._elevation_query_base % (location.latitude, location.longitude)
if self.api_key != "":
url += "&key=%s" % self.api_key
data = self._read_from_url(url)
response = json.loads(data)
if response["status"] == "OK":
location.elevation = int(float(response["results"][0]["elevation"]))
else:
location.elevation = 0
|
[
"def",
"_get_elevation",
"(",
"self",
",",
"location",
")",
":",
"url",
"=",
"self",
".",
"_elevation_query_base",
"%",
"(",
"location",
".",
"latitude",
",",
"location",
".",
"longitude",
")",
"if",
"self",
".",
"api_key",
"!=",
"\"\"",
":",
"url",
"+=",
"\"&key=%s\"",
"%",
"self",
".",
"api_key",
"data",
"=",
"self",
".",
"_read_from_url",
"(",
"url",
")",
"response",
"=",
"json",
".",
"loads",
"(",
"data",
")",
"if",
"response",
"[",
"\"status\"",
"]",
"==",
"\"OK\"",
":",
"location",
".",
"elevation",
"=",
"int",
"(",
"float",
"(",
"response",
"[",
"\"results\"",
"]",
"[",
"0",
"]",
"[",
"\"elevation\"",
"]",
")",
")",
"else",
":",
"location",
".",
"elevation",
"=",
"0"
] |
Query the elevation information with the latitude and longitude of
the specified `location`.
|
[
"Query",
"the",
"elevation",
"information",
"with",
"the",
"latitude",
"and",
"longitude",
"of",
"the",
"specified",
"location",
"."
] |
b0aa63fce692357cd33c2bf36c69ed5b6582440c
|
https://github.com/sffjunkie/astral/blob/b0aa63fce692357cd33c2bf36c69ed5b6582440c/src/astral.py#L1731-L1744
|
11,578
|
sffjunkie/astral
|
src/astral.py
|
Astral.sun_utc
|
def sun_utc(self, date, latitude, longitude, observer_elevation=0):
"""Calculate all the info for the sun at once.
All times are returned in the UTC timezone.
:param date: Date to calculate for.
:type date: :class:`datetime.date`
:param latitude: Latitude - Northern latitudes should be positive
:type latitude: float
:param longitude: Longitude - Eastern longitudes should be positive
:type longitude: float
:param observer_elevation: Elevation in metres to calculate sun for
:type observer_elevation: int
:returns: Dictionary with keys ``dawn``, ``sunrise``, ``noon``,
``sunset`` and ``dusk`` whose values are the results of the
corresponding `_utc` methods.
:rtype: dict
"""
dawn = self.dawn_utc(date, latitude, longitude, observer_elevation=observer_elevation)
sunrise = self.sunrise_utc(date, latitude, longitude, observer_elevation=observer_elevation)
noon = self.solar_noon_utc(date, longitude)
sunset = self.sunset_utc(date, latitude, longitude, observer_elevation=observer_elevation)
dusk = self.dusk_utc(date, latitude, longitude, observer_elevation=observer_elevation)
return {
"dawn": dawn,
"sunrise": sunrise,
"noon": noon,
"sunset": sunset,
"dusk": dusk,
}
|
python
|
def sun_utc(self, date, latitude, longitude, observer_elevation=0):
"""Calculate all the info for the sun at once.
All times are returned in the UTC timezone.
:param date: Date to calculate for.
:type date: :class:`datetime.date`
:param latitude: Latitude - Northern latitudes should be positive
:type latitude: float
:param longitude: Longitude - Eastern longitudes should be positive
:type longitude: float
:param observer_elevation: Elevation in metres to calculate sun for
:type observer_elevation: int
:returns: Dictionary with keys ``dawn``, ``sunrise``, ``noon``,
``sunset`` and ``dusk`` whose values are the results of the
corresponding `_utc` methods.
:rtype: dict
"""
dawn = self.dawn_utc(date, latitude, longitude, observer_elevation=observer_elevation)
sunrise = self.sunrise_utc(date, latitude, longitude, observer_elevation=observer_elevation)
noon = self.solar_noon_utc(date, longitude)
sunset = self.sunset_utc(date, latitude, longitude, observer_elevation=observer_elevation)
dusk = self.dusk_utc(date, latitude, longitude, observer_elevation=observer_elevation)
return {
"dawn": dawn,
"sunrise": sunrise,
"noon": noon,
"sunset": sunset,
"dusk": dusk,
}
|
[
"def",
"sun_utc",
"(",
"self",
",",
"date",
",",
"latitude",
",",
"longitude",
",",
"observer_elevation",
"=",
"0",
")",
":",
"dawn",
"=",
"self",
".",
"dawn_utc",
"(",
"date",
",",
"latitude",
",",
"longitude",
",",
"observer_elevation",
"=",
"observer_elevation",
")",
"sunrise",
"=",
"self",
".",
"sunrise_utc",
"(",
"date",
",",
"latitude",
",",
"longitude",
",",
"observer_elevation",
"=",
"observer_elevation",
")",
"noon",
"=",
"self",
".",
"solar_noon_utc",
"(",
"date",
",",
"longitude",
")",
"sunset",
"=",
"self",
".",
"sunset_utc",
"(",
"date",
",",
"latitude",
",",
"longitude",
",",
"observer_elevation",
"=",
"observer_elevation",
")",
"dusk",
"=",
"self",
".",
"dusk_utc",
"(",
"date",
",",
"latitude",
",",
"longitude",
",",
"observer_elevation",
"=",
"observer_elevation",
")",
"return",
"{",
"\"dawn\"",
":",
"dawn",
",",
"\"sunrise\"",
":",
"sunrise",
",",
"\"noon\"",
":",
"noon",
",",
"\"sunset\"",
":",
"sunset",
",",
"\"dusk\"",
":",
"dusk",
",",
"}"
] |
Calculate all the info for the sun at once.
All times are returned in the UTC timezone.
:param date: Date to calculate for.
:type date: :class:`datetime.date`
:param latitude: Latitude - Northern latitudes should be positive
:type latitude: float
:param longitude: Longitude - Eastern longitudes should be positive
:type longitude: float
:param observer_elevation: Elevation in metres to calculate sun for
:type observer_elevation: int
:returns: Dictionary with keys ``dawn``, ``sunrise``, ``noon``,
``sunset`` and ``dusk`` whose values are the results of the
corresponding `_utc` methods.
:rtype: dict
|
[
"Calculate",
"all",
"the",
"info",
"for",
"the",
"sun",
"at",
"once",
".",
"All",
"times",
"are",
"returned",
"in",
"the",
"UTC",
"timezone",
"."
] |
b0aa63fce692357cd33c2bf36c69ed5b6582440c
|
https://github.com/sffjunkie/astral/blob/b0aa63fce692357cd33c2bf36c69ed5b6582440c/src/astral.py#L1805-L1836
|
11,579
|
sffjunkie/astral
|
src/astral.py
|
Astral.dawn_utc
|
def dawn_utc(self, date, latitude, longitude, depression=0, observer_elevation=0):
"""Calculate dawn time in the UTC timezone.
:param date: Date to calculate for.
:type date: :class:`datetime.date`
:param latitude: Latitude - Northern latitudes should be positive
:type latitude: float
:param longitude: Longitude - Eastern longitudes should be positive
:type longitude: float
:param depression: Override the depression used
:type depression: float
:param observer_elevation: Elevation in metres to calculate dawn for
:type observer_elevation: int
:return: The UTC date and time at which dawn occurs.
:rtype: :class:`~datetime.datetime`
"""
if depression == 0:
depression = self._depression
depression += 90
try:
return self._calc_time(depression, SUN_RISING, date, latitude, longitude, observer_elevation)
except ValueError as exc:
if exc.args[0] == "math domain error":
raise AstralError(
(
"Sun never reaches %d degrees below the horizon, "
"at this location."
)
% (depression - 90)
)
else:
raise
|
python
|
def dawn_utc(self, date, latitude, longitude, depression=0, observer_elevation=0):
"""Calculate dawn time in the UTC timezone.
:param date: Date to calculate for.
:type date: :class:`datetime.date`
:param latitude: Latitude - Northern latitudes should be positive
:type latitude: float
:param longitude: Longitude - Eastern longitudes should be positive
:type longitude: float
:param depression: Override the depression used
:type depression: float
:param observer_elevation: Elevation in metres to calculate dawn for
:type observer_elevation: int
:return: The UTC date and time at which dawn occurs.
:rtype: :class:`~datetime.datetime`
"""
if depression == 0:
depression = self._depression
depression += 90
try:
return self._calc_time(depression, SUN_RISING, date, latitude, longitude, observer_elevation)
except ValueError as exc:
if exc.args[0] == "math domain error":
raise AstralError(
(
"Sun never reaches %d degrees below the horizon, "
"at this location."
)
% (depression - 90)
)
else:
raise
|
[
"def",
"dawn_utc",
"(",
"self",
",",
"date",
",",
"latitude",
",",
"longitude",
",",
"depression",
"=",
"0",
",",
"observer_elevation",
"=",
"0",
")",
":",
"if",
"depression",
"==",
"0",
":",
"depression",
"=",
"self",
".",
"_depression",
"depression",
"+=",
"90",
"try",
":",
"return",
"self",
".",
"_calc_time",
"(",
"depression",
",",
"SUN_RISING",
",",
"date",
",",
"latitude",
",",
"longitude",
",",
"observer_elevation",
")",
"except",
"ValueError",
"as",
"exc",
":",
"if",
"exc",
".",
"args",
"[",
"0",
"]",
"==",
"\"math domain error\"",
":",
"raise",
"AstralError",
"(",
"(",
"\"Sun never reaches %d degrees below the horizon, \"",
"\"at this location.\"",
")",
"%",
"(",
"depression",
"-",
"90",
")",
")",
"else",
":",
"raise"
] |
Calculate dawn time in the UTC timezone.
:param date: Date to calculate for.
:type date: :class:`datetime.date`
:param latitude: Latitude - Northern latitudes should be positive
:type latitude: float
:param longitude: Longitude - Eastern longitudes should be positive
:type longitude: float
:param depression: Override the depression used
:type depression: float
:param observer_elevation: Elevation in metres to calculate dawn for
:type observer_elevation: int
:return: The UTC date and time at which dawn occurs.
:rtype: :class:`~datetime.datetime`
|
[
"Calculate",
"dawn",
"time",
"in",
"the",
"UTC",
"timezone",
"."
] |
b0aa63fce692357cd33c2bf36c69ed5b6582440c
|
https://github.com/sffjunkie/astral/blob/b0aa63fce692357cd33c2bf36c69ed5b6582440c/src/astral.py#L1838-L1872
|
11,580
|
sffjunkie/astral
|
src/astral.py
|
Astral.sunrise_utc
|
def sunrise_utc(self, date, latitude, longitude, observer_elevation=0):
"""Calculate sunrise time in the UTC timezone.
:param date: Date to calculate for.
:type date: :class:`datetime.date`
:param latitude: Latitude - Northern latitudes should be positive
:type latitude: float
:param longitude: Longitude - Eastern longitudes should be positive
:type longitude: float
:param observer_elevation: Elevation in metres to calculate sunrise for
:type observer_elevation: int
:return: The UTC date and time at which sunrise occurs.
:rtype: :class:`~datetime.datetime`
"""
try:
return self._calc_time(90 + 0.833, SUN_RISING, date, latitude, longitude, observer_elevation)
except ValueError as exc:
if exc.args[0] == "math domain error":
raise AstralError(
("Sun never reaches the horizon on this day, " "at this location.")
)
else:
raise
|
python
|
def sunrise_utc(self, date, latitude, longitude, observer_elevation=0):
"""Calculate sunrise time in the UTC timezone.
:param date: Date to calculate for.
:type date: :class:`datetime.date`
:param latitude: Latitude - Northern latitudes should be positive
:type latitude: float
:param longitude: Longitude - Eastern longitudes should be positive
:type longitude: float
:param observer_elevation: Elevation in metres to calculate sunrise for
:type observer_elevation: int
:return: The UTC date and time at which sunrise occurs.
:rtype: :class:`~datetime.datetime`
"""
try:
return self._calc_time(90 + 0.833, SUN_RISING, date, latitude, longitude, observer_elevation)
except ValueError as exc:
if exc.args[0] == "math domain error":
raise AstralError(
("Sun never reaches the horizon on this day, " "at this location.")
)
else:
raise
|
[
"def",
"sunrise_utc",
"(",
"self",
",",
"date",
",",
"latitude",
",",
"longitude",
",",
"observer_elevation",
"=",
"0",
")",
":",
"try",
":",
"return",
"self",
".",
"_calc_time",
"(",
"90",
"+",
"0.833",
",",
"SUN_RISING",
",",
"date",
",",
"latitude",
",",
"longitude",
",",
"observer_elevation",
")",
"except",
"ValueError",
"as",
"exc",
":",
"if",
"exc",
".",
"args",
"[",
"0",
"]",
"==",
"\"math domain error\"",
":",
"raise",
"AstralError",
"(",
"(",
"\"Sun never reaches the horizon on this day, \"",
"\"at this location.\"",
")",
")",
"else",
":",
"raise"
] |
Calculate sunrise time in the UTC timezone.
:param date: Date to calculate for.
:type date: :class:`datetime.date`
:param latitude: Latitude - Northern latitudes should be positive
:type latitude: float
:param longitude: Longitude - Eastern longitudes should be positive
:type longitude: float
:param observer_elevation: Elevation in metres to calculate sunrise for
:type observer_elevation: int
:return: The UTC date and time at which sunrise occurs.
:rtype: :class:`~datetime.datetime`
|
[
"Calculate",
"sunrise",
"time",
"in",
"the",
"UTC",
"timezone",
"."
] |
b0aa63fce692357cd33c2bf36c69ed5b6582440c
|
https://github.com/sffjunkie/astral/blob/b0aa63fce692357cd33c2bf36c69ed5b6582440c/src/astral.py#L1874-L1898
|
11,581
|
sffjunkie/astral
|
src/astral.py
|
Astral.solar_noon_utc
|
def solar_noon_utc(self, date, longitude):
"""Calculate solar noon time in the UTC timezone.
:param date: Date to calculate for.
:type date: :class:`datetime.date`
:param longitude: Longitude - Eastern longitudes should be positive
:type longitude: float
:return: The UTC date and time at which noon occurs.
:rtype: :class:`~datetime.datetime`
"""
jc = self._jday_to_jcentury(self._julianday(date))
eqtime = self._eq_of_time(jc)
timeUTC = (720.0 - (4 * longitude) - eqtime) / 60.0
hour = int(timeUTC)
minute = int((timeUTC - hour) * 60)
second = int((((timeUTC - hour) * 60) - minute) * 60)
if second > 59:
second -= 60
minute += 1
elif second < 0:
second += 60
minute -= 1
if minute > 59:
minute -= 60
hour += 1
elif minute < 0:
minute += 60
hour -= 1
if hour > 23:
hour -= 24
date += datetime.timedelta(days=1)
elif hour < 0:
hour += 24
date -= datetime.timedelta(days=1)
noon = datetime.datetime(date.year, date.month, date.day, hour, minute, second)
noon = pytz.UTC.localize(noon) # pylint: disable=E1120
return noon
|
python
|
def solar_noon_utc(self, date, longitude):
"""Calculate solar noon time in the UTC timezone.
:param date: Date to calculate for.
:type date: :class:`datetime.date`
:param longitude: Longitude - Eastern longitudes should be positive
:type longitude: float
:return: The UTC date and time at which noon occurs.
:rtype: :class:`~datetime.datetime`
"""
jc = self._jday_to_jcentury(self._julianday(date))
eqtime = self._eq_of_time(jc)
timeUTC = (720.0 - (4 * longitude) - eqtime) / 60.0
hour = int(timeUTC)
minute = int((timeUTC - hour) * 60)
second = int((((timeUTC - hour) * 60) - minute) * 60)
if second > 59:
second -= 60
minute += 1
elif second < 0:
second += 60
minute -= 1
if minute > 59:
minute -= 60
hour += 1
elif minute < 0:
minute += 60
hour -= 1
if hour > 23:
hour -= 24
date += datetime.timedelta(days=1)
elif hour < 0:
hour += 24
date -= datetime.timedelta(days=1)
noon = datetime.datetime(date.year, date.month, date.day, hour, minute, second)
noon = pytz.UTC.localize(noon) # pylint: disable=E1120
return noon
|
[
"def",
"solar_noon_utc",
"(",
"self",
",",
"date",
",",
"longitude",
")",
":",
"jc",
"=",
"self",
".",
"_jday_to_jcentury",
"(",
"self",
".",
"_julianday",
"(",
"date",
")",
")",
"eqtime",
"=",
"self",
".",
"_eq_of_time",
"(",
"jc",
")",
"timeUTC",
"=",
"(",
"720.0",
"-",
"(",
"4",
"*",
"longitude",
")",
"-",
"eqtime",
")",
"/",
"60.0",
"hour",
"=",
"int",
"(",
"timeUTC",
")",
"minute",
"=",
"int",
"(",
"(",
"timeUTC",
"-",
"hour",
")",
"*",
"60",
")",
"second",
"=",
"int",
"(",
"(",
"(",
"(",
"timeUTC",
"-",
"hour",
")",
"*",
"60",
")",
"-",
"minute",
")",
"*",
"60",
")",
"if",
"second",
">",
"59",
":",
"second",
"-=",
"60",
"minute",
"+=",
"1",
"elif",
"second",
"<",
"0",
":",
"second",
"+=",
"60",
"minute",
"-=",
"1",
"if",
"minute",
">",
"59",
":",
"minute",
"-=",
"60",
"hour",
"+=",
"1",
"elif",
"minute",
"<",
"0",
":",
"minute",
"+=",
"60",
"hour",
"-=",
"1",
"if",
"hour",
">",
"23",
":",
"hour",
"-=",
"24",
"date",
"+=",
"datetime",
".",
"timedelta",
"(",
"days",
"=",
"1",
")",
"elif",
"hour",
"<",
"0",
":",
"hour",
"+=",
"24",
"date",
"-=",
"datetime",
".",
"timedelta",
"(",
"days",
"=",
"1",
")",
"noon",
"=",
"datetime",
".",
"datetime",
"(",
"date",
".",
"year",
",",
"date",
".",
"month",
",",
"date",
".",
"day",
",",
"hour",
",",
"minute",
",",
"second",
")",
"noon",
"=",
"pytz",
".",
"UTC",
".",
"localize",
"(",
"noon",
")",
"# pylint: disable=E1120",
"return",
"noon"
] |
Calculate solar noon time in the UTC timezone.
:param date: Date to calculate for.
:type date: :class:`datetime.date`
:param longitude: Longitude - Eastern longitudes should be positive
:type longitude: float
:return: The UTC date and time at which noon occurs.
:rtype: :class:`~datetime.datetime`
|
[
"Calculate",
"solar",
"noon",
"time",
"in",
"the",
"UTC",
"timezone",
"."
] |
b0aa63fce692357cd33c2bf36c69ed5b6582440c
|
https://github.com/sffjunkie/astral/blob/b0aa63fce692357cd33c2bf36c69ed5b6582440c/src/astral.py#L1900-L1944
|
11,582
|
sffjunkie/astral
|
src/astral.py
|
Astral.sunset_utc
|
def sunset_utc(self, date, latitude, longitude, observer_elevation=0):
"""Calculate sunset time in the UTC timezone.
:param date: Date to calculate for.
:type date: :class:`datetime.date`
:param latitude: Latitude - Northern latitudes should be positive
:type latitude: float
:param longitude: Longitude - Eastern longitudes should be positive
:type longitude: float
:param observer_elevation: Elevation in metres to calculate sunset for
:type observer_elevation: int
:return: The UTC date and time at which sunset occurs.
:rtype: :class:`~datetime.datetime`
"""
try:
return self._calc_time(90 + 0.833, SUN_SETTING, date, latitude, longitude, observer_elevation)
except ValueError as exc:
if exc.args[0] == "math domain error":
raise AstralError(
("Sun never reaches the horizon on this day, " "at this location.")
)
else:
raise
|
python
|
def sunset_utc(self, date, latitude, longitude, observer_elevation=0):
"""Calculate sunset time in the UTC timezone.
:param date: Date to calculate for.
:type date: :class:`datetime.date`
:param latitude: Latitude - Northern latitudes should be positive
:type latitude: float
:param longitude: Longitude - Eastern longitudes should be positive
:type longitude: float
:param observer_elevation: Elevation in metres to calculate sunset for
:type observer_elevation: int
:return: The UTC date and time at which sunset occurs.
:rtype: :class:`~datetime.datetime`
"""
try:
return self._calc_time(90 + 0.833, SUN_SETTING, date, latitude, longitude, observer_elevation)
except ValueError as exc:
if exc.args[0] == "math domain error":
raise AstralError(
("Sun never reaches the horizon on this day, " "at this location.")
)
else:
raise
|
[
"def",
"sunset_utc",
"(",
"self",
",",
"date",
",",
"latitude",
",",
"longitude",
",",
"observer_elevation",
"=",
"0",
")",
":",
"try",
":",
"return",
"self",
".",
"_calc_time",
"(",
"90",
"+",
"0.833",
",",
"SUN_SETTING",
",",
"date",
",",
"latitude",
",",
"longitude",
",",
"observer_elevation",
")",
"except",
"ValueError",
"as",
"exc",
":",
"if",
"exc",
".",
"args",
"[",
"0",
"]",
"==",
"\"math domain error\"",
":",
"raise",
"AstralError",
"(",
"(",
"\"Sun never reaches the horizon on this day, \"",
"\"at this location.\"",
")",
")",
"else",
":",
"raise"
] |
Calculate sunset time in the UTC timezone.
:param date: Date to calculate for.
:type date: :class:`datetime.date`
:param latitude: Latitude - Northern latitudes should be positive
:type latitude: float
:param longitude: Longitude - Eastern longitudes should be positive
:type longitude: float
:param observer_elevation: Elevation in metres to calculate sunset for
:type observer_elevation: int
:return: The UTC date and time at which sunset occurs.
:rtype: :class:`~datetime.datetime`
|
[
"Calculate",
"sunset",
"time",
"in",
"the",
"UTC",
"timezone",
"."
] |
b0aa63fce692357cd33c2bf36c69ed5b6582440c
|
https://github.com/sffjunkie/astral/blob/b0aa63fce692357cd33c2bf36c69ed5b6582440c/src/astral.py#L1946-L1970
|
11,583
|
sffjunkie/astral
|
src/astral.py
|
Astral.dusk_utc
|
def dusk_utc(self, date, latitude, longitude, depression=0, observer_elevation=0):
"""Calculate dusk time in the UTC timezone.
:param date: Date to calculate for.
:type date: :class:`datetime.date`
:param latitude: Latitude - Northern latitudes should be positive
:type latitude: float
:param longitude: Longitude - Eastern longitudes should be positive
:type longitude: float
:param depression: Override the depression used
:type depression: float
:param observer_elevation: Elevation in metres to calculate dusk for
:type observer_elevation: int
:return: The UTC date and time at which dusk occurs.
:rtype: :class:`~datetime.datetime`
"""
if depression == 0:
depression = self._depression
depression += 90
try:
return self._calc_time(depression, SUN_SETTING, date, latitude, longitude, observer_elevation)
except ValueError as exc:
if exc.args[0] == "math domain error":
raise AstralError(
(
"Sun never reaches %d degrees below the horizon, "
"at this location."
)
% (depression - 90)
)
else:
raise
|
python
|
def dusk_utc(self, date, latitude, longitude, depression=0, observer_elevation=0):
"""Calculate dusk time in the UTC timezone.
:param date: Date to calculate for.
:type date: :class:`datetime.date`
:param latitude: Latitude - Northern latitudes should be positive
:type latitude: float
:param longitude: Longitude - Eastern longitudes should be positive
:type longitude: float
:param depression: Override the depression used
:type depression: float
:param observer_elevation: Elevation in metres to calculate dusk for
:type observer_elevation: int
:return: The UTC date and time at which dusk occurs.
:rtype: :class:`~datetime.datetime`
"""
if depression == 0:
depression = self._depression
depression += 90
try:
return self._calc_time(depression, SUN_SETTING, date, latitude, longitude, observer_elevation)
except ValueError as exc:
if exc.args[0] == "math domain error":
raise AstralError(
(
"Sun never reaches %d degrees below the horizon, "
"at this location."
)
% (depression - 90)
)
else:
raise
|
[
"def",
"dusk_utc",
"(",
"self",
",",
"date",
",",
"latitude",
",",
"longitude",
",",
"depression",
"=",
"0",
",",
"observer_elevation",
"=",
"0",
")",
":",
"if",
"depression",
"==",
"0",
":",
"depression",
"=",
"self",
".",
"_depression",
"depression",
"+=",
"90",
"try",
":",
"return",
"self",
".",
"_calc_time",
"(",
"depression",
",",
"SUN_SETTING",
",",
"date",
",",
"latitude",
",",
"longitude",
",",
"observer_elevation",
")",
"except",
"ValueError",
"as",
"exc",
":",
"if",
"exc",
".",
"args",
"[",
"0",
"]",
"==",
"\"math domain error\"",
":",
"raise",
"AstralError",
"(",
"(",
"\"Sun never reaches %d degrees below the horizon, \"",
"\"at this location.\"",
")",
"%",
"(",
"depression",
"-",
"90",
")",
")",
"else",
":",
"raise"
] |
Calculate dusk time in the UTC timezone.
:param date: Date to calculate for.
:type date: :class:`datetime.date`
:param latitude: Latitude - Northern latitudes should be positive
:type latitude: float
:param longitude: Longitude - Eastern longitudes should be positive
:type longitude: float
:param depression: Override the depression used
:type depression: float
:param observer_elevation: Elevation in metres to calculate dusk for
:type observer_elevation: int
:return: The UTC date and time at which dusk occurs.
:rtype: :class:`~datetime.datetime`
|
[
"Calculate",
"dusk",
"time",
"in",
"the",
"UTC",
"timezone",
"."
] |
b0aa63fce692357cd33c2bf36c69ed5b6582440c
|
https://github.com/sffjunkie/astral/blob/b0aa63fce692357cd33c2bf36c69ed5b6582440c/src/astral.py#L1972-L2006
|
11,584
|
sffjunkie/astral
|
src/astral.py
|
Astral.solar_midnight_utc
|
def solar_midnight_utc(self, date, longitude):
"""Calculate solar midnight time in the UTC timezone.
Note that this claculates the solar midgnight that is closest
to 00:00:00 of the specified date i.e. it may return a time that is on
the previous day.
:param date: Date to calculate for.
:type date: :class:`datetime.date`
:param longitude: Longitude - Eastern longitudes should be positive
:type longitude: float
:return: The UTC date and time at which midnight occurs.
:rtype: :class:`~datetime.datetime`
"""
julianday = self._julianday(date)
newt = self._jday_to_jcentury(julianday + 0.5 + -longitude / 360.0)
eqtime = self._eq_of_time(newt)
timeUTC = (-longitude * 4.0) - eqtime
timeUTC = timeUTC / 60.0
hour = int(timeUTC)
minute = int((timeUTC - hour) * 60)
second = int((((timeUTC - hour) * 60) - minute) * 60)
if second > 59:
second -= 60
minute += 1
elif second < 0:
second += 60
minute -= 1
if minute > 59:
minute -= 60
hour += 1
elif minute < 0:
minute += 60
hour -= 1
if hour < 0:
hour += 24
date -= datetime.timedelta(days=1)
midnight = datetime.datetime(
date.year, date.month, date.day, hour, minute, second
)
midnight = pytz.UTC.localize(midnight) # pylint: disable=E1120
return midnight
|
python
|
def solar_midnight_utc(self, date, longitude):
"""Calculate solar midnight time in the UTC timezone.
Note that this claculates the solar midgnight that is closest
to 00:00:00 of the specified date i.e. it may return a time that is on
the previous day.
:param date: Date to calculate for.
:type date: :class:`datetime.date`
:param longitude: Longitude - Eastern longitudes should be positive
:type longitude: float
:return: The UTC date and time at which midnight occurs.
:rtype: :class:`~datetime.datetime`
"""
julianday = self._julianday(date)
newt = self._jday_to_jcentury(julianday + 0.5 + -longitude / 360.0)
eqtime = self._eq_of_time(newt)
timeUTC = (-longitude * 4.0) - eqtime
timeUTC = timeUTC / 60.0
hour = int(timeUTC)
minute = int((timeUTC - hour) * 60)
second = int((((timeUTC - hour) * 60) - minute) * 60)
if second > 59:
second -= 60
minute += 1
elif second < 0:
second += 60
minute -= 1
if minute > 59:
minute -= 60
hour += 1
elif minute < 0:
minute += 60
hour -= 1
if hour < 0:
hour += 24
date -= datetime.timedelta(days=1)
midnight = datetime.datetime(
date.year, date.month, date.day, hour, minute, second
)
midnight = pytz.UTC.localize(midnight) # pylint: disable=E1120
return midnight
|
[
"def",
"solar_midnight_utc",
"(",
"self",
",",
"date",
",",
"longitude",
")",
":",
"julianday",
"=",
"self",
".",
"_julianday",
"(",
"date",
")",
"newt",
"=",
"self",
".",
"_jday_to_jcentury",
"(",
"julianday",
"+",
"0.5",
"+",
"-",
"longitude",
"/",
"360.0",
")",
"eqtime",
"=",
"self",
".",
"_eq_of_time",
"(",
"newt",
")",
"timeUTC",
"=",
"(",
"-",
"longitude",
"*",
"4.0",
")",
"-",
"eqtime",
"timeUTC",
"=",
"timeUTC",
"/",
"60.0",
"hour",
"=",
"int",
"(",
"timeUTC",
")",
"minute",
"=",
"int",
"(",
"(",
"timeUTC",
"-",
"hour",
")",
"*",
"60",
")",
"second",
"=",
"int",
"(",
"(",
"(",
"(",
"timeUTC",
"-",
"hour",
")",
"*",
"60",
")",
"-",
"minute",
")",
"*",
"60",
")",
"if",
"second",
">",
"59",
":",
"second",
"-=",
"60",
"minute",
"+=",
"1",
"elif",
"second",
"<",
"0",
":",
"second",
"+=",
"60",
"minute",
"-=",
"1",
"if",
"minute",
">",
"59",
":",
"minute",
"-=",
"60",
"hour",
"+=",
"1",
"elif",
"minute",
"<",
"0",
":",
"minute",
"+=",
"60",
"hour",
"-=",
"1",
"if",
"hour",
"<",
"0",
":",
"hour",
"+=",
"24",
"date",
"-=",
"datetime",
".",
"timedelta",
"(",
"days",
"=",
"1",
")",
"midnight",
"=",
"datetime",
".",
"datetime",
"(",
"date",
".",
"year",
",",
"date",
".",
"month",
",",
"date",
".",
"day",
",",
"hour",
",",
"minute",
",",
"second",
")",
"midnight",
"=",
"pytz",
".",
"UTC",
".",
"localize",
"(",
"midnight",
")",
"# pylint: disable=E1120",
"return",
"midnight"
] |
Calculate solar midnight time in the UTC timezone.
Note that this claculates the solar midgnight that is closest
to 00:00:00 of the specified date i.e. it may return a time that is on
the previous day.
:param date: Date to calculate for.
:type date: :class:`datetime.date`
:param longitude: Longitude - Eastern longitudes should be positive
:type longitude: float
:return: The UTC date and time at which midnight occurs.
:rtype: :class:`~datetime.datetime`
|
[
"Calculate",
"solar",
"midnight",
"time",
"in",
"the",
"UTC",
"timezone",
"."
] |
b0aa63fce692357cd33c2bf36c69ed5b6582440c
|
https://github.com/sffjunkie/astral/blob/b0aa63fce692357cd33c2bf36c69ed5b6582440c/src/astral.py#L2008-L2059
|
11,585
|
sffjunkie/astral
|
src/astral.py
|
Astral.daylight_utc
|
def daylight_utc(self, date, latitude, longitude, observer_elevation=0):
"""Calculate daylight start and end times in the UTC timezone.
:param date: Date to calculate for.
:type date: :class:`datetime.date`
:param latitude: Latitude - Northern latitudes should be positive
:type latitude: float
:param longitude: Longitude - Eastern longitudes should be positive
:type longitude: float
:param observer_elevation: Elevation in metres to calculate daylight for
:type observer_elevation: int
:return: A tuple of the UTC date and time at which daylight starts and ends.
:rtype: (:class:`~datetime.datetime`, :class:`~datetime.datetime`)
"""
start = self.sunrise_utc(date, latitude, longitude, observer_elevation)
end = self.sunset_utc(date, latitude, longitude, observer_elevation)
return start, end
|
python
|
def daylight_utc(self, date, latitude, longitude, observer_elevation=0):
"""Calculate daylight start and end times in the UTC timezone.
:param date: Date to calculate for.
:type date: :class:`datetime.date`
:param latitude: Latitude - Northern latitudes should be positive
:type latitude: float
:param longitude: Longitude - Eastern longitudes should be positive
:type longitude: float
:param observer_elevation: Elevation in metres to calculate daylight for
:type observer_elevation: int
:return: A tuple of the UTC date and time at which daylight starts and ends.
:rtype: (:class:`~datetime.datetime`, :class:`~datetime.datetime`)
"""
start = self.sunrise_utc(date, latitude, longitude, observer_elevation)
end = self.sunset_utc(date, latitude, longitude, observer_elevation)
return start, end
|
[
"def",
"daylight_utc",
"(",
"self",
",",
"date",
",",
"latitude",
",",
"longitude",
",",
"observer_elevation",
"=",
"0",
")",
":",
"start",
"=",
"self",
".",
"sunrise_utc",
"(",
"date",
",",
"latitude",
",",
"longitude",
",",
"observer_elevation",
")",
"end",
"=",
"self",
".",
"sunset_utc",
"(",
"date",
",",
"latitude",
",",
"longitude",
",",
"observer_elevation",
")",
"return",
"start",
",",
"end"
] |
Calculate daylight start and end times in the UTC timezone.
:param date: Date to calculate for.
:type date: :class:`datetime.date`
:param latitude: Latitude - Northern latitudes should be positive
:type latitude: float
:param longitude: Longitude - Eastern longitudes should be positive
:type longitude: float
:param observer_elevation: Elevation in metres to calculate daylight for
:type observer_elevation: int
:return: A tuple of the UTC date and time at which daylight starts and ends.
:rtype: (:class:`~datetime.datetime`, :class:`~datetime.datetime`)
|
[
"Calculate",
"daylight",
"start",
"and",
"end",
"times",
"in",
"the",
"UTC",
"timezone",
"."
] |
b0aa63fce692357cd33c2bf36c69ed5b6582440c
|
https://github.com/sffjunkie/astral/blob/b0aa63fce692357cd33c2bf36c69ed5b6582440c/src/astral.py#L2061-L2080
|
11,586
|
sffjunkie/astral
|
src/astral.py
|
Astral.night_utc
|
def night_utc(self, date, latitude, longitude, observer_elevation=0):
"""Calculate night start and end times in the UTC timezone.
Night is calculated to be between astronomical dusk on the
date specified and astronomical dawn of the next day.
:param date: Date to calculate for.
:type date: :class:`datetime.date`
:param latitude: Latitude - Northern latitudes should be positive
:type latitude: float
:param longitude: Longitude - Eastern longitudes should be positive
:type longitude: float
:param observer_elevation: Elevation in metres to calculate night for
:type observer_elevation: int
:return: A tuple of the UTC date and time at which night starts and ends.
:rtype: (:class:`~datetime.datetime`, :class:`~datetime.datetime`)
"""
start = self.dusk_utc(date, latitude, longitude, 18, observer_elevation)
tomorrow = date + datetime.timedelta(days=1)
end = self.dawn_utc(tomorrow, latitude, longitude, 18, observer_elevation)
return start, end
|
python
|
def night_utc(self, date, latitude, longitude, observer_elevation=0):
"""Calculate night start and end times in the UTC timezone.
Night is calculated to be between astronomical dusk on the
date specified and astronomical dawn of the next day.
:param date: Date to calculate for.
:type date: :class:`datetime.date`
:param latitude: Latitude - Northern latitudes should be positive
:type latitude: float
:param longitude: Longitude - Eastern longitudes should be positive
:type longitude: float
:param observer_elevation: Elevation in metres to calculate night for
:type observer_elevation: int
:return: A tuple of the UTC date and time at which night starts and ends.
:rtype: (:class:`~datetime.datetime`, :class:`~datetime.datetime`)
"""
start = self.dusk_utc(date, latitude, longitude, 18, observer_elevation)
tomorrow = date + datetime.timedelta(days=1)
end = self.dawn_utc(tomorrow, latitude, longitude, 18, observer_elevation)
return start, end
|
[
"def",
"night_utc",
"(",
"self",
",",
"date",
",",
"latitude",
",",
"longitude",
",",
"observer_elevation",
"=",
"0",
")",
":",
"start",
"=",
"self",
".",
"dusk_utc",
"(",
"date",
",",
"latitude",
",",
"longitude",
",",
"18",
",",
"observer_elevation",
")",
"tomorrow",
"=",
"date",
"+",
"datetime",
".",
"timedelta",
"(",
"days",
"=",
"1",
")",
"end",
"=",
"self",
".",
"dawn_utc",
"(",
"tomorrow",
",",
"latitude",
",",
"longitude",
",",
"18",
",",
"observer_elevation",
")",
"return",
"start",
",",
"end"
] |
Calculate night start and end times in the UTC timezone.
Night is calculated to be between astronomical dusk on the
date specified and astronomical dawn of the next day.
:param date: Date to calculate for.
:type date: :class:`datetime.date`
:param latitude: Latitude - Northern latitudes should be positive
:type latitude: float
:param longitude: Longitude - Eastern longitudes should be positive
:type longitude: float
:param observer_elevation: Elevation in metres to calculate night for
:type observer_elevation: int
:return: A tuple of the UTC date and time at which night starts and ends.
:rtype: (:class:`~datetime.datetime`, :class:`~datetime.datetime`)
|
[
"Calculate",
"night",
"start",
"and",
"end",
"times",
"in",
"the",
"UTC",
"timezone",
"."
] |
b0aa63fce692357cd33c2bf36c69ed5b6582440c
|
https://github.com/sffjunkie/astral/blob/b0aa63fce692357cd33c2bf36c69ed5b6582440c/src/astral.py#L2082-L2105
|
11,587
|
sffjunkie/astral
|
src/astral.py
|
Astral.blue_hour_utc
|
def blue_hour_utc(self, direction, date, latitude, longitude, observer_elevation=0):
"""Returns the start and end times of the Blue Hour in the UTC timezone
when the sun is traversing in the specified direction.
This method uses the definition from PhotoPills i.e. the
blue hour is when the sun is between 6 and 4 degrees below the horizon.
:param direction: Determines whether the time is for the sun rising or setting.
Use ``astral.SUN_RISING`` or ``astral.SUN_SETTING``.
:type direction: int
:param date: The date for which to calculate the times.
:type date: :class:`datetime.date`
:param latitude: Latitude - Northern latitudes should be positive
:type latitude: float
:param longitude: Longitude - Eastern longitudes should be positive
:type longitude: float
:param observer_elevation: Elevation in metres to calculate the blue hour for
:type observer_elevation: int
:return: A tuple of the UTC date and time at which the Blue Hour starts and ends.
:rtype: (:class:`~datetime.datetime`, :class:`~datetime.datetime`)
"""
if date is None:
date = datetime.date.today()
start = self.time_at_elevation_utc(-6, direction, date, latitude, longitude, observer_elevation)
end = self.time_at_elevation_utc(-4, direction, date, latitude, longitude, observer_elevation)
if direction == SUN_RISING:
return start, end
else:
return end, start
|
python
|
def blue_hour_utc(self, direction, date, latitude, longitude, observer_elevation=0):
"""Returns the start and end times of the Blue Hour in the UTC timezone
when the sun is traversing in the specified direction.
This method uses the definition from PhotoPills i.e. the
blue hour is when the sun is between 6 and 4 degrees below the horizon.
:param direction: Determines whether the time is for the sun rising or setting.
Use ``astral.SUN_RISING`` or ``astral.SUN_SETTING``.
:type direction: int
:param date: The date for which to calculate the times.
:type date: :class:`datetime.date`
:param latitude: Latitude - Northern latitudes should be positive
:type latitude: float
:param longitude: Longitude - Eastern longitudes should be positive
:type longitude: float
:param observer_elevation: Elevation in metres to calculate the blue hour for
:type observer_elevation: int
:return: A tuple of the UTC date and time at which the Blue Hour starts and ends.
:rtype: (:class:`~datetime.datetime`, :class:`~datetime.datetime`)
"""
if date is None:
date = datetime.date.today()
start = self.time_at_elevation_utc(-6, direction, date, latitude, longitude, observer_elevation)
end = self.time_at_elevation_utc(-4, direction, date, latitude, longitude, observer_elevation)
if direction == SUN_RISING:
return start, end
else:
return end, start
|
[
"def",
"blue_hour_utc",
"(",
"self",
",",
"direction",
",",
"date",
",",
"latitude",
",",
"longitude",
",",
"observer_elevation",
"=",
"0",
")",
":",
"if",
"date",
"is",
"None",
":",
"date",
"=",
"datetime",
".",
"date",
".",
"today",
"(",
")",
"start",
"=",
"self",
".",
"time_at_elevation_utc",
"(",
"-",
"6",
",",
"direction",
",",
"date",
",",
"latitude",
",",
"longitude",
",",
"observer_elevation",
")",
"end",
"=",
"self",
".",
"time_at_elevation_utc",
"(",
"-",
"4",
",",
"direction",
",",
"date",
",",
"latitude",
",",
"longitude",
",",
"observer_elevation",
")",
"if",
"direction",
"==",
"SUN_RISING",
":",
"return",
"start",
",",
"end",
"else",
":",
"return",
"end",
",",
"start"
] |
Returns the start and end times of the Blue Hour in the UTC timezone
when the sun is traversing in the specified direction.
This method uses the definition from PhotoPills i.e. the
blue hour is when the sun is between 6 and 4 degrees below the horizon.
:param direction: Determines whether the time is for the sun rising or setting.
Use ``astral.SUN_RISING`` or ``astral.SUN_SETTING``.
:type direction: int
:param date: The date for which to calculate the times.
:type date: :class:`datetime.date`
:param latitude: Latitude - Northern latitudes should be positive
:type latitude: float
:param longitude: Longitude - Eastern longitudes should be positive
:type longitude: float
:param observer_elevation: Elevation in metres to calculate the blue hour for
:type observer_elevation: int
:return: A tuple of the UTC date and time at which the Blue Hour starts and ends.
:rtype: (:class:`~datetime.datetime`, :class:`~datetime.datetime`)
|
[
"Returns",
"the",
"start",
"and",
"end",
"times",
"of",
"the",
"Blue",
"Hour",
"in",
"the",
"UTC",
"timezone",
"when",
"the",
"sun",
"is",
"traversing",
"in",
"the",
"specified",
"direction",
"."
] |
b0aa63fce692357cd33c2bf36c69ed5b6582440c
|
https://github.com/sffjunkie/astral/blob/b0aa63fce692357cd33c2bf36c69ed5b6582440c/src/astral.py#L2179-L2211
|
11,588
|
sffjunkie/astral
|
src/astral.py
|
Astral.time_at_elevation_utc
|
def time_at_elevation_utc(self, elevation, direction, date, latitude, longitude, observer_elevation=0):
"""Calculate the time in the UTC timezone when the sun is at
the specified elevation on the specified date.
Note: This method uses positive elevations for those above the horizon.
:param elevation: Elevation in degrees above the horizon to calculate for.
:type elevation: float
:param direction: Determines whether the calculated time is for the sun rising or setting.
Use ``astral.SUN_RISING`` or ``astral.SUN_SETTING``. Default is rising.
:type direction: int
:param date: Date to calculate for.
:type date: :class:`datetime.date`
:param latitude: Latitude - Northern latitudes should be positive
:type latitude: float
:param longitude: Longitude - Eastern longitudes should be positive
:type longitude: float
:param observer_elevation: Elevation in metres to calculate time at elevation for
:type observer_elevation: int
:return: The UTC date and time at which the sun is at the required
elevation.
:rtype: :class:`~datetime.datetime`
"""
if elevation > 90.0:
elevation = 180.0 - elevation
direction = SUN_SETTING
depression = 90 - elevation
try:
return self._calc_time(depression, direction, date, latitude, longitude, observer_elevation)
except ValueError as exc:
if exc.args[0] == "math domain error":
raise AstralError(
("Sun never reaches an elevation of %d degrees" "at this location.")
% elevation
)
else:
raise
|
python
|
def time_at_elevation_utc(self, elevation, direction, date, latitude, longitude, observer_elevation=0):
"""Calculate the time in the UTC timezone when the sun is at
the specified elevation on the specified date.
Note: This method uses positive elevations for those above the horizon.
:param elevation: Elevation in degrees above the horizon to calculate for.
:type elevation: float
:param direction: Determines whether the calculated time is for the sun rising or setting.
Use ``astral.SUN_RISING`` or ``astral.SUN_SETTING``. Default is rising.
:type direction: int
:param date: Date to calculate for.
:type date: :class:`datetime.date`
:param latitude: Latitude - Northern latitudes should be positive
:type latitude: float
:param longitude: Longitude - Eastern longitudes should be positive
:type longitude: float
:param observer_elevation: Elevation in metres to calculate time at elevation for
:type observer_elevation: int
:return: The UTC date and time at which the sun is at the required
elevation.
:rtype: :class:`~datetime.datetime`
"""
if elevation > 90.0:
elevation = 180.0 - elevation
direction = SUN_SETTING
depression = 90 - elevation
try:
return self._calc_time(depression, direction, date, latitude, longitude, observer_elevation)
except ValueError as exc:
if exc.args[0] == "math domain error":
raise AstralError(
("Sun never reaches an elevation of %d degrees" "at this location.")
% elevation
)
else:
raise
|
[
"def",
"time_at_elevation_utc",
"(",
"self",
",",
"elevation",
",",
"direction",
",",
"date",
",",
"latitude",
",",
"longitude",
",",
"observer_elevation",
"=",
"0",
")",
":",
"if",
"elevation",
">",
"90.0",
":",
"elevation",
"=",
"180.0",
"-",
"elevation",
"direction",
"=",
"SUN_SETTING",
"depression",
"=",
"90",
"-",
"elevation",
"try",
":",
"return",
"self",
".",
"_calc_time",
"(",
"depression",
",",
"direction",
",",
"date",
",",
"latitude",
",",
"longitude",
",",
"observer_elevation",
")",
"except",
"ValueError",
"as",
"exc",
":",
"if",
"exc",
".",
"args",
"[",
"0",
"]",
"==",
"\"math domain error\"",
":",
"raise",
"AstralError",
"(",
"(",
"\"Sun never reaches an elevation of %d degrees\"",
"\"at this location.\"",
")",
"%",
"elevation",
")",
"else",
":",
"raise"
] |
Calculate the time in the UTC timezone when the sun is at
the specified elevation on the specified date.
Note: This method uses positive elevations for those above the horizon.
:param elevation: Elevation in degrees above the horizon to calculate for.
:type elevation: float
:param direction: Determines whether the calculated time is for the sun rising or setting.
Use ``astral.SUN_RISING`` or ``astral.SUN_SETTING``. Default is rising.
:type direction: int
:param date: Date to calculate for.
:type date: :class:`datetime.date`
:param latitude: Latitude - Northern latitudes should be positive
:type latitude: float
:param longitude: Longitude - Eastern longitudes should be positive
:type longitude: float
:param observer_elevation: Elevation in metres to calculate time at elevation for
:type observer_elevation: int
:return: The UTC date and time at which the sun is at the required
elevation.
:rtype: :class:`~datetime.datetime`
|
[
"Calculate",
"the",
"time",
"in",
"the",
"UTC",
"timezone",
"when",
"the",
"sun",
"is",
"at",
"the",
"specified",
"elevation",
"on",
"the",
"specified",
"date",
"."
] |
b0aa63fce692357cd33c2bf36c69ed5b6582440c
|
https://github.com/sffjunkie/astral/blob/b0aa63fce692357cd33c2bf36c69ed5b6582440c/src/astral.py#L2213-L2252
|
11,589
|
sffjunkie/astral
|
src/astral.py
|
Astral.solar_azimuth
|
def solar_azimuth(self, dateandtime, latitude, longitude):
"""Calculate the azimuth angle of the sun.
:param dateandtime: The date and time for which to calculate
the angle.
:type dateandtime: :class:`~datetime.datetime`
:param latitude: Latitude - Northern latitudes should be positive
:type latitude: float
:param longitude: Longitude - Eastern longitudes should be positive
:type longitude: float
:return: The azimuth angle in degrees clockwise from North.
:rtype: float
If `dateandtime` is a naive Python datetime then it is assumed to be
in the UTC timezone.
"""
if latitude > 89.8:
latitude = 89.8
if latitude < -89.8:
latitude = -89.8
if dateandtime.tzinfo is None:
zone = 0
utc_datetime = dateandtime
else:
zone = -dateandtime.utcoffset().total_seconds() / 3600.0
utc_datetime = dateandtime.astimezone(pytz.utc)
timenow = (
utc_datetime.hour
+ (utc_datetime.minute / 60.0)
+ (utc_datetime.second / 3600.0)
)
JD = self._julianday(dateandtime)
t = self._jday_to_jcentury(JD + timenow / 24.0)
theta = self._sun_declination(t)
eqtime = self._eq_of_time(t)
solarDec = theta # in degrees
solarTimeFix = eqtime - (4.0 * -longitude) + (60 * zone)
trueSolarTime = (
dateandtime.hour * 60.0
+ dateandtime.minute
+ dateandtime.second / 60.0
+ solarTimeFix
)
# in minutes
while trueSolarTime > 1440:
trueSolarTime = trueSolarTime - 1440
hourangle = trueSolarTime / 4.0 - 180.0
# Thanks to Louis Schwarzmayr for the next line:
if hourangle < -180:
hourangle = hourangle + 360.0
harad = radians(hourangle)
csz = sin(radians(latitude)) * sin(radians(solarDec)) + cos(
radians(latitude)
) * cos(radians(solarDec)) * cos(harad)
if csz > 1.0:
csz = 1.0
elif csz < -1.0:
csz = -1.0
zenith = degrees(acos(csz))
azDenom = cos(radians(latitude)) * sin(radians(zenith))
if abs(azDenom) > 0.001:
azRad = (
(sin(radians(latitude)) * cos(radians(zenith))) - sin(radians(solarDec))
) / azDenom
if abs(azRad) > 1.0:
if azRad < 0:
azRad = -1.0
else:
azRad = 1.0
azimuth = 180.0 - degrees(acos(azRad))
if hourangle > 0.0:
azimuth = -azimuth
else:
if latitude > 0.0:
azimuth = 180.0
else:
azimuth = 0.0
if azimuth < 0.0:
azimuth = azimuth + 360.0
return azimuth
|
python
|
def solar_azimuth(self, dateandtime, latitude, longitude):
"""Calculate the azimuth angle of the sun.
:param dateandtime: The date and time for which to calculate
the angle.
:type dateandtime: :class:`~datetime.datetime`
:param latitude: Latitude - Northern latitudes should be positive
:type latitude: float
:param longitude: Longitude - Eastern longitudes should be positive
:type longitude: float
:return: The azimuth angle in degrees clockwise from North.
:rtype: float
If `dateandtime` is a naive Python datetime then it is assumed to be
in the UTC timezone.
"""
if latitude > 89.8:
latitude = 89.8
if latitude < -89.8:
latitude = -89.8
if dateandtime.tzinfo is None:
zone = 0
utc_datetime = dateandtime
else:
zone = -dateandtime.utcoffset().total_seconds() / 3600.0
utc_datetime = dateandtime.astimezone(pytz.utc)
timenow = (
utc_datetime.hour
+ (utc_datetime.minute / 60.0)
+ (utc_datetime.second / 3600.0)
)
JD = self._julianday(dateandtime)
t = self._jday_to_jcentury(JD + timenow / 24.0)
theta = self._sun_declination(t)
eqtime = self._eq_of_time(t)
solarDec = theta # in degrees
solarTimeFix = eqtime - (4.0 * -longitude) + (60 * zone)
trueSolarTime = (
dateandtime.hour * 60.0
+ dateandtime.minute
+ dateandtime.second / 60.0
+ solarTimeFix
)
# in minutes
while trueSolarTime > 1440:
trueSolarTime = trueSolarTime - 1440
hourangle = trueSolarTime / 4.0 - 180.0
# Thanks to Louis Schwarzmayr for the next line:
if hourangle < -180:
hourangle = hourangle + 360.0
harad = radians(hourangle)
csz = sin(radians(latitude)) * sin(radians(solarDec)) + cos(
radians(latitude)
) * cos(radians(solarDec)) * cos(harad)
if csz > 1.0:
csz = 1.0
elif csz < -1.0:
csz = -1.0
zenith = degrees(acos(csz))
azDenom = cos(radians(latitude)) * sin(radians(zenith))
if abs(azDenom) > 0.001:
azRad = (
(sin(radians(latitude)) * cos(radians(zenith))) - sin(radians(solarDec))
) / azDenom
if abs(azRad) > 1.0:
if azRad < 0:
azRad = -1.0
else:
azRad = 1.0
azimuth = 180.0 - degrees(acos(azRad))
if hourangle > 0.0:
azimuth = -azimuth
else:
if latitude > 0.0:
azimuth = 180.0
else:
azimuth = 0.0
if azimuth < 0.0:
azimuth = azimuth + 360.0
return azimuth
|
[
"def",
"solar_azimuth",
"(",
"self",
",",
"dateandtime",
",",
"latitude",
",",
"longitude",
")",
":",
"if",
"latitude",
">",
"89.8",
":",
"latitude",
"=",
"89.8",
"if",
"latitude",
"<",
"-",
"89.8",
":",
"latitude",
"=",
"-",
"89.8",
"if",
"dateandtime",
".",
"tzinfo",
"is",
"None",
":",
"zone",
"=",
"0",
"utc_datetime",
"=",
"dateandtime",
"else",
":",
"zone",
"=",
"-",
"dateandtime",
".",
"utcoffset",
"(",
")",
".",
"total_seconds",
"(",
")",
"/",
"3600.0",
"utc_datetime",
"=",
"dateandtime",
".",
"astimezone",
"(",
"pytz",
".",
"utc",
")",
"timenow",
"=",
"(",
"utc_datetime",
".",
"hour",
"+",
"(",
"utc_datetime",
".",
"minute",
"/",
"60.0",
")",
"+",
"(",
"utc_datetime",
".",
"second",
"/",
"3600.0",
")",
")",
"JD",
"=",
"self",
".",
"_julianday",
"(",
"dateandtime",
")",
"t",
"=",
"self",
".",
"_jday_to_jcentury",
"(",
"JD",
"+",
"timenow",
"/",
"24.0",
")",
"theta",
"=",
"self",
".",
"_sun_declination",
"(",
"t",
")",
"eqtime",
"=",
"self",
".",
"_eq_of_time",
"(",
"t",
")",
"solarDec",
"=",
"theta",
"# in degrees",
"solarTimeFix",
"=",
"eqtime",
"-",
"(",
"4.0",
"*",
"-",
"longitude",
")",
"+",
"(",
"60",
"*",
"zone",
")",
"trueSolarTime",
"=",
"(",
"dateandtime",
".",
"hour",
"*",
"60.0",
"+",
"dateandtime",
".",
"minute",
"+",
"dateandtime",
".",
"second",
"/",
"60.0",
"+",
"solarTimeFix",
")",
"# in minutes",
"while",
"trueSolarTime",
">",
"1440",
":",
"trueSolarTime",
"=",
"trueSolarTime",
"-",
"1440",
"hourangle",
"=",
"trueSolarTime",
"/",
"4.0",
"-",
"180.0",
"# Thanks to Louis Schwarzmayr for the next line:",
"if",
"hourangle",
"<",
"-",
"180",
":",
"hourangle",
"=",
"hourangle",
"+",
"360.0",
"harad",
"=",
"radians",
"(",
"hourangle",
")",
"csz",
"=",
"sin",
"(",
"radians",
"(",
"latitude",
")",
")",
"*",
"sin",
"(",
"radians",
"(",
"solarDec",
")",
")",
"+",
"cos",
"(",
"radians",
"(",
"latitude",
")",
")",
"*",
"cos",
"(",
"radians",
"(",
"solarDec",
")",
")",
"*",
"cos",
"(",
"harad",
")",
"if",
"csz",
">",
"1.0",
":",
"csz",
"=",
"1.0",
"elif",
"csz",
"<",
"-",
"1.0",
":",
"csz",
"=",
"-",
"1.0",
"zenith",
"=",
"degrees",
"(",
"acos",
"(",
"csz",
")",
")",
"azDenom",
"=",
"cos",
"(",
"radians",
"(",
"latitude",
")",
")",
"*",
"sin",
"(",
"radians",
"(",
"zenith",
")",
")",
"if",
"abs",
"(",
"azDenom",
")",
">",
"0.001",
":",
"azRad",
"=",
"(",
"(",
"sin",
"(",
"radians",
"(",
"latitude",
")",
")",
"*",
"cos",
"(",
"radians",
"(",
"zenith",
")",
")",
")",
"-",
"sin",
"(",
"radians",
"(",
"solarDec",
")",
")",
")",
"/",
"azDenom",
"if",
"abs",
"(",
"azRad",
")",
">",
"1.0",
":",
"if",
"azRad",
"<",
"0",
":",
"azRad",
"=",
"-",
"1.0",
"else",
":",
"azRad",
"=",
"1.0",
"azimuth",
"=",
"180.0",
"-",
"degrees",
"(",
"acos",
"(",
"azRad",
")",
")",
"if",
"hourangle",
">",
"0.0",
":",
"azimuth",
"=",
"-",
"azimuth",
"else",
":",
"if",
"latitude",
">",
"0.0",
":",
"azimuth",
"=",
"180.0",
"else",
":",
"azimuth",
"=",
"0.0",
"if",
"azimuth",
"<",
"0.0",
":",
"azimuth",
"=",
"azimuth",
"+",
"360.0",
"return",
"azimuth"
] |
Calculate the azimuth angle of the sun.
:param dateandtime: The date and time for which to calculate
the angle.
:type dateandtime: :class:`~datetime.datetime`
:param latitude: Latitude - Northern latitudes should be positive
:type latitude: float
:param longitude: Longitude - Eastern longitudes should be positive
:type longitude: float
:return: The azimuth angle in degrees clockwise from North.
:rtype: float
If `dateandtime` is a naive Python datetime then it is assumed to be
in the UTC timezone.
|
[
"Calculate",
"the",
"azimuth",
"angle",
"of",
"the",
"sun",
"."
] |
b0aa63fce692357cd33c2bf36c69ed5b6582440c
|
https://github.com/sffjunkie/astral/blob/b0aa63fce692357cd33c2bf36c69ed5b6582440c/src/astral.py#L2254-L2353
|
11,590
|
sffjunkie/astral
|
src/astral.py
|
Astral.solar_zenith
|
def solar_zenith(self, dateandtime, latitude, longitude):
"""Calculates the solar zenith angle.
:param dateandtime: The date and time for which to calculate
the angle.
:type dateandtime: :class:`~datetime.datetime`
:param latitude: Latitude - Northern latitudes should be positive
:type latitude: float
:param longitude: Longitude - Eastern longitudes should be positive
:type longitude: float
:return: The zenith angle in degrees from vertical.
:rtype: float
If `dateandtime` is a naive Python datetime then it is assumed to be
in the UTC timezone.
"""
return 90.0 - self.solar_elevation(dateandtime, latitude, longitude)
|
python
|
def solar_zenith(self, dateandtime, latitude, longitude):
"""Calculates the solar zenith angle.
:param dateandtime: The date and time for which to calculate
the angle.
:type dateandtime: :class:`~datetime.datetime`
:param latitude: Latitude - Northern latitudes should be positive
:type latitude: float
:param longitude: Longitude - Eastern longitudes should be positive
:type longitude: float
:return: The zenith angle in degrees from vertical.
:rtype: float
If `dateandtime` is a naive Python datetime then it is assumed to be
in the UTC timezone.
"""
return 90.0 - self.solar_elevation(dateandtime, latitude, longitude)
|
[
"def",
"solar_zenith",
"(",
"self",
",",
"dateandtime",
",",
"latitude",
",",
"longitude",
")",
":",
"return",
"90.0",
"-",
"self",
".",
"solar_elevation",
"(",
"dateandtime",
",",
"latitude",
",",
"longitude",
")"
] |
Calculates the solar zenith angle.
:param dateandtime: The date and time for which to calculate
the angle.
:type dateandtime: :class:`~datetime.datetime`
:param latitude: Latitude - Northern latitudes should be positive
:type latitude: float
:param longitude: Longitude - Eastern longitudes should be positive
:type longitude: float
:return: The zenith angle in degrees from vertical.
:rtype: float
If `dateandtime` is a naive Python datetime then it is assumed to be
in the UTC timezone.
|
[
"Calculates",
"the",
"solar",
"zenith",
"angle",
"."
] |
b0aa63fce692357cd33c2bf36c69ed5b6582440c
|
https://github.com/sffjunkie/astral/blob/b0aa63fce692357cd33c2bf36c69ed5b6582440c/src/astral.py#L2482-L2500
|
11,591
|
sffjunkie/astral
|
src/astral.py
|
Astral.moon_phase
|
def moon_phase(self, date, rtype=int):
"""Calculates the phase of the moon on the specified date.
:param date: The date to calculate the phase for.
:type date: :class:`datetime.date`
:param rtype: The type to return either int (default) or float.
:return:
A number designating the phase.
| 0 = New moon
| 7 = First quarter
| 14 = Full moon
| 21 = Last quarter
"""
if rtype != float and rtype != int:
rtype = int
moon = self._moon_phase_asfloat(date)
if moon >= 28.0:
moon -= 28.0
moon = rtype(moon)
return moon
|
python
|
def moon_phase(self, date, rtype=int):
"""Calculates the phase of the moon on the specified date.
:param date: The date to calculate the phase for.
:type date: :class:`datetime.date`
:param rtype: The type to return either int (default) or float.
:return:
A number designating the phase.
| 0 = New moon
| 7 = First quarter
| 14 = Full moon
| 21 = Last quarter
"""
if rtype != float and rtype != int:
rtype = int
moon = self._moon_phase_asfloat(date)
if moon >= 28.0:
moon -= 28.0
moon = rtype(moon)
return moon
|
[
"def",
"moon_phase",
"(",
"self",
",",
"date",
",",
"rtype",
"=",
"int",
")",
":",
"if",
"rtype",
"!=",
"float",
"and",
"rtype",
"!=",
"int",
":",
"rtype",
"=",
"int",
"moon",
"=",
"self",
".",
"_moon_phase_asfloat",
"(",
"date",
")",
"if",
"moon",
">=",
"28.0",
":",
"moon",
"-=",
"28.0",
"moon",
"=",
"rtype",
"(",
"moon",
")",
"return",
"moon"
] |
Calculates the phase of the moon on the specified date.
:param date: The date to calculate the phase for.
:type date: :class:`datetime.date`
:param rtype: The type to return either int (default) or float.
:return:
A number designating the phase.
| 0 = New moon
| 7 = First quarter
| 14 = Full moon
| 21 = Last quarter
|
[
"Calculates",
"the",
"phase",
"of",
"the",
"moon",
"on",
"the",
"specified",
"date",
"."
] |
b0aa63fce692357cd33c2bf36c69ed5b6582440c
|
https://github.com/sffjunkie/astral/blob/b0aa63fce692357cd33c2bf36c69ed5b6582440c/src/astral.py#L2502-L2526
|
11,592
|
sffjunkie/astral
|
src/astral.py
|
Astral.rahukaalam_utc
|
def rahukaalam_utc(self, date, latitude, longitude, observer_elevation=0):
"""Calculate ruhakaalam times in the UTC timezone.
:param date: Date to calculate for.
:type date: :class:`datetime.date`
:param latitude: Latitude - Northern latitudes should be positive
:type latitude: float
:param longitude: Longitude - Eastern longitudes should be positive
:type longitude: float
:param observer_elevation: Elevation in metres to calculate Rahukaalam for
:type observer_elevation: int
:return: Tuple containing the start and end times for Rahukaalam.
:rtype: tuple
"""
if date is None:
date = datetime.date.today()
sunrise = self.sunrise_utc(date, latitude, longitude, observer_elevation)
sunset = self.sunset_utc(date, latitude, longitude, observer_elevation)
octant_duration = datetime.timedelta(seconds=(sunset - sunrise).seconds / 8)
# Mo,Sa,Fr,We,Th,Tu,Su
octant_index = [1, 6, 4, 5, 3, 2, 7]
weekday = date.weekday()
octant = octant_index[weekday]
start = sunrise + (octant_duration * octant)
end = start + octant_duration
return start, end
|
python
|
def rahukaalam_utc(self, date, latitude, longitude, observer_elevation=0):
"""Calculate ruhakaalam times in the UTC timezone.
:param date: Date to calculate for.
:type date: :class:`datetime.date`
:param latitude: Latitude - Northern latitudes should be positive
:type latitude: float
:param longitude: Longitude - Eastern longitudes should be positive
:type longitude: float
:param observer_elevation: Elevation in metres to calculate Rahukaalam for
:type observer_elevation: int
:return: Tuple containing the start and end times for Rahukaalam.
:rtype: tuple
"""
if date is None:
date = datetime.date.today()
sunrise = self.sunrise_utc(date, latitude, longitude, observer_elevation)
sunset = self.sunset_utc(date, latitude, longitude, observer_elevation)
octant_duration = datetime.timedelta(seconds=(sunset - sunrise).seconds / 8)
# Mo,Sa,Fr,We,Th,Tu,Su
octant_index = [1, 6, 4, 5, 3, 2, 7]
weekday = date.weekday()
octant = octant_index[weekday]
start = sunrise + (octant_duration * octant)
end = start + octant_duration
return start, end
|
[
"def",
"rahukaalam_utc",
"(",
"self",
",",
"date",
",",
"latitude",
",",
"longitude",
",",
"observer_elevation",
"=",
"0",
")",
":",
"if",
"date",
"is",
"None",
":",
"date",
"=",
"datetime",
".",
"date",
".",
"today",
"(",
")",
"sunrise",
"=",
"self",
".",
"sunrise_utc",
"(",
"date",
",",
"latitude",
",",
"longitude",
",",
"observer_elevation",
")",
"sunset",
"=",
"self",
".",
"sunset_utc",
"(",
"date",
",",
"latitude",
",",
"longitude",
",",
"observer_elevation",
")",
"octant_duration",
"=",
"datetime",
".",
"timedelta",
"(",
"seconds",
"=",
"(",
"sunset",
"-",
"sunrise",
")",
".",
"seconds",
"/",
"8",
")",
"# Mo,Sa,Fr,We,Th,Tu,Su",
"octant_index",
"=",
"[",
"1",
",",
"6",
",",
"4",
",",
"5",
",",
"3",
",",
"2",
",",
"7",
"]",
"weekday",
"=",
"date",
".",
"weekday",
"(",
")",
"octant",
"=",
"octant_index",
"[",
"weekday",
"]",
"start",
"=",
"sunrise",
"+",
"(",
"octant_duration",
"*",
"octant",
")",
"end",
"=",
"start",
"+",
"octant_duration",
"return",
"start",
",",
"end"
] |
Calculate ruhakaalam times in the UTC timezone.
:param date: Date to calculate for.
:type date: :class:`datetime.date`
:param latitude: Latitude - Northern latitudes should be positive
:type latitude: float
:param longitude: Longitude - Eastern longitudes should be positive
:type longitude: float
:param observer_elevation: Elevation in metres to calculate Rahukaalam for
:type observer_elevation: int
:return: Tuple containing the start and end times for Rahukaalam.
:rtype: tuple
|
[
"Calculate",
"ruhakaalam",
"times",
"in",
"the",
"UTC",
"timezone",
"."
] |
b0aa63fce692357cd33c2bf36c69ed5b6582440c
|
https://github.com/sffjunkie/astral/blob/b0aa63fce692357cd33c2bf36c69ed5b6582440c/src/astral.py#L2528-L2561
|
11,593
|
sffjunkie/astral
|
src/astral.py
|
Astral._depression_adjustment
|
def _depression_adjustment(self, elevation):
"""Calculate the extra degrees of depression due to the increase in elevation.
:param elevation: Elevation above the earth in metres
:type elevation: float
"""
if elevation <= 0:
return 0
r = 6356900 # radius of the earth
a1 = r
h1 = r + elevation
theta1 = acos(a1 / h1)
a2 = r * sin(theta1)
b2 = r - (r * cos(theta1))
h2 = sqrt(pow(a2, 2) + pow(b2, 2))
alpha = acos(a2 / h2)
return degrees(alpha)
|
python
|
def _depression_adjustment(self, elevation):
"""Calculate the extra degrees of depression due to the increase in elevation.
:param elevation: Elevation above the earth in metres
:type elevation: float
"""
if elevation <= 0:
return 0
r = 6356900 # radius of the earth
a1 = r
h1 = r + elevation
theta1 = acos(a1 / h1)
a2 = r * sin(theta1)
b2 = r - (r * cos(theta1))
h2 = sqrt(pow(a2, 2) + pow(b2, 2))
alpha = acos(a2 / h2)
return degrees(alpha)
|
[
"def",
"_depression_adjustment",
"(",
"self",
",",
"elevation",
")",
":",
"if",
"elevation",
"<=",
"0",
":",
"return",
"0",
"r",
"=",
"6356900",
"# radius of the earth",
"a1",
"=",
"r",
"h1",
"=",
"r",
"+",
"elevation",
"theta1",
"=",
"acos",
"(",
"a1",
"/",
"h1",
")",
"a2",
"=",
"r",
"*",
"sin",
"(",
"theta1",
")",
"b2",
"=",
"r",
"-",
"(",
"r",
"*",
"cos",
"(",
"theta1",
")",
")",
"h2",
"=",
"sqrt",
"(",
"pow",
"(",
"a2",
",",
"2",
")",
"+",
"pow",
"(",
"b2",
",",
"2",
")",
")",
"alpha",
"=",
"acos",
"(",
"a2",
"/",
"h2",
")",
"return",
"degrees",
"(",
"alpha",
")"
] |
Calculate the extra degrees of depression due to the increase in elevation.
:param elevation: Elevation above the earth in metres
:type elevation: float
|
[
"Calculate",
"the",
"extra",
"degrees",
"of",
"depression",
"due",
"to",
"the",
"increase",
"in",
"elevation",
"."
] |
b0aa63fce692357cd33c2bf36c69ed5b6582440c
|
https://github.com/sffjunkie/astral/blob/b0aa63fce692357cd33c2bf36c69ed5b6582440c/src/astral.py#L2807-L2827
|
11,594
|
joowani/kq
|
example/worker-cli.py
|
callback
|
def callback(status, message, job, result, exception, stacktrace):
"""Example callback function.
:param status: Job status. Possible values are "invalid" (job could not be
deserialized or was malformed), "failure" (job raised an exception),
"timeout" (job timed out), or "success" (job finished successfully and
returned a result).
:type status: str
:param message: Kafka message.
:type message: kq.Message
:param job: Job object, or None if **status** was "invalid".
:type job: kq.Job
:param result: Job result, or None if an exception was raised.
:type result: object | None
:param exception: Exception raised by job, or None if there was none.
:type exception: Exception | None
:param stacktrace: Exception traceback, or None if there was none.
:type stacktrace: str | None
"""
assert status in ['invalid', 'success', 'timeout', 'failure']
assert isinstance(message, Message)
if status == 'invalid':
assert job is None
assert result is None
assert exception is None
assert stacktrace is None
if status == 'success':
assert isinstance(job, Job)
assert exception is None
assert stacktrace is None
elif status == 'timeout':
assert isinstance(job, Job)
assert result is None
assert exception is None
assert stacktrace is None
elif status == 'failure':
assert isinstance(job, Job)
assert result is None
assert exception is not None
assert stacktrace is not None
|
python
|
def callback(status, message, job, result, exception, stacktrace):
"""Example callback function.
:param status: Job status. Possible values are "invalid" (job could not be
deserialized or was malformed), "failure" (job raised an exception),
"timeout" (job timed out), or "success" (job finished successfully and
returned a result).
:type status: str
:param message: Kafka message.
:type message: kq.Message
:param job: Job object, or None if **status** was "invalid".
:type job: kq.Job
:param result: Job result, or None if an exception was raised.
:type result: object | None
:param exception: Exception raised by job, or None if there was none.
:type exception: Exception | None
:param stacktrace: Exception traceback, or None if there was none.
:type stacktrace: str | None
"""
assert status in ['invalid', 'success', 'timeout', 'failure']
assert isinstance(message, Message)
if status == 'invalid':
assert job is None
assert result is None
assert exception is None
assert stacktrace is None
if status == 'success':
assert isinstance(job, Job)
assert exception is None
assert stacktrace is None
elif status == 'timeout':
assert isinstance(job, Job)
assert result is None
assert exception is None
assert stacktrace is None
elif status == 'failure':
assert isinstance(job, Job)
assert result is None
assert exception is not None
assert stacktrace is not None
|
[
"def",
"callback",
"(",
"status",
",",
"message",
",",
"job",
",",
"result",
",",
"exception",
",",
"stacktrace",
")",
":",
"assert",
"status",
"in",
"[",
"'invalid'",
",",
"'success'",
",",
"'timeout'",
",",
"'failure'",
"]",
"assert",
"isinstance",
"(",
"message",
",",
"Message",
")",
"if",
"status",
"==",
"'invalid'",
":",
"assert",
"job",
"is",
"None",
"assert",
"result",
"is",
"None",
"assert",
"exception",
"is",
"None",
"assert",
"stacktrace",
"is",
"None",
"if",
"status",
"==",
"'success'",
":",
"assert",
"isinstance",
"(",
"job",
",",
"Job",
")",
"assert",
"exception",
"is",
"None",
"assert",
"stacktrace",
"is",
"None",
"elif",
"status",
"==",
"'timeout'",
":",
"assert",
"isinstance",
"(",
"job",
",",
"Job",
")",
"assert",
"result",
"is",
"None",
"assert",
"exception",
"is",
"None",
"assert",
"stacktrace",
"is",
"None",
"elif",
"status",
"==",
"'failure'",
":",
"assert",
"isinstance",
"(",
"job",
",",
"Job",
")",
"assert",
"result",
"is",
"None",
"assert",
"exception",
"is",
"not",
"None",
"assert",
"stacktrace",
"is",
"not",
"None"
] |
Example callback function.
:param status: Job status. Possible values are "invalid" (job could not be
deserialized or was malformed), "failure" (job raised an exception),
"timeout" (job timed out), or "success" (job finished successfully and
returned a result).
:type status: str
:param message: Kafka message.
:type message: kq.Message
:param job: Job object, or None if **status** was "invalid".
:type job: kq.Job
:param result: Job result, or None if an exception was raised.
:type result: object | None
:param exception: Exception raised by job, or None if there was none.
:type exception: Exception | None
:param stacktrace: Exception traceback, or None if there was none.
:type stacktrace: str | None
|
[
"Example",
"callback",
"function",
"."
] |
f5ff3f1828cc1d9de668f82b2d18a98026ce4281
|
https://github.com/joowani/kq/blob/f5ff3f1828cc1d9de668f82b2d18a98026ce4281/example/worker-cli.py#L19-L62
|
11,595
|
joowani/kq
|
kq/worker.py
|
Worker._execute_callback
|
def _execute_callback(self, status, message, job, res, err, stacktrace):
"""Execute the callback.
:param status: Job status. Possible values are "invalid" (job could not
be deserialized or was malformed), "failure" (job raised an error),
"timeout" (job timed out), or "success" (job finished successfully
and returned a result).
:type status: str
:param message: Kafka message.
:type message: :doc:`kq.Message <message>`
:param job: Job object, or None if **status** was "invalid".
:type job: kq.Job
:param res: Job result, or None if an exception was raised.
:type res: object | None
:param err: Exception raised by job, or None if there was none.
:type err: Exception | None
:param stacktrace: Exception traceback, or None if there was none.
:type stacktrace: str | None
"""
if self._callback is not None:
try:
self._logger.info('Executing callback ...')
self._callback(status, message, job, res, err, stacktrace)
except Exception as e:
self._logger.exception(
'Callback raised an exception: {}'.format(e))
|
python
|
def _execute_callback(self, status, message, job, res, err, stacktrace):
"""Execute the callback.
:param status: Job status. Possible values are "invalid" (job could not
be deserialized or was malformed), "failure" (job raised an error),
"timeout" (job timed out), or "success" (job finished successfully
and returned a result).
:type status: str
:param message: Kafka message.
:type message: :doc:`kq.Message <message>`
:param job: Job object, or None if **status** was "invalid".
:type job: kq.Job
:param res: Job result, or None if an exception was raised.
:type res: object | None
:param err: Exception raised by job, or None if there was none.
:type err: Exception | None
:param stacktrace: Exception traceback, or None if there was none.
:type stacktrace: str | None
"""
if self._callback is not None:
try:
self._logger.info('Executing callback ...')
self._callback(status, message, job, res, err, stacktrace)
except Exception as e:
self._logger.exception(
'Callback raised an exception: {}'.format(e))
|
[
"def",
"_execute_callback",
"(",
"self",
",",
"status",
",",
"message",
",",
"job",
",",
"res",
",",
"err",
",",
"stacktrace",
")",
":",
"if",
"self",
".",
"_callback",
"is",
"not",
"None",
":",
"try",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"'Executing callback ...'",
")",
"self",
".",
"_callback",
"(",
"status",
",",
"message",
",",
"job",
",",
"res",
",",
"err",
",",
"stacktrace",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"_logger",
".",
"exception",
"(",
"'Callback raised an exception: {}'",
".",
"format",
"(",
"e",
")",
")"
] |
Execute the callback.
:param status: Job status. Possible values are "invalid" (job could not
be deserialized or was malformed), "failure" (job raised an error),
"timeout" (job timed out), or "success" (job finished successfully
and returned a result).
:type status: str
:param message: Kafka message.
:type message: :doc:`kq.Message <message>`
:param job: Job object, or None if **status** was "invalid".
:type job: kq.Job
:param res: Job result, or None if an exception was raised.
:type res: object | None
:param err: Exception raised by job, or None if there was none.
:type err: Exception | None
:param stacktrace: Exception traceback, or None if there was none.
:type stacktrace: str | None
|
[
"Execute",
"the",
"callback",
"."
] |
f5ff3f1828cc1d9de668f82b2d18a98026ce4281
|
https://github.com/joowani/kq/blob/f5ff3f1828cc1d9de668f82b2d18a98026ce4281/kq/worker.py#L106-L131
|
11,596
|
joowani/kq
|
kq/worker.py
|
Worker._process_message
|
def _process_message(self, msg):
"""De-serialize the message and execute the job.
:param msg: Kafka message.
:type msg: :doc:`kq.Message <message>`
"""
self._logger.info(
'Processing Message(topic={}, partition={}, offset={}) ...'
.format(msg.topic, msg.partition, msg.offset))
try:
job = self._deserializer(msg.value)
job_repr = get_call_repr(job.func, *job.args, **job.kwargs)
except Exception as err:
self._logger.exception('Job was invalid: {}'.format(err))
self._execute_callback('invalid', msg, None, None, None, None)
else:
self._logger.info('Executing job {}: {}'.format(job.id, job_repr))
if job.timeout:
timer = threading.Timer(job.timeout, _thread.interrupt_main)
timer.start()
else:
timer = None
try:
res = job.func(*job.args, **job.kwargs)
except KeyboardInterrupt:
self._logger.error(
'Job {} timed out or was interrupted'.format(job.id))
self._execute_callback('timeout', msg, job, None, None, None)
except Exception as err:
self._logger.exception(
'Job {} raised an exception:'.format(job.id))
tb = traceback.format_exc()
self._execute_callback('failure', msg, job, None, err, tb)
else:
self._logger.info('Job {} returned: {}'.format(job.id, res))
self._execute_callback('success', msg, job, res, None, None)
finally:
if timer is not None:
timer.cancel()
|
python
|
def _process_message(self, msg):
"""De-serialize the message and execute the job.
:param msg: Kafka message.
:type msg: :doc:`kq.Message <message>`
"""
self._logger.info(
'Processing Message(topic={}, partition={}, offset={}) ...'
.format(msg.topic, msg.partition, msg.offset))
try:
job = self._deserializer(msg.value)
job_repr = get_call_repr(job.func, *job.args, **job.kwargs)
except Exception as err:
self._logger.exception('Job was invalid: {}'.format(err))
self._execute_callback('invalid', msg, None, None, None, None)
else:
self._logger.info('Executing job {}: {}'.format(job.id, job_repr))
if job.timeout:
timer = threading.Timer(job.timeout, _thread.interrupt_main)
timer.start()
else:
timer = None
try:
res = job.func(*job.args, **job.kwargs)
except KeyboardInterrupt:
self._logger.error(
'Job {} timed out or was interrupted'.format(job.id))
self._execute_callback('timeout', msg, job, None, None, None)
except Exception as err:
self._logger.exception(
'Job {} raised an exception:'.format(job.id))
tb = traceback.format_exc()
self._execute_callback('failure', msg, job, None, err, tb)
else:
self._logger.info('Job {} returned: {}'.format(job.id, res))
self._execute_callback('success', msg, job, res, None, None)
finally:
if timer is not None:
timer.cancel()
|
[
"def",
"_process_message",
"(",
"self",
",",
"msg",
")",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"'Processing Message(topic={}, partition={}, offset={}) ...'",
".",
"format",
"(",
"msg",
".",
"topic",
",",
"msg",
".",
"partition",
",",
"msg",
".",
"offset",
")",
")",
"try",
":",
"job",
"=",
"self",
".",
"_deserializer",
"(",
"msg",
".",
"value",
")",
"job_repr",
"=",
"get_call_repr",
"(",
"job",
".",
"func",
",",
"*",
"job",
".",
"args",
",",
"*",
"*",
"job",
".",
"kwargs",
")",
"except",
"Exception",
"as",
"err",
":",
"self",
".",
"_logger",
".",
"exception",
"(",
"'Job was invalid: {}'",
".",
"format",
"(",
"err",
")",
")",
"self",
".",
"_execute_callback",
"(",
"'invalid'",
",",
"msg",
",",
"None",
",",
"None",
",",
"None",
",",
"None",
")",
"else",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"'Executing job {}: {}'",
".",
"format",
"(",
"job",
".",
"id",
",",
"job_repr",
")",
")",
"if",
"job",
".",
"timeout",
":",
"timer",
"=",
"threading",
".",
"Timer",
"(",
"job",
".",
"timeout",
",",
"_thread",
".",
"interrupt_main",
")",
"timer",
".",
"start",
"(",
")",
"else",
":",
"timer",
"=",
"None",
"try",
":",
"res",
"=",
"job",
".",
"func",
"(",
"*",
"job",
".",
"args",
",",
"*",
"*",
"job",
".",
"kwargs",
")",
"except",
"KeyboardInterrupt",
":",
"self",
".",
"_logger",
".",
"error",
"(",
"'Job {} timed out or was interrupted'",
".",
"format",
"(",
"job",
".",
"id",
")",
")",
"self",
".",
"_execute_callback",
"(",
"'timeout'",
",",
"msg",
",",
"job",
",",
"None",
",",
"None",
",",
"None",
")",
"except",
"Exception",
"as",
"err",
":",
"self",
".",
"_logger",
".",
"exception",
"(",
"'Job {} raised an exception:'",
".",
"format",
"(",
"job",
".",
"id",
")",
")",
"tb",
"=",
"traceback",
".",
"format_exc",
"(",
")",
"self",
".",
"_execute_callback",
"(",
"'failure'",
",",
"msg",
",",
"job",
",",
"None",
",",
"err",
",",
"tb",
")",
"else",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"'Job {} returned: {}'",
".",
"format",
"(",
"job",
".",
"id",
",",
"res",
")",
")",
"self",
".",
"_execute_callback",
"(",
"'success'",
",",
"msg",
",",
"job",
",",
"res",
",",
"None",
",",
"None",
")",
"finally",
":",
"if",
"timer",
"is",
"not",
"None",
":",
"timer",
".",
"cancel",
"(",
")"
] |
De-serialize the message and execute the job.
:param msg: Kafka message.
:type msg: :doc:`kq.Message <message>`
|
[
"De",
"-",
"serialize",
"the",
"message",
"and",
"execute",
"the",
"job",
"."
] |
f5ff3f1828cc1d9de668f82b2d18a98026ce4281
|
https://github.com/joowani/kq/blob/f5ff3f1828cc1d9de668f82b2d18a98026ce4281/kq/worker.py#L133-L173
|
11,597
|
joowani/kq
|
kq/worker.py
|
Worker.start
|
def start(self, max_messages=math.inf, commit_offsets=True):
"""Start processing Kafka messages and executing jobs.
:param max_messages: Maximum number of Kafka messages to process before
stopping. If not set, worker runs until interrupted.
:type max_messages: int
:param commit_offsets: If set to True, consumer offsets are committed
every time a message is processed (default: True).
:type commit_offsets: bool
:return: Total number of messages processed.
:rtype: int
"""
self._logger.info('Starting {} ...'.format(self))
self._consumer.unsubscribe()
self._consumer.subscribe([self.topic])
messages_processed = 0
while messages_processed < max_messages:
record = next(self._consumer)
message = Message(
topic=record.topic,
partition=record.partition,
offset=record.offset,
key=record.key,
value=record.value
)
self._process_message(message)
if commit_offsets:
self._consumer.commit()
messages_processed += 1
return messages_processed
|
python
|
def start(self, max_messages=math.inf, commit_offsets=True):
"""Start processing Kafka messages and executing jobs.
:param max_messages: Maximum number of Kafka messages to process before
stopping. If not set, worker runs until interrupted.
:type max_messages: int
:param commit_offsets: If set to True, consumer offsets are committed
every time a message is processed (default: True).
:type commit_offsets: bool
:return: Total number of messages processed.
:rtype: int
"""
self._logger.info('Starting {} ...'.format(self))
self._consumer.unsubscribe()
self._consumer.subscribe([self.topic])
messages_processed = 0
while messages_processed < max_messages:
record = next(self._consumer)
message = Message(
topic=record.topic,
partition=record.partition,
offset=record.offset,
key=record.key,
value=record.value
)
self._process_message(message)
if commit_offsets:
self._consumer.commit()
messages_processed += 1
return messages_processed
|
[
"def",
"start",
"(",
"self",
",",
"max_messages",
"=",
"math",
".",
"inf",
",",
"commit_offsets",
"=",
"True",
")",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"'Starting {} ...'",
".",
"format",
"(",
"self",
")",
")",
"self",
".",
"_consumer",
".",
"unsubscribe",
"(",
")",
"self",
".",
"_consumer",
".",
"subscribe",
"(",
"[",
"self",
".",
"topic",
"]",
")",
"messages_processed",
"=",
"0",
"while",
"messages_processed",
"<",
"max_messages",
":",
"record",
"=",
"next",
"(",
"self",
".",
"_consumer",
")",
"message",
"=",
"Message",
"(",
"topic",
"=",
"record",
".",
"topic",
",",
"partition",
"=",
"record",
".",
"partition",
",",
"offset",
"=",
"record",
".",
"offset",
",",
"key",
"=",
"record",
".",
"key",
",",
"value",
"=",
"record",
".",
"value",
")",
"self",
".",
"_process_message",
"(",
"message",
")",
"if",
"commit_offsets",
":",
"self",
".",
"_consumer",
".",
"commit",
"(",
")",
"messages_processed",
"+=",
"1",
"return",
"messages_processed"
] |
Start processing Kafka messages and executing jobs.
:param max_messages: Maximum number of Kafka messages to process before
stopping. If not set, worker runs until interrupted.
:type max_messages: int
:param commit_offsets: If set to True, consumer offsets are committed
every time a message is processed (default: True).
:type commit_offsets: bool
:return: Total number of messages processed.
:rtype: int
|
[
"Start",
"processing",
"Kafka",
"messages",
"and",
"executing",
"jobs",
"."
] |
f5ff3f1828cc1d9de668f82b2d18a98026ce4281
|
https://github.com/joowani/kq/blob/f5ff3f1828cc1d9de668f82b2d18a98026ce4281/kq/worker.py#L229-L264
|
11,598
|
joowani/kq
|
kq/utils.py
|
get_call_repr
|
def get_call_repr(func, *args, **kwargs):
"""Return the string representation of the function call.
:param func: A callable (e.g. function, method).
:type func: callable
:param args: Positional arguments for the callable.
:param kwargs: Keyword arguments for the callable.
:return: String representation of the function call.
:rtype: str
"""
# Functions, builtins and methods
if ismethod(func) or isfunction(func) or isbuiltin(func):
func_repr = '{}.{}'.format(func.__module__, func.__qualname__)
# A callable class instance
elif not isclass(func) and hasattr(func, '__call__'):
func_repr = '{}.{}'.format(func.__module__, func.__class__.__name__)
else:
func_repr = repr(func)
args_reprs = [repr(arg) for arg in args]
kwargs_reprs = [k + '=' + repr(v) for k, v in sorted(kwargs.items())]
return '{}({})'.format(func_repr, ', '.join(args_reprs + kwargs_reprs))
|
python
|
def get_call_repr(func, *args, **kwargs):
"""Return the string representation of the function call.
:param func: A callable (e.g. function, method).
:type func: callable
:param args: Positional arguments for the callable.
:param kwargs: Keyword arguments for the callable.
:return: String representation of the function call.
:rtype: str
"""
# Functions, builtins and methods
if ismethod(func) or isfunction(func) or isbuiltin(func):
func_repr = '{}.{}'.format(func.__module__, func.__qualname__)
# A callable class instance
elif not isclass(func) and hasattr(func, '__call__'):
func_repr = '{}.{}'.format(func.__module__, func.__class__.__name__)
else:
func_repr = repr(func)
args_reprs = [repr(arg) for arg in args]
kwargs_reprs = [k + '=' + repr(v) for k, v in sorted(kwargs.items())]
return '{}({})'.format(func_repr, ', '.join(args_reprs + kwargs_reprs))
|
[
"def",
"get_call_repr",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Functions, builtins and methods",
"if",
"ismethod",
"(",
"func",
")",
"or",
"isfunction",
"(",
"func",
")",
"or",
"isbuiltin",
"(",
"func",
")",
":",
"func_repr",
"=",
"'{}.{}'",
".",
"format",
"(",
"func",
".",
"__module__",
",",
"func",
".",
"__qualname__",
")",
"# A callable class instance",
"elif",
"not",
"isclass",
"(",
"func",
")",
"and",
"hasattr",
"(",
"func",
",",
"'__call__'",
")",
":",
"func_repr",
"=",
"'{}.{}'",
".",
"format",
"(",
"func",
".",
"__module__",
",",
"func",
".",
"__class__",
".",
"__name__",
")",
"else",
":",
"func_repr",
"=",
"repr",
"(",
"func",
")",
"args_reprs",
"=",
"[",
"repr",
"(",
"arg",
")",
"for",
"arg",
"in",
"args",
"]",
"kwargs_reprs",
"=",
"[",
"k",
"+",
"'='",
"+",
"repr",
"(",
"v",
")",
"for",
"k",
",",
"v",
"in",
"sorted",
"(",
"kwargs",
".",
"items",
"(",
")",
")",
"]",
"return",
"'{}({})'",
".",
"format",
"(",
"func_repr",
",",
"', '",
".",
"join",
"(",
"args_reprs",
"+",
"kwargs_reprs",
")",
")"
] |
Return the string representation of the function call.
:param func: A callable (e.g. function, method).
:type func: callable
:param args: Positional arguments for the callable.
:param kwargs: Keyword arguments for the callable.
:return: String representation of the function call.
:rtype: str
|
[
"Return",
"the",
"string",
"representation",
"of",
"the",
"function",
"call",
"."
] |
f5ff3f1828cc1d9de668f82b2d18a98026ce4281
|
https://github.com/joowani/kq/blob/f5ff3f1828cc1d9de668f82b2d18a98026ce4281/kq/utils.py#L5-L26
|
11,599
|
joowani/kq
|
kq/queue.py
|
Queue.using
|
def using(self, timeout=None, key=None, partition=None):
"""Set enqueue specifications such as timeout, key and partition.
:param timeout: Job timeout threshold in seconds. If not set, default
timeout (specified during queue initialization) is used instead.
:type timeout: int | float
:param key: Kafka message key. Jobs with the same keys are sent to the
same topic partition and executed sequentially. Applies only if the
**partition** parameter is not set, and the producer’s partitioner
configuration is left as default. For more details on producers,
refer to kafka-python's documentation_.
:type key: bytes
:param partition: Topic partition the message is sent to. If not set,
the producer's partitioner selects the partition. For more details
on producers, refer to kafka-python's documentation_.
:type partition: int
:return: Enqueue specification object which has an ``enqueue`` method
with the same signature as :func:`kq.queue.Queue.enqueue`.
**Example:**
.. testcode::
import requests
from kafka import KafkaProducer
from kq import Job, Queue
# Set up a Kafka producer.
producer = KafkaProducer(bootstrap_servers='127.0.0.1:9092')
# Set up a queue.
queue = Queue(topic='topic', producer=producer)
url = 'https://www.google.com/'
# Enqueue a function call in partition 0 with message key 'foo'.
queue.using(partition=0, key=b'foo').enqueue(requests.get, url)
# Enqueue a function call with a timeout of 10 seconds.
queue.using(timeout=10).enqueue(requests.get, url)
# Job values are preferred over values set with "using" method.
job = Job(func=requests.get, args=[url], timeout=5)
queue.using(timeout=10).enqueue(job) # timeout is still 5
.. _documentation: http://kafka-python.rtfd.io/en/master/#kafkaproducer
"""
return EnqueueSpec(
topic=self._topic,
producer=self._producer,
serializer=self._serializer,
logger=self._logger,
timeout=timeout or self._timeout,
key=key,
partition=partition
)
|
python
|
def using(self, timeout=None, key=None, partition=None):
"""Set enqueue specifications such as timeout, key and partition.
:param timeout: Job timeout threshold in seconds. If not set, default
timeout (specified during queue initialization) is used instead.
:type timeout: int | float
:param key: Kafka message key. Jobs with the same keys are sent to the
same topic partition and executed sequentially. Applies only if the
**partition** parameter is not set, and the producer’s partitioner
configuration is left as default. For more details on producers,
refer to kafka-python's documentation_.
:type key: bytes
:param partition: Topic partition the message is sent to. If not set,
the producer's partitioner selects the partition. For more details
on producers, refer to kafka-python's documentation_.
:type partition: int
:return: Enqueue specification object which has an ``enqueue`` method
with the same signature as :func:`kq.queue.Queue.enqueue`.
**Example:**
.. testcode::
import requests
from kafka import KafkaProducer
from kq import Job, Queue
# Set up a Kafka producer.
producer = KafkaProducer(bootstrap_servers='127.0.0.1:9092')
# Set up a queue.
queue = Queue(topic='topic', producer=producer)
url = 'https://www.google.com/'
# Enqueue a function call in partition 0 with message key 'foo'.
queue.using(partition=0, key=b'foo').enqueue(requests.get, url)
# Enqueue a function call with a timeout of 10 seconds.
queue.using(timeout=10).enqueue(requests.get, url)
# Job values are preferred over values set with "using" method.
job = Job(func=requests.get, args=[url], timeout=5)
queue.using(timeout=10).enqueue(job) # timeout is still 5
.. _documentation: http://kafka-python.rtfd.io/en/master/#kafkaproducer
"""
return EnqueueSpec(
topic=self._topic,
producer=self._producer,
serializer=self._serializer,
logger=self._logger,
timeout=timeout or self._timeout,
key=key,
partition=partition
)
|
[
"def",
"using",
"(",
"self",
",",
"timeout",
"=",
"None",
",",
"key",
"=",
"None",
",",
"partition",
"=",
"None",
")",
":",
"return",
"EnqueueSpec",
"(",
"topic",
"=",
"self",
".",
"_topic",
",",
"producer",
"=",
"self",
".",
"_producer",
",",
"serializer",
"=",
"self",
".",
"_serializer",
",",
"logger",
"=",
"self",
".",
"_logger",
",",
"timeout",
"=",
"timeout",
"or",
"self",
".",
"_timeout",
",",
"key",
"=",
"key",
",",
"partition",
"=",
"partition",
")"
] |
Set enqueue specifications such as timeout, key and partition.
:param timeout: Job timeout threshold in seconds. If not set, default
timeout (specified during queue initialization) is used instead.
:type timeout: int | float
:param key: Kafka message key. Jobs with the same keys are sent to the
same topic partition and executed sequentially. Applies only if the
**partition** parameter is not set, and the producer’s partitioner
configuration is left as default. For more details on producers,
refer to kafka-python's documentation_.
:type key: bytes
:param partition: Topic partition the message is sent to. If not set,
the producer's partitioner selects the partition. For more details
on producers, refer to kafka-python's documentation_.
:type partition: int
:return: Enqueue specification object which has an ``enqueue`` method
with the same signature as :func:`kq.queue.Queue.enqueue`.
**Example:**
.. testcode::
import requests
from kafka import KafkaProducer
from kq import Job, Queue
# Set up a Kafka producer.
producer = KafkaProducer(bootstrap_servers='127.0.0.1:9092')
# Set up a queue.
queue = Queue(topic='topic', producer=producer)
url = 'https://www.google.com/'
# Enqueue a function call in partition 0 with message key 'foo'.
queue.using(partition=0, key=b'foo').enqueue(requests.get, url)
# Enqueue a function call with a timeout of 10 seconds.
queue.using(timeout=10).enqueue(requests.get, url)
# Job values are preferred over values set with "using" method.
job = Job(func=requests.get, args=[url], timeout=5)
queue.using(timeout=10).enqueue(job) # timeout is still 5
.. _documentation: http://kafka-python.rtfd.io/en/master/#kafkaproducer
|
[
"Set",
"enqueue",
"specifications",
"such",
"as",
"timeout",
"key",
"and",
"partition",
"."
] |
f5ff3f1828cc1d9de668f82b2d18a98026ce4281
|
https://github.com/joowani/kq/blob/f5ff3f1828cc1d9de668f82b2d18a98026ce4281/kq/queue.py#L207-L263
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.