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
partition
stringclasses
1 value
okpy/ok-client
client/utils/software_update.py
check_version
def check_version(server, version, filename, timeout=SHORT_TIMEOUT): """Check for the latest version of OK and update accordingly.""" address = VERSION_ENDPOINT.format(server=server) print('Checking for software updates...') log.info('Existing OK version: %s', version) log.info('Checking latest ve...
python
def check_version(server, version, filename, timeout=SHORT_TIMEOUT): """Check for the latest version of OK and update accordingly.""" address = VERSION_ENDPOINT.format(server=server) print('Checking for software updates...') log.info('Existing OK version: %s', version) log.info('Checking latest ve...
[ "def", "check_version", "(", "server", ",", "version", ",", "filename", ",", "timeout", "=", "SHORT_TIMEOUT", ")", ":", "address", "=", "VERSION_ENDPOINT", ".", "format", "(", "server", "=", "server", ")", "print", "(", "'Checking for software updates...'", ")",...
Check for the latest version of OK and update accordingly.
[ "Check", "for", "the", "latest", "version", "of", "OK", "and", "update", "accordingly", "." ]
517f57dd76284af40ba9766e42d9222b644afd9c
https://github.com/okpy/ok-client/blob/517f57dd76284af40ba9766e42d9222b644afd9c/client/utils/software_update.py#L11-L65
train
okpy/ok-client
client/sources/common/interpreter.py
CodeCase.run
def run(self): """Implements the GradedTestCase interface.""" self.console.load(self.lines, setup=self.setup, teardown=self.teardown) return self.console.interpret()
python
def run(self): """Implements the GradedTestCase interface.""" self.console.load(self.lines, setup=self.setup, teardown=self.teardown) return self.console.interpret()
[ "def", "run", "(", "self", ")", ":", "self", ".", "console", ".", "load", "(", "self", ".", "lines", ",", "setup", "=", "self", ".", "setup", ",", "teardown", "=", "self", ".", "teardown", ")", "return", "self", ".", "console", ".", "interpret", "(...
Implements the GradedTestCase interface.
[ "Implements", "the", "GradedTestCase", "interface", "." ]
517f57dd76284af40ba9766e42d9222b644afd9c
https://github.com/okpy/ok-client/blob/517f57dd76284af40ba9766e42d9222b644afd9c/client/sources/common/interpreter.py#L41-L44
train
okpy/ok-client
client/sources/common/interpreter.py
CodeCase.unlock
def unlock(self, unique_id_prefix, case_id, interact): """Unlocks the CodeCase. PARAMETERS: unique_id_prefix -- string; a prefix of a unique identifier for this Case, for purposes of analytics. case_id -- string; an identifier for this Case, for purp...
python
def unlock(self, unique_id_prefix, case_id, interact): """Unlocks the CodeCase. PARAMETERS: unique_id_prefix -- string; a prefix of a unique identifier for this Case, for purposes of analytics. case_id -- string; an identifier for this Case, for purp...
[ "def", "unlock", "(", "self", ",", "unique_id_prefix", ",", "case_id", ",", "interact", ")", ":", "print", "(", "self", ".", "setup", ".", "strip", "(", ")", ")", "prompt_num", "=", "0", "current_prompt", "=", "[", "]", "try", ":", "for", "line", "in...
Unlocks the CodeCase. PARAMETERS: unique_id_prefix -- string; a prefix of a unique identifier for this Case, for purposes of analytics. case_id -- string; an identifier for this Case, for purposes of analytics. interact ...
[ "Unlocks", "the", "CodeCase", "." ]
517f57dd76284af40ba9766e42d9222b644afd9c
https://github.com/okpy/ok-client/blob/517f57dd76284af40ba9766e42d9222b644afd9c/client/sources/common/interpreter.py#L55-L89
train
okpy/ok-client
client/sources/common/interpreter.py
CodeCase.split_code
def split_code(cls, code, PS1, PS2): """Splits the given string of code based on the provided PS1 and PS2 symbols. PARAMETERS: code -- str; lines of interpretable code, using PS1 and PS2 prompts PS1 -- str; first-level prompt symbol PS2 -- str; second-level prompt symb...
python
def split_code(cls, code, PS1, PS2): """Splits the given string of code based on the provided PS1 and PS2 symbols. PARAMETERS: code -- str; lines of interpretable code, using PS1 and PS2 prompts PS1 -- str; first-level prompt symbol PS2 -- str; second-level prompt symb...
[ "def", "split_code", "(", "cls", ",", "code", ",", "PS1", ",", "PS2", ")", ":", "processed_lines", "=", "[", "]", "for", "line", "in", "textwrap", ".", "dedent", "(", "code", ")", ".", "splitlines", "(", ")", ":", "if", "not", "line", "or", "line",...
Splits the given string of code based on the provided PS1 and PS2 symbols. PARAMETERS: code -- str; lines of interpretable code, using PS1 and PS2 prompts PS1 -- str; first-level prompt symbol PS2 -- str; second-level prompt symbol RETURN: list; a processed se...
[ "Splits", "the", "given", "string", "of", "code", "based", "on", "the", "provided", "PS1", "and", "PS2", "symbols", "." ]
517f57dd76284af40ba9766e42d9222b644afd9c
https://github.com/okpy/ok-client/blob/517f57dd76284af40ba9766e42d9222b644afd9c/client/sources/common/interpreter.py#L92-L114
train
okpy/ok-client
client/sources/common/interpreter.py
CodeCase._sync_code
def _sync_code(self): """Syncs the current state of self.lines with self.code, the serializable string representing the set of code. """ new_code = [] for line in self.lines: if isinstance(line, CodeAnswer): new_code.append(line.dump()) els...
python
def _sync_code(self): """Syncs the current state of self.lines with self.code, the serializable string representing the set of code. """ new_code = [] for line in self.lines: if isinstance(line, CodeAnswer): new_code.append(line.dump()) els...
[ "def", "_sync_code", "(", "self", ")", ":", "new_code", "=", "[", "]", "for", "line", "in", "self", ".", "lines", ":", "if", "isinstance", "(", "line", ",", "CodeAnswer", ")", ":", "new_code", ".", "append", "(", "line", ".", "dump", "(", ")", ")",...
Syncs the current state of self.lines with self.code, the serializable string representing the set of code.
[ "Syncs", "the", "current", "state", "of", "self", ".", "lines", "with", "self", ".", "code", "the", "serializable", "string", "representing", "the", "set", "of", "code", "." ]
517f57dd76284af40ba9766e42d9222b644afd9c
https://github.com/okpy/ok-client/blob/517f57dd76284af40ba9766e42d9222b644afd9c/client/sources/common/interpreter.py#L116-L126
train
okpy/ok-client
client/sources/common/interpreter.py
CodeCase._construct_unique_id
def _construct_unique_id(self, id_prefix, lines): """Constructs a unique ID for a particular prompt in this case, based on the id_prefix and the lines in the prompt. """ text = [] for line in lines: if isinstance(line, str): text.append(line) ...
python
def _construct_unique_id(self, id_prefix, lines): """Constructs a unique ID for a particular prompt in this case, based on the id_prefix and the lines in the prompt. """ text = [] for line in lines: if isinstance(line, str): text.append(line) ...
[ "def", "_construct_unique_id", "(", "self", ",", "id_prefix", ",", "lines", ")", ":", "text", "=", "[", "]", "for", "line", "in", "lines", ":", "if", "isinstance", "(", "line", ",", "str", ")", ":", "text", ".", "append", "(", "line", ")", "elif", ...
Constructs a unique ID for a particular prompt in this case, based on the id_prefix and the lines in the prompt.
[ "Constructs", "a", "unique", "ID", "for", "a", "particular", "prompt", "in", "this", "case", "based", "on", "the", "id_prefix", "and", "the", "lines", "in", "the", "prompt", "." ]
517f57dd76284af40ba9766e42d9222b644afd9c
https://github.com/okpy/ok-client/blob/517f57dd76284af40ba9766e42d9222b644afd9c/client/sources/common/interpreter.py#L128-L138
train
okpy/ok-client
client/sources/common/interpreter.py
Console.interpret
def interpret(self): """Interprets the console on the loaded code. RETURNS: bool; True if the code passes, False otherwise. """ if not self._interpret_lines(self._setup): return False success = self._interpret_lines(self._code, compare_all=True) succ...
python
def interpret(self): """Interprets the console on the loaded code. RETURNS: bool; True if the code passes, False otherwise. """ if not self._interpret_lines(self._setup): return False success = self._interpret_lines(self._code, compare_all=True) succ...
[ "def", "interpret", "(", "self", ")", ":", "if", "not", "self", ".", "_interpret_lines", "(", "self", ".", "_setup", ")", ":", "return", "False", "success", "=", "self", ".", "_interpret_lines", "(", "self", ".", "_code", ",", "compare_all", "=", "True",...
Interprets the console on the loaded code. RETURNS: bool; True if the code passes, False otherwise.
[ "Interprets", "the", "console", "on", "the", "loaded", "code", "." ]
517f57dd76284af40ba9766e42d9222b644afd9c
https://github.com/okpy/ok-client/blob/517f57dd76284af40ba9766e42d9222b644afd9c/client/sources/common/interpreter.py#L172-L183
train
okpy/ok-client
client/sources/common/interpreter.py
Console._interpret_lines
def _interpret_lines(self, lines, compare_all=False): """Interprets the set of lines. PARAMTERS: lines -- list of str; lines of code compare_all -- bool; if True, check for no output for lines that are not followed by a CodeAnswer RETURNS: b...
python
def _interpret_lines(self, lines, compare_all=False): """Interprets the set of lines. PARAMTERS: lines -- list of str; lines of code compare_all -- bool; if True, check for no output for lines that are not followed by a CodeAnswer RETURNS: b...
[ "def", "_interpret_lines", "(", "self", ",", "lines", ",", "compare_all", "=", "False", ")", ":", "current", "=", "[", "]", "for", "line", "in", "lines", "+", "[", "''", "]", ":", "if", "isinstance", "(", "line", ",", "str", ")", ":", "if", "curren...
Interprets the set of lines. PARAMTERS: lines -- list of str; lines of code compare_all -- bool; if True, check for no output for lines that are not followed by a CodeAnswer RETURNS: bool; True if successful, False otherwise.
[ "Interprets", "the", "set", "of", "lines", "." ]
517f57dd76284af40ba9766e42d9222b644afd9c
https://github.com/okpy/ok-client/blob/517f57dd76284af40ba9766e42d9222b644afd9c/client/sources/common/interpreter.py#L208-L243
train
okpy/ok-client
client/sources/common/interpreter.py
CodeAnswer.dump
def dump(self): """Serialize a test case to a string.""" result = list(self.output_lines()) if self.locked: result.append('# locked') if self.choices: for choice in self.choices: result.append('# choice: ' + choice) if self.expl...
python
def dump(self): """Serialize a test case to a string.""" result = list(self.output_lines()) if self.locked: result.append('# locked') if self.choices: for choice in self.choices: result.append('# choice: ' + choice) if self.expl...
[ "def", "dump", "(", "self", ")", ":", "result", "=", "list", "(", "self", ".", "output_lines", "(", ")", ")", "if", "self", ".", "locked", ":", "result", ".", "append", "(", "'# locked'", ")", "if", "self", ".", "choices", ":", "for", "choice", "in...
Serialize a test case to a string.
[ "Serialize", "a", "test", "case", "to", "a", "string", "." ]
517f57dd76284af40ba9766e42d9222b644afd9c
https://github.com/okpy/ok-client/blob/517f57dd76284af40ba9766e42d9222b644afd9c/client/sources/common/interpreter.py#L310-L320
train
okpy/ok-client
client/sources/common/interpreter.py
CodeAnswer.output_lines
def output_lines(self): """Return a sequence of lines, suitable for printing or comparing answers. """ if self.exception: return [self.EXCEPTION_HEADERS[0], ' ...'] + self.exception_detail else: return self.output
python
def output_lines(self): """Return a sequence of lines, suitable for printing or comparing answers. """ if self.exception: return [self.EXCEPTION_HEADERS[0], ' ...'] + self.exception_detail else: return self.output
[ "def", "output_lines", "(", "self", ")", ":", "if", "self", ".", "exception", ":", "return", "[", "self", ".", "EXCEPTION_HEADERS", "[", "0", "]", ",", "' ...'", "]", "+", "self", ".", "exception_detail", "else", ":", "return", "self", ".", "output" ]
Return a sequence of lines, suitable for printing or comparing answers.
[ "Return", "a", "sequence", "of", "lines", "suitable", "for", "printing", "or", "comparing", "answers", "." ]
517f57dd76284af40ba9766e42d9222b644afd9c
https://github.com/okpy/ok-client/blob/517f57dd76284af40ba9766e42d9222b644afd9c/client/sources/common/interpreter.py#L322-L329
train
okpy/ok-client
client/utils/format.py
prettyjson
def prettyjson(json, indentation=' '): """Formats a Python-object into a string in a JSON like way, but uses triple quotes for multiline strings. PARAMETERS: json -- Python object that is serializable into json. indentation -- str; represents one level of indentation NOTES: All mul...
python
def prettyjson(json, indentation=' '): """Formats a Python-object into a string in a JSON like way, but uses triple quotes for multiline strings. PARAMETERS: json -- Python object that is serializable into json. indentation -- str; represents one level of indentation NOTES: All mul...
[ "def", "prettyjson", "(", "json", ",", "indentation", "=", "' '", ")", ":", "if", "isinstance", "(", "json", ",", "int", ")", "or", "isinstance", "(", "json", ",", "float", ")", ":", "return", "str", "(", "json", ")", "elif", "isinstance", "(", "jso...
Formats a Python-object into a string in a JSON like way, but uses triple quotes for multiline strings. PARAMETERS: json -- Python object that is serializable into json. indentation -- str; represents one level of indentation NOTES: All multiline strings are treated as raw strings. ...
[ "Formats", "a", "Python", "-", "object", "into", "a", "string", "in", "a", "JSON", "like", "way", "but", "uses", "triple", "quotes", "for", "multiline", "strings", "." ]
517f57dd76284af40ba9766e42d9222b644afd9c
https://github.com/okpy/ok-client/blob/517f57dd76284af40ba9766e42d9222b644afd9c/client/utils/format.py#L129-L160
train
okpy/ok-client
client/api/notebook.py
validate_contents
def validate_contents(file_contents): """Ensures that all ipynb files in FILE_CONTENTS are valid JSON files.""" for name, contents in file_contents.items(): if os.path.splitext(name)[1] != '.ipynb': continue if not contents: return False try: json_...
python
def validate_contents(file_contents): """Ensures that all ipynb files in FILE_CONTENTS are valid JSON files.""" for name, contents in file_contents.items(): if os.path.splitext(name)[1] != '.ipynb': continue if not contents: return False try: json_...
[ "def", "validate_contents", "(", "file_contents", ")", ":", "for", "name", ",", "contents", "in", "file_contents", ".", "items", "(", ")", ":", "if", "os", ".", "path", ".", "splitext", "(", "name", ")", "[", "1", "]", "!=", "'.ipynb'", ":", "continue"...
Ensures that all ipynb files in FILE_CONTENTS are valid JSON files.
[ "Ensures", "that", "all", "ipynb", "files", "in", "FILE_CONTENTS", "are", "valid", "JSON", "files", "." ]
517f57dd76284af40ba9766e42d9222b644afd9c
https://github.com/okpy/ok-client/blob/517f57dd76284af40ba9766e42d9222b644afd9c/client/api/notebook.py#L144-L156
train
okpy/ok-client
client/api/notebook.py
wait_for_save
def wait_for_save(filename, timeout=5): """Waits for FILENAME to update, waiting up to TIMEOUT seconds. Returns True if a save was detected, and False otherwise. """ modification_time = os.path.getmtime(filename) start_time = time.time() while time.time() < start_time + timeout: if (os.p...
python
def wait_for_save(filename, timeout=5): """Waits for FILENAME to update, waiting up to TIMEOUT seconds. Returns True if a save was detected, and False otherwise. """ modification_time = os.path.getmtime(filename) start_time = time.time() while time.time() < start_time + timeout: if (os.p...
[ "def", "wait_for_save", "(", "filename", ",", "timeout", "=", "5", ")", ":", "modification_time", "=", "os", ".", "path", ".", "getmtime", "(", "filename", ")", "start_time", "=", "time", ".", "time", "(", ")", "while", "time", ".", "time", "(", ")", ...
Waits for FILENAME to update, waiting up to TIMEOUT seconds. Returns True if a save was detected, and False otherwise.
[ "Waits", "for", "FILENAME", "to", "update", "waiting", "up", "to", "TIMEOUT", "seconds", ".", "Returns", "True", "if", "a", "save", "was", "detected", "and", "False", "otherwise", "." ]
517f57dd76284af40ba9766e42d9222b644afd9c
https://github.com/okpy/ok-client/blob/517f57dd76284af40ba9766e42d9222b644afd9c/client/api/notebook.py#L158-L169
train
okpy/ok-client
client/api/notebook.py
Notebook.score
def score(self, env=None, score_out=None): """ Run the scoring protocol. score_out -- str; a file name to write the point breakdown into. Returns: dict; maps score tag (str) -> points (float) """ messages = {} self.assignment.set_args( s...
python
def score(self, env=None, score_out=None): """ Run the scoring protocol. score_out -- str; a file name to write the point breakdown into. Returns: dict; maps score tag (str) -> points (float) """ messages = {} self.assignment.set_args( s...
[ "def", "score", "(", "self", ",", "env", "=", "None", ",", "score_out", "=", "None", ")", ":", "messages", "=", "{", "}", "self", ".", "assignment", ".", "set_args", "(", "score", "=", "True", ",", "score_out", "=", "score_out", ",", ")", "if", "en...
Run the scoring protocol. score_out -- str; a file name to write the point breakdown into. Returns: dict; maps score tag (str) -> points (float)
[ "Run", "the", "scoring", "protocol", "." ]
517f57dd76284af40ba9766e42d9222b644afd9c
https://github.com/okpy/ok-client/blob/517f57dd76284af40ba9766e42d9222b644afd9c/client/api/notebook.py#L43-L60
train
okpy/ok-client
client/api/notebook.py
Notebook.save_notebook
def save_notebook(self): """ Saves the current notebook by injecting JavaScript to save to .ipynb file. """ try: from IPython.display import display, Javascript except ImportError: log.warning("Could not import IPython Display Function") print(...
python
def save_notebook(self): """ Saves the current notebook by injecting JavaScript to save to .ipynb file. """ try: from IPython.display import display, Javascript except ImportError: log.warning("Could not import IPython Display Function") print(...
[ "def", "save_notebook", "(", "self", ")", ":", "try", ":", "from", "IPython", ".", "display", "import", "display", ",", "Javascript", "except", "ImportError", ":", "log", ".", "warning", "(", "\"Could not import IPython Display Function\"", ")", "print", "(", "\...
Saves the current notebook by injecting JavaScript to save to .ipynb file.
[ "Saves", "the", "current", "notebook", "by", "injecting", "JavaScript", "to", "save", "to", ".", "ipynb", "file", "." ]
517f57dd76284af40ba9766e42d9222b644afd9c
https://github.com/okpy/ok-client/blob/517f57dd76284af40ba9766e42d9222b644afd9c/client/api/notebook.py#L94-L127
train
okpy/ok-client
client/cli/lock.py
main
def main(): """Run the LockingProtocol.""" args = parse_input() args.lock = True args.question = [] args.all = False args.timeout = 0 args.verbose = False args.interactive = False try: assign = assignment.load_assignment(args.config, args) msgs = messages.Messages()...
python
def main(): """Run the LockingProtocol.""" args = parse_input() args.lock = True args.question = [] args.all = False args.timeout = 0 args.verbose = False args.interactive = False try: assign = assignment.load_assignment(args.config, args) msgs = messages.Messages()...
[ "def", "main", "(", ")", ":", "args", "=", "parse_input", "(", ")", "args", ".", "lock", "=", "True", "args", ".", "question", "=", "[", "]", "args", ".", "all", "=", "False", "args", ".", "timeout", "=", "0", "args", ".", "verbose", "=", "False"...
Run the LockingProtocol.
[ "Run", "the", "LockingProtocol", "." ]
517f57dd76284af40ba9766e42d9222b644afd9c
https://github.com/okpy/ok-client/blob/517f57dd76284af40ba9766e42d9222b644afd9c/client/cli/lock.py#L23-L46
train
okpy/ok-client
client/cli/publish.py
write_tree
def write_tree(zipf, src_directory, dst_directory): """Write all .py files in a source directory to a destination directory inside a zip archive. """ if not os.path.exists(src_directory): abort('Tree ' + src_directory + ' does not exist.') for root, _, files in os.walk(src_directory): ...
python
def write_tree(zipf, src_directory, dst_directory): """Write all .py files in a source directory to a destination directory inside a zip archive. """ if not os.path.exists(src_directory): abort('Tree ' + src_directory + ' does not exist.') for root, _, files in os.walk(src_directory): ...
[ "def", "write_tree", "(", "zipf", ",", "src_directory", ",", "dst_directory", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "src_directory", ")", ":", "abort", "(", "'Tree '", "+", "src_directory", "+", "' does not exist.'", ")", "for", "ro...
Write all .py files in a source directory to a destination directory inside a zip archive.
[ "Write", "all", ".", "py", "files", "in", "a", "source", "directory", "to", "a", "destination", "directory", "inside", "a", "zip", "archive", "." ]
517f57dd76284af40ba9766e42d9222b644afd9c
https://github.com/okpy/ok-client/blob/517f57dd76284af40ba9766e42d9222b644afd9c/client/cli/publish.py#L28-L40
train
okpy/ok-client
client/utils/output.py
_OutputLogger.new_log
def new_log(self): """Registers a new log so that calls to write will append to the log. RETURN: int; a unique ID to reference the log. """ log_id = self._num_logs self._logs[log_id] = [] self._num_logs += 1 return log_id
python
def new_log(self): """Registers a new log so that calls to write will append to the log. RETURN: int; a unique ID to reference the log. """ log_id = self._num_logs self._logs[log_id] = [] self._num_logs += 1 return log_id
[ "def", "new_log", "(", "self", ")", ":", "log_id", "=", "self", ".", "_num_logs", "self", ".", "_logs", "[", "log_id", "]", "=", "[", "]", "self", ".", "_num_logs", "+=", "1", "return", "log_id" ]
Registers a new log so that calls to write will append to the log. RETURN: int; a unique ID to reference the log.
[ "Registers", "a", "new", "log", "so", "that", "calls", "to", "write", "will", "append", "to", "the", "log", "." ]
517f57dd76284af40ba9766e42d9222b644afd9c
https://github.com/okpy/ok-client/blob/517f57dd76284af40ba9766e42d9222b644afd9c/client/utils/output.py#L24-L33
train
okpy/ok-client
client/protocols/scoring.py
display_breakdown
def display_breakdown(scores, outfile=None): """Writes the point breakdown to `outfile` given a dictionary of scores. `outfile` should be a string. If `outfile` is None, write to stdout. RETURNS: dict; 'Total' -> finalized score (float) """ total = 0 outfile = open(outfile, 'w') if outfile...
python
def display_breakdown(scores, outfile=None): """Writes the point breakdown to `outfile` given a dictionary of scores. `outfile` should be a string. If `outfile` is None, write to stdout. RETURNS: dict; 'Total' -> finalized score (float) """ total = 0 outfile = open(outfile, 'w') if outfile...
[ "def", "display_breakdown", "(", "scores", ",", "outfile", "=", "None", ")", ":", "total", "=", "0", "outfile", "=", "open", "(", "outfile", ",", "'w'", ")", "if", "outfile", "else", "sys", ".", "stdout", "format", ".", "print_line", "(", "'-'", ")", ...
Writes the point breakdown to `outfile` given a dictionary of scores. `outfile` should be a string. If `outfile` is None, write to stdout. RETURNS: dict; 'Total' -> finalized score (float)
[ "Writes", "the", "point", "breakdown", "to", "outfile", "given", "a", "dictionary", "of", "scores", ".", "outfile", "should", "be", "a", "string", ".", "If", "outfile", "is", "None", "write", "to", "stdout", "." ]
517f57dd76284af40ba9766e42d9222b644afd9c
https://github.com/okpy/ok-client/blob/517f57dd76284af40ba9766e42d9222b644afd9c/client/protocols/scoring.py#L57-L76
train
okpy/ok-client
client/protocols/scoring.py
ScoringProtocol.run
def run(self, messages, env=None): """Score tests and print results. Tests are taken from self.assignment.specified_tests. A score breakdown by question and the total score are both printed. ENV is used by the programatic API for Python doctests only. """ if not self.arg...
python
def run(self, messages, env=None): """Score tests and print results. Tests are taken from self.assignment.specified_tests. A score breakdown by question and the total score are both printed. ENV is used by the programatic API for Python doctests only. """ if not self.arg...
[ "def", "run", "(", "self", ",", "messages", ",", "env", "=", "None", ")", ":", "if", "not", "self", ".", "args", ".", "score", "or", "self", ".", "args", ".", "testing", ":", "return", "format", ".", "print_line", "(", "'~'", ")", "print", "(", "...
Score tests and print results. Tests are taken from self.assignment.specified_tests. A score breakdown by question and the total score are both printed. ENV is used by the programatic API for Python doctests only.
[ "Score", "tests", "and", "print", "results", ".", "Tests", "are", "taken", "from", "self", ".", "assignment", ".", "specified_tests", ".", "A", "score", "breakdown", "by", "question", "and", "the", "total", "score", "are", "both", "printed", "." ]
517f57dd76284af40ba9766e42d9222b644afd9c
https://github.com/okpy/ok-client/blob/517f57dd76284af40ba9766e42d9222b644afd9c/client/protocols/scoring.py#L24-L55
train
okpy/ok-client
client/utils/locking.py
lock
def lock(key, text): """Locks the given text using the given key and returns the result""" return hmac.new(key.encode('utf-8'), text.encode('utf-8')).hexdigest()
python
def lock(key, text): """Locks the given text using the given key and returns the result""" return hmac.new(key.encode('utf-8'), text.encode('utf-8')).hexdigest()
[ "def", "lock", "(", "key", ",", "text", ")", ":", "return", "hmac", ".", "new", "(", "key", ".", "encode", "(", "'utf-8'", ")", ",", "text", ".", "encode", "(", "'utf-8'", ")", ")", ".", "hexdigest", "(", ")" ]
Locks the given text using the given key and returns the result
[ "Locks", "the", "given", "text", "using", "the", "given", "key", "and", "returns", "the", "result" ]
517f57dd76284af40ba9766e42d9222b644afd9c
https://github.com/okpy/ok-client/blob/517f57dd76284af40ba9766e42d9222b644afd9c/client/utils/locking.py#L5-L7
train
okpy/ok-client
client/protocols/unlock.py
UnlockProtocol.run
def run(self, messages): """Responsible for unlocking each test. The unlocking process can be aborted by raising a KeyboardInterrupt or an EOFError. RETURNS: dict; mapping of test name (str) -> JSON-serializable object. It is up to each test to determine what informatio...
python
def run(self, messages): """Responsible for unlocking each test. The unlocking process can be aborted by raising a KeyboardInterrupt or an EOFError. RETURNS: dict; mapping of test name (str) -> JSON-serializable object. It is up to each test to determine what informatio...
[ "def", "run", "(", "self", ",", "messages", ")", ":", "if", "not", "self", ".", "args", ".", "unlock", ":", "return", "format", ".", "print_line", "(", "'~'", ")", "print", "(", "'Unlocking tests'", ")", "print", "(", ")", "print", "(", "'At each \"{}\...
Responsible for unlocking each test. The unlocking process can be aborted by raising a KeyboardInterrupt or an EOFError. RETURNS: dict; mapping of test name (str) -> JSON-serializable object. It is up to each test to determine what information is significant for analytics.
[ "Responsible", "for", "unlocking", "each", "test", "." ]
517f57dd76284af40ba9766e42d9222b644afd9c
https://github.com/okpy/ok-client/blob/517f57dd76284af40ba9766e42d9222b644afd9c/client/protocols/unlock.py#L46-L88
train
okpy/ok-client
client/protocols/unlock.py
UnlockProtocol.interact
def interact(self, unique_id, case_id, question_prompt, answer, choices=None, randomize=True): """Reads student input for unlocking tests until the student answers correctly. PARAMETERS: unique_id -- str; the ID that is recorded with this unlocking attem...
python
def interact(self, unique_id, case_id, question_prompt, answer, choices=None, randomize=True): """Reads student input for unlocking tests until the student answers correctly. PARAMETERS: unique_id -- str; the ID that is recorded with this unlocking attem...
[ "def", "interact", "(", "self", ",", "unique_id", ",", "case_id", ",", "question_prompt", ",", "answer", ",", "choices", "=", "None", ",", "randomize", "=", "True", ")", ":", "if", "randomize", "and", "choices", ":", "choices", "=", "random", ".", "sampl...
Reads student input for unlocking tests until the student answers correctly. PARAMETERS: unique_id -- str; the ID that is recorded with this unlocking attempt. case_id -- str; the ID that is recorded with this unlocking ...
[ "Reads", "student", "input", "for", "unlocking", "tests", "until", "the", "student", "answers", "correctly", "." ]
517f57dd76284af40ba9766e42d9222b644afd9c
https://github.com/okpy/ok-client/blob/517f57dd76284af40ba9766e42d9222b644afd9c/client/protocols/unlock.py#L90-L184
train
okpy/ok-client
client/protocols/unlock.py
UnlockProtocol._verify_student_input
def _verify_student_input(self, student_input, locked): """If the student's answer is correct, returns the normalized answer. Otherwise, returns None. """ guesses = [student_input] try: guesses.append(repr(ast.literal_eval(student_input))) except Exception: ...
python
def _verify_student_input(self, student_input, locked): """If the student's answer is correct, returns the normalized answer. Otherwise, returns None. """ guesses = [student_input] try: guesses.append(repr(ast.literal_eval(student_input))) except Exception: ...
[ "def", "_verify_student_input", "(", "self", ",", "student_input", ",", "locked", ")", ":", "guesses", "=", "[", "student_input", "]", "try", ":", "guesses", ".", "append", "(", "repr", "(", "ast", ".", "literal_eval", "(", "student_input", ")", ")", ")", ...
If the student's answer is correct, returns the normalized answer. Otherwise, returns None.
[ "If", "the", "student", "s", "answer", "is", "correct", "returns", "the", "normalized", "answer", ".", "Otherwise", "returns", "None", "." ]
517f57dd76284af40ba9766e42d9222b644afd9c
https://github.com/okpy/ok-client/blob/517f57dd76284af40ba9766e42d9222b644afd9c/client/protocols/unlock.py#L190-L203
train
okpy/ok-client
client/protocols/unlock.py
UnlockProtocol._display_choices
def _display_choices(self, choices): """Prints a mapping of numbers to choices and returns the mapping as a dictionary. """ print("Choose the number of the correct choice:") choice_map = {} for i, choice in enumerate(choices): i = str(i) print('{})...
python
def _display_choices(self, choices): """Prints a mapping of numbers to choices and returns the mapping as a dictionary. """ print("Choose the number of the correct choice:") choice_map = {} for i, choice in enumerate(choices): i = str(i) print('{})...
[ "def", "_display_choices", "(", "self", ",", "choices", ")", ":", "print", "(", "\"Choose the number of the correct choice:\"", ")", "choice_map", "=", "{", "}", "for", "i", ",", "choice", "in", "enumerate", "(", "choices", ")", ":", "i", "=", "str", "(", ...
Prints a mapping of numbers to choices and returns the mapping as a dictionary.
[ "Prints", "a", "mapping", "of", "numbers", "to", "choices", "and", "returns", "the", "mapping", "as", "a", "dictionary", "." ]
517f57dd76284af40ba9766e42d9222b644afd9c
https://github.com/okpy/ok-client/blob/517f57dd76284af40ba9766e42d9222b644afd9c/client/protocols/unlock.py#L212-L224
train
okpy/ok-client
client/utils/timer.py
timed
def timed(timeout, fn, args=(), kargs={}): """For a nonzero timeout, evaluates a call expression in a separate thread. If the timeout is 0, the expression is evaluated in the main thread. PARAMETERS: fn -- function; Python function to be evaluated args -- tuple; positional arguments for fn ...
python
def timed(timeout, fn, args=(), kargs={}): """For a nonzero timeout, evaluates a call expression in a separate thread. If the timeout is 0, the expression is evaluated in the main thread. PARAMETERS: fn -- function; Python function to be evaluated args -- tuple; positional arguments for fn ...
[ "def", "timed", "(", "timeout", ",", "fn", ",", "args", "=", "(", ")", ",", "kargs", "=", "{", "}", ")", ":", "if", "timeout", "==", "0", ":", "return", "fn", "(", "*", "args", ",", "**", "kargs", ")", "submission", "=", "__ReturningThread", "(",...
For a nonzero timeout, evaluates a call expression in a separate thread. If the timeout is 0, the expression is evaluated in the main thread. PARAMETERS: fn -- function; Python function to be evaluated args -- tuple; positional arguments for fn kargs -- dict; keyword arguments for fn ...
[ "For", "a", "nonzero", "timeout", "evaluates", "a", "call", "expression", "in", "a", "separate", "thread", ".", "If", "the", "timeout", "is", "0", "the", "expression", "is", "evaluated", "in", "the", "main", "thread", "." ]
517f57dd76284af40ba9766e42d9222b644afd9c
https://github.com/okpy/ok-client/blob/517f57dd76284af40ba9766e42d9222b644afd9c/client/utils/timer.py#L7-L34
train
okpy/ok-client
client/api/assignment.py
Assignment.grade
def grade(self, question, env=None, skip_locked_cases=False): """Runs tests for a particular question. The setup and teardown will always be executed. question -- str; a question name (as would be entered at the command line env -- dict; an environment in which ...
python
def grade(self, question, env=None, skip_locked_cases=False): """Runs tests for a particular question. The setup and teardown will always be executed. question -- str; a question name (as would be entered at the command line env -- dict; an environment in which ...
[ "def", "grade", "(", "self", ",", "question", ",", "env", "=", "None", ",", "skip_locked_cases", "=", "False", ")", ":", "if", "env", "is", "None", ":", "import", "__main__", "env", "=", "__main__", ".", "__dict__", "messages", "=", "{", "}", "tests", ...
Runs tests for a particular question. The setup and teardown will always be executed. question -- str; a question name (as would be entered at the command line env -- dict; an environment in which to execute the tests. If None, uses the environment o...
[ "Runs", "tests", "for", "a", "particular", "question", ".", "The", "setup", "and", "teardown", "will", "always", "be", "executed", "." ]
517f57dd76284af40ba9766e42d9222b644afd9c
https://github.com/okpy/ok-client/blob/517f57dd76284af40ba9766e42d9222b644afd9c/client/api/assignment.py#L70-L103
train
okpy/ok-client
client/protocols/analytics.py
AnalyticsProtocol.run
def run(self, messages): """Returns some analytics about this autograder run.""" statistics = {} statistics['time'] = str(datetime.now()) statistics['time-utc'] = str(datetime.utcnow()) statistics['unlock'] = self.args.unlock if self.args.question: statistics...
python
def run(self, messages): """Returns some analytics about this autograder run.""" statistics = {} statistics['time'] = str(datetime.now()) statistics['time-utc'] = str(datetime.utcnow()) statistics['unlock'] = self.args.unlock if self.args.question: statistics...
[ "def", "run", "(", "self", ",", "messages", ")", ":", "statistics", "=", "{", "}", "statistics", "[", "'time'", "]", "=", "str", "(", "datetime", ".", "now", "(", ")", ")", "statistics", "[", "'time-utc'", "]", "=", "str", "(", "datetime", ".", "ut...
Returns some analytics about this autograder run.
[ "Returns", "some", "analytics", "about", "this", "autograder", "run", "." ]
517f57dd76284af40ba9766e42d9222b644afd9c
https://github.com/okpy/ok-client/blob/517f57dd76284af40ba9766e42d9222b644afd9c/client/protocols/analytics.py#L35-L52
train
okpy/ok-client
client/protocols/analytics.py
AnalyticsProtocol.log_run
def log_run(self, messages): """Record this run of the autograder to a local file. If the student does not specify what question(s) the student is running ok against, assume that the student is aiming to work on the question with the first failed test. If a student finishes ques...
python
def log_run(self, messages): """Record this run of the autograder to a local file. If the student does not specify what question(s) the student is running ok against, assume that the student is aiming to work on the question with the first failed test. If a student finishes ques...
[ "def", "log_run", "(", "self", ",", "messages", ")", ":", "history", "=", "self", ".", "read_history", "(", ")", "history", "[", "'all_attempts'", "]", "+=", "1", "questions", "=", "messages", "[", "'analytics'", "]", ".", "get", "(", "'question'", ",", ...
Record this run of the autograder to a local file. If the student does not specify what question(s) the student is running ok against, assume that the student is aiming to work on the question with the first failed test. If a student finishes questions 1 - N-1, the first test to fail wi...
[ "Record", "this", "run", "of", "the", "autograder", "to", "a", "local", "file", "." ]
517f57dd76284af40ba9766e42d9222b644afd9c
https://github.com/okpy/ok-client/blob/517f57dd76284af40ba9766e42d9222b644afd9c/client/protocols/analytics.py#L78-L143
train
okpy/ok-client
client/utils/network.py
check_ssl
def check_ssl(): """Attempts to import SSL or raises an exception.""" try: import ssl except: log.warning('Error importing SSL module', stack_info=True) print(SSL_ERROR_MESSAGE) sys.exit(1) else: log.info('SSL module is available') return ssl
python
def check_ssl(): """Attempts to import SSL or raises an exception.""" try: import ssl except: log.warning('Error importing SSL module', stack_info=True) print(SSL_ERROR_MESSAGE) sys.exit(1) else: log.info('SSL module is available') return ssl
[ "def", "check_ssl", "(", ")", ":", "try", ":", "import", "ssl", "except", ":", "log", ".", "warning", "(", "'Error importing SSL module'", ",", "stack_info", "=", "True", ")", "print", "(", "SSL_ERROR_MESSAGE", ")", "sys", ".", "exit", "(", "1", ")", "el...
Attempts to import SSL or raises an exception.
[ "Attempts", "to", "import", "SSL", "or", "raises", "an", "exception", "." ]
517f57dd76284af40ba9766e42d9222b644afd9c
https://github.com/okpy/ok-client/blob/517f57dd76284af40ba9766e42d9222b644afd9c/client/utils/network.py#L14-L24
train
okpy/ok-client
client/protocols/grading.py
GradingProtocol.run
def run(self, messages, env=None): """Run gradeable tests and print results and return analytics. RETURNS: dict; a mapping of test name -> JSON-serializable object. It is up to each test to determine what kind of data it wants to return as significant for analytics. However, all...
python
def run(self, messages, env=None): """Run gradeable tests and print results and return analytics. RETURNS: dict; a mapping of test name -> JSON-serializable object. It is up to each test to determine what kind of data it wants to return as significant for analytics. However, all...
[ "def", "run", "(", "self", ",", "messages", ",", "env", "=", "None", ")", ":", "if", "self", ".", "args", ".", "score", "or", "self", ".", "args", ".", "unlock", "or", "self", ".", "args", ".", "testing", ":", "return", "tests", "=", "self", ".",...
Run gradeable tests and print results and return analytics. RETURNS: dict; a mapping of test name -> JSON-serializable object. It is up to each test to determine what kind of data it wants to return as significant for analytics. However, all tests must include the number passed,...
[ "Run", "gradeable", "tests", "and", "print", "results", "and", "return", "analytics", "." ]
517f57dd76284af40ba9766e42d9222b644afd9c
https://github.com/okpy/ok-client/blob/517f57dd76284af40ba9766e42d9222b644afd9c/client/protocols/grading.py#L24-L46
train
okpy/ok-client
client/sources/common/core.py
Field.coerce
def coerce(self, value): """Subclasses should override this method for type coercion. Default version will simply return the argument. If the argument is not valid, a SerializeException is raised. For primitives like booleans, ints, floats, and strings, use this default version...
python
def coerce(self, value): """Subclasses should override this method for type coercion. Default version will simply return the argument. If the argument is not valid, a SerializeException is raised. For primitives like booleans, ints, floats, and strings, use this default version...
[ "def", "coerce", "(", "self", ",", "value", ")", ":", "if", "not", "self", ".", "is_valid", "(", "value", ")", ":", "raise", "ex", ".", "SerializeException", "(", "'{} is not a valid value for '", "'type {}'", ".", "format", "(", "value", ",", "self", ".",...
Subclasses should override this method for type coercion. Default version will simply return the argument. If the argument is not valid, a SerializeException is raised. For primitives like booleans, ints, floats, and strings, use this default version to avoid unintended type conversion...
[ "Subclasses", "should", "override", "this", "method", "for", "type", "coercion", "." ]
517f57dd76284af40ba9766e42d9222b644afd9c
https://github.com/okpy/ok-client/blob/517f57dd76284af40ba9766e42d9222b644afd9c/client/sources/common/core.py#L37-L48
train
okpy/ok-client
client/sources/common/core.py
Field.to_json
def to_json(self, value): """Subclasses should override this method for JSON encoding.""" if not self.is_valid(value): raise ex.SerializeException('Invalid value: {}'.format(value)) return value
python
def to_json(self, value): """Subclasses should override this method for JSON encoding.""" if not self.is_valid(value): raise ex.SerializeException('Invalid value: {}'.format(value)) return value
[ "def", "to_json", "(", "self", ",", "value", ")", ":", "if", "not", "self", ".", "is_valid", "(", "value", ")", ":", "raise", "ex", ".", "SerializeException", "(", "'Invalid value: {}'", ".", "format", "(", "value", ")", ")", "return", "value" ]
Subclasses should override this method for JSON encoding.
[ "Subclasses", "should", "override", "this", "method", "for", "JSON", "encoding", "." ]
517f57dd76284af40ba9766e42d9222b644afd9c
https://github.com/okpy/ok-client/blob/517f57dd76284af40ba9766e42d9222b644afd9c/client/sources/common/core.py#L50-L54
train
CRS-support/ftw
ftw/http.py
HttpResponse.parse_content_encoding
def parse_content_encoding(self, response_headers, response_data): """ Parses a response that contains Content-Encoding to retrieve response_data """ if response_headers['content-encoding'] == 'gzip': buf = StringIO.StringIO(response_data) zipbuf = gzip.Gz...
python
def parse_content_encoding(self, response_headers, response_data): """ Parses a response that contains Content-Encoding to retrieve response_data """ if response_headers['content-encoding'] == 'gzip': buf = StringIO.StringIO(response_data) zipbuf = gzip.Gz...
[ "def", "parse_content_encoding", "(", "self", ",", "response_headers", ",", "response_data", ")", ":", "if", "response_headers", "[", "'content-encoding'", "]", "==", "'gzip'", ":", "buf", "=", "StringIO", ".", "StringIO", "(", "response_data", ")", "zipbuf", "=...
Parses a response that contains Content-Encoding to retrieve response_data
[ "Parses", "a", "response", "that", "contains", "Content", "-", "Encoding", "to", "retrieve", "response_data" ]
1bbfd9b702e7e65532c1fd52bc82960556cefae5
https://github.com/CRS-support/ftw/blob/1bbfd9b702e7e65532c1fd52bc82960556cefae5/ftw/http.py#L41-L61
train
CRS-support/ftw
ftw/http.py
HttpResponse.process_response
def process_response(self): """ Parses an HTTP response after an HTTP request is sent """ split_response = self.response.split(self.CRLF) response_line = split_response[0] response_headers = {} response_data = None data_line = None for line_num in ...
python
def process_response(self): """ Parses an HTTP response after an HTTP request is sent """ split_response = self.response.split(self.CRLF) response_line = split_response[0] response_headers = {} response_data = None data_line = None for line_num in ...
[ "def", "process_response", "(", "self", ")", ":", "split_response", "=", "self", ".", "response", ".", "split", "(", "self", ".", "CRLF", ")", "response_line", "=", "split_response", "[", "0", "]", "response_headers", "=", "{", "}", "response_data", "=", "...
Parses an HTTP response after an HTTP request is sent
[ "Parses", "an", "HTTP", "response", "after", "an", "HTTP", "request", "is", "sent" ]
1bbfd9b702e7e65532c1fd52bc82960556cefae5
https://github.com/CRS-support/ftw/blob/1bbfd9b702e7e65532c1fd52bc82960556cefae5/ftw/http.py#L142-L218
train
CRS-support/ftw
ftw/http.py
HttpUA.send_request
def send_request(self, http_request): """ Send a request and get response """ self.request_object = http_request self.build_socket() self.build_request() try: self.sock.send(self.request) except socket.error as err: raise errors.Tes...
python
def send_request(self, http_request): """ Send a request and get response """ self.request_object = http_request self.build_socket() self.build_request() try: self.sock.send(self.request) except socket.error as err: raise errors.Tes...
[ "def", "send_request", "(", "self", ",", "http_request", ")", ":", "self", ".", "request_object", "=", "http_request", "self", ".", "build_socket", "(", ")", "self", ".", "build_request", "(", ")", "try", ":", "self", ".", "sock", ".", "send", "(", "self...
Send a request and get response
[ "Send", "a", "request", "and", "get", "response" ]
1bbfd9b702e7e65532c1fd52bc82960556cefae5
https://github.com/CRS-support/ftw/blob/1bbfd9b702e7e65532c1fd52bc82960556cefae5/ftw/http.py#L241-L258
train
CRS-support/ftw
ftw/http.py
HttpUA.build_socket
def build_socket(self): """ Generate either an HTTPS or HTTP socket """ try: self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.settimeout(self.SOCKET_TIMEOUT) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) ...
python
def build_socket(self): """ Generate either an HTTPS or HTTP socket """ try: self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.settimeout(self.SOCKET_TIMEOUT) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) ...
[ "def", "build_socket", "(", "self", ")", ":", "try", ":", "self", ".", "sock", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_STREAM", ")", "self", ".", "sock", ".", "settimeout", "(", "self", ".", "SOCKET_TIMEOU...
Generate either an HTTPS or HTTP socket
[ "Generate", "either", "an", "HTTPS", "or", "HTTP", "socket" ]
1bbfd9b702e7e65532c1fd52bc82960556cefae5
https://github.com/CRS-support/ftw/blob/1bbfd9b702e7e65532c1fd52bc82960556cefae5/ftw/http.py#L260-L282
train
CRS-support/ftw
ftw/http.py
HttpUA.find_cookie
def find_cookie(self): """ Find a list of all cookies for a given domain """ return_cookies = [] origin_domain = self.request_object.dest_addr for cookie in self.cookiejar: for cookie_morsals in cookie[0].values(): cover_domain = cookie_morsals...
python
def find_cookie(self): """ Find a list of all cookies for a given domain """ return_cookies = [] origin_domain = self.request_object.dest_addr for cookie in self.cookiejar: for cookie_morsals in cookie[0].values(): cover_domain = cookie_morsals...
[ "def", "find_cookie", "(", "self", ")", ":", "return_cookies", "=", "[", "]", "origin_domain", "=", "self", ".", "request_object", ".", "dest_addr", "for", "cookie", "in", "self", ".", "cookiejar", ":", "for", "cookie_morsals", "in", "cookie", "[", "0", "]...
Find a list of all cookies for a given domain
[ "Find", "a", "list", "of", "all", "cookies", "for", "a", "given", "domain" ]
1bbfd9b702e7e65532c1fd52bc82960556cefae5
https://github.com/CRS-support/ftw/blob/1bbfd9b702e7e65532c1fd52bc82960556cefae5/ftw/http.py#L284-L303
train
CRS-support/ftw
ftw/http.py
HttpUA.get_response
def get_response(self): """ Get the response from the socket """ self.sock.setblocking(0) our_data = [] # Beginning time begin = time.time() while True: # If we have data then if we're passed the timeout break if our_data and time.t...
python
def get_response(self): """ Get the response from the socket """ self.sock.setblocking(0) our_data = [] # Beginning time begin = time.time() while True: # If we have data then if we're passed the timeout break if our_data and time.t...
[ "def", "get_response", "(", "self", ")", ":", "self", ".", "sock", ".", "setblocking", "(", "0", ")", "our_data", "=", "[", "]", "begin", "=", "time", ".", "time", "(", ")", "while", "True", ":", "if", "our_data", "and", "time", ".", "time", "(", ...
Get the response from the socket
[ "Get", "the", "response", "from", "the", "socket" ]
1bbfd9b702e7e65532c1fd52bc82960556cefae5
https://github.com/CRS-support/ftw/blob/1bbfd9b702e7e65532c1fd52bc82960556cefae5/ftw/http.py#L410-L476
train
CRS-support/ftw
ftw/ruleset.py
Output.process_regex
def process_regex(self, key): """ Extract the value of key from dictionary if available and process it as a python regex """ return re.compile(self.output_dict[key]) if \ key in self.output_dict else None
python
def process_regex(self, key): """ Extract the value of key from dictionary if available and process it as a python regex """ return re.compile(self.output_dict[key]) if \ key in self.output_dict else None
[ "def", "process_regex", "(", "self", ",", "key", ")", ":", "return", "re", ".", "compile", "(", "self", ".", "output_dict", "[", "key", "]", ")", "if", "key", "in", "self", ".", "output_dict", "else", "None" ]
Extract the value of key from dictionary if available and process it as a python regex
[ "Extract", "the", "value", "of", "key", "from", "dictionary", "if", "available", "and", "process", "it", "as", "a", "python", "regex" ]
1bbfd9b702e7e65532c1fd52bc82960556cefae5
https://github.com/CRS-support/ftw/blob/1bbfd9b702e7e65532c1fd52bc82960556cefae5/ftw/ruleset.py#L70-L76
train
CRS-support/ftw
ftw/util.py
instantiate_database
def instantiate_database(sqlite_file='ftwj.sqlite'): """ Create journal database for FTW runs """ table_name = 'ftw' col1 = 'rule_id' col1_t = 'INTEGER' col2 = 'test_id' col2_t = 'STRING' col3 = 'time_start' col3_t = 'TEXT' col4 = 'time_end' col4_t = 'TEXT' col5 = 're...
python
def instantiate_database(sqlite_file='ftwj.sqlite'): """ Create journal database for FTW runs """ table_name = 'ftw' col1 = 'rule_id' col1_t = 'INTEGER' col2 = 'test_id' col2_t = 'STRING' col3 = 'time_start' col3_t = 'TEXT' col4 = 'time_end' col4_t = 'TEXT' col5 = 're...
[ "def", "instantiate_database", "(", "sqlite_file", "=", "'ftwj.sqlite'", ")", ":", "table_name", "=", "'ftw'", "col1", "=", "'rule_id'", "col1_t", "=", "'INTEGER'", "col2", "=", "'test_id'", "col2_t", "=", "'STRING'", "col3", "=", "'time_start'", "col3_t", "=", ...
Create journal database for FTW runs
[ "Create", "journal", "database", "for", "FTW", "runs" ]
1bbfd9b702e7e65532c1fd52bc82960556cefae5
https://github.com/CRS-support/ftw/blob/1bbfd9b702e7e65532c1fd52bc82960556cefae5/ftw/util.py#L18-L51
train
CRS-support/ftw
ftw/util.py
get_rulesets
def get_rulesets(ruledir, recurse): """ List of ruleset objects extracted from the yaml directory """ if os.path.isdir(ruledir) and recurse: yaml_files = [y for x in os.walk(ruledir) for y in glob(os.path.join(x[0], '*.yaml'))] elif os.path.isdir(ruledir) and not recurse: yaml_files ...
python
def get_rulesets(ruledir, recurse): """ List of ruleset objects extracted from the yaml directory """ if os.path.isdir(ruledir) and recurse: yaml_files = [y for x in os.walk(ruledir) for y in glob(os.path.join(x[0], '*.yaml'))] elif os.path.isdir(ruledir) and not recurse: yaml_files ...
[ "def", "get_rulesets", "(", "ruledir", ",", "recurse", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "ruledir", ")", "and", "recurse", ":", "yaml_files", "=", "[", "y", "for", "x", "in", "os", ".", "walk", "(", "ruledir", ")", "for", "y", ...
List of ruleset objects extracted from the yaml directory
[ "List", "of", "ruleset", "objects", "extracted", "from", "the", "yaml", "directory" ]
1bbfd9b702e7e65532c1fd52bc82960556cefae5
https://github.com/CRS-support/ftw/blob/1bbfd9b702e7e65532c1fd52bc82960556cefae5/ftw/util.py#L53-L67
train
CRS-support/ftw
ftw/util.py
extract_yaml
def extract_yaml(yaml_files): """ Take a list of yaml_files and load them to return back to the testing program """ loaded_yaml = [] for yaml_file in yaml_files: try: with open(yaml_file, 'r') as fd: loaded_yaml.append(yaml.safe_load(fd)) except IOErro...
python
def extract_yaml(yaml_files): """ Take a list of yaml_files and load them to return back to the testing program """ loaded_yaml = [] for yaml_file in yaml_files: try: with open(yaml_file, 'r') as fd: loaded_yaml.append(yaml.safe_load(fd)) except IOErro...
[ "def", "extract_yaml", "(", "yaml_files", ")", ":", "loaded_yaml", "=", "[", "]", "for", "yaml_file", "in", "yaml_files", ":", "try", ":", "with", "open", "(", "yaml_file", ",", "'r'", ")", "as", "fd", ":", "loaded_yaml", ".", "append", "(", "yaml", "....
Take a list of yaml_files and load them to return back to the testing program
[ "Take", "a", "list", "of", "yaml_files", "and", "load", "them", "to", "return", "back", "to", "the", "testing", "program" ]
1bbfd9b702e7e65532c1fd52bc82960556cefae5
https://github.com/CRS-support/ftw/blob/1bbfd9b702e7e65532c1fd52bc82960556cefae5/ftw/util.py#L77-L96
train
tipsi/aiozk
aiozk/protocol/response.py
Response.deserialize
def deserialize(cls, raw_bytes): """ Deserializes the given raw bytes into an instance. Since this is a subclass of ``Part`` but a top-level one (i.e. no other subclass of ``Part`` would have a ``Response`` as a part) this merely has to parse the raw bytes and discard the result...
python
def deserialize(cls, raw_bytes): """ Deserializes the given raw bytes into an instance. Since this is a subclass of ``Part`` but a top-level one (i.e. no other subclass of ``Part`` would have a ``Response`` as a part) this merely has to parse the raw bytes and discard the result...
[ "def", "deserialize", "(", "cls", ",", "raw_bytes", ")", ":", "instance", ",", "_", "=", "cls", ".", "parse", "(", "raw_bytes", ",", "offset", "=", "0", ")", "return", "instance" ]
Deserializes the given raw bytes into an instance. Since this is a subclass of ``Part`` but a top-level one (i.e. no other subclass of ``Part`` would have a ``Response`` as a part) this merely has to parse the raw bytes and discard the resulting offset.
[ "Deserializes", "the", "given", "raw", "bytes", "into", "an", "instance", "." ]
96d2f543de248c6d993b5bfe6621167dd1eb8223
https://github.com/tipsi/aiozk/blob/96d2f543de248c6d993b5bfe6621167dd1eb8223/aiozk/protocol/response.py#L27-L37
train
tipsi/aiozk
aiozk/protocol/part.py
Part.render
def render(self, parts=None): """ Returns a two-element tuple with the ``struct`` format and values. Iterates over the applicable sub-parts and calls `render()` on them, accumulating the format string and values. Optionally takes a subset of parts to render, default behavior is...
python
def render(self, parts=None): """ Returns a two-element tuple with the ``struct`` format and values. Iterates over the applicable sub-parts and calls `render()` on them, accumulating the format string and values. Optionally takes a subset of parts to render, default behavior is...
[ "def", "render", "(", "self", ",", "parts", "=", "None", ")", ":", "if", "not", "parts", ":", "parts", "=", "self", ".", "parts", "fmt", "=", "[", "]", "data", "=", "[", "]", "for", "name", ",", "part_class", "in", "parts", ":", "if", "issubclass...
Returns a two-element tuple with the ``struct`` format and values. Iterates over the applicable sub-parts and calls `render()` on them, accumulating the format string and values. Optionally takes a subset of parts to render, default behavior is to render all sub-parts belonging to the ...
[ "Returns", "a", "two", "-", "element", "tuple", "with", "the", "struct", "format", "and", "values", "." ]
96d2f543de248c6d993b5bfe6621167dd1eb8223
https://github.com/tipsi/aiozk/blob/96d2f543de248c6d993b5bfe6621167dd1eb8223/aiozk/protocol/part.py#L29-L56
train
tipsi/aiozk
aiozk/protocol/primitives.py
VariablePrimitive.render
def render(self): """ Returns the ``struct`` format and list of the size and value. The format is derived from the size primitive and the length of the resulting encoded value (e.g. the format for a string of 'foo' ends up as 'h3s'. .. note :: The value is exp...
python
def render(self): """ Returns the ``struct`` format and list of the size and value. The format is derived from the size primitive and the length of the resulting encoded value (e.g. the format for a string of 'foo' ends up as 'h3s'. .. note :: The value is exp...
[ "def", "render", "(", "self", ")", ":", "size_format", "=", "self", ".", "size_primitive", ".", "fmt", "if", "self", ".", "value", "is", "None", ":", "return", "size_format", ",", "[", "-", "1", "]", "value", "=", "self", ".", "render_value", "(", "s...
Returns the ``struct`` format and list of the size and value. The format is derived from the size primitive and the length of the resulting encoded value (e.g. the format for a string of 'foo' ends up as 'h3s'. .. note :: The value is expected to be string-able (wrapped in ``...
[ "Returns", "the", "struct", "format", "and", "list", "of", "the", "size", "and", "value", "." ]
96d2f543de248c6d993b5bfe6621167dd1eb8223
https://github.com/tipsi/aiozk/blob/96d2f543de248c6d993b5bfe6621167dd1eb8223/aiozk/protocol/primitives.py#L65-L88
train
tipsi/aiozk
aiozk/protocol/primitives.py
Vector.of
def of(cls, part_class): """ Creates a new class with the ``item_class`` attribute properly set. """ copy = type( "VectorOf%s" % part_class.__name__, cls.__bases__, dict(cls.__dict__) ) copy.item_class = part_class return copy
python
def of(cls, part_class): """ Creates a new class with the ``item_class`` attribute properly set. """ copy = type( "VectorOf%s" % part_class.__name__, cls.__bases__, dict(cls.__dict__) ) copy.item_class = part_class return copy
[ "def", "of", "(", "cls", ",", "part_class", ")", ":", "copy", "=", "type", "(", "\"VectorOf%s\"", "%", "part_class", ".", "__name__", ",", "cls", ".", "__bases__", ",", "dict", "(", "cls", ".", "__dict__", ")", ")", "copy", ".", "item_class", "=", "p...
Creates a new class with the ``item_class`` attribute properly set.
[ "Creates", "a", "new", "class", "with", "the", "item_class", "attribute", "properly", "set", "." ]
96d2f543de248c6d993b5bfe6621167dd1eb8223
https://github.com/tipsi/aiozk/blob/96d2f543de248c6d993b5bfe6621167dd1eb8223/aiozk/protocol/primitives.py#L199-L209
train
tipsi/aiozk
aiozk/protocol/primitives.py
Vector.render
def render(self): """ Creates a composite ``struct`` format and the data to render with it. The format and data are prefixed with a 32-bit integer denoting the number of elements, after which each of the items in the array value are ``render()``-ed and added to the format and da...
python
def render(self): """ Creates a composite ``struct`` format and the data to render with it. The format and data are prefixed with a 32-bit integer denoting the number of elements, after which each of the items in the array value are ``render()``-ed and added to the format and da...
[ "def", "render", "(", "self", ")", ":", "value", "=", "self", ".", "value", "if", "value", "is", "None", ":", "value", "=", "[", "]", "fmt", "=", "[", "Int", ".", "fmt", "]", "data", "=", "[", "len", "(", "value", ")", "]", "for", "item_value",...
Creates a composite ``struct`` format and the data to render with it. The format and data are prefixed with a 32-bit integer denoting the number of elements, after which each of the items in the array value are ``render()``-ed and added to the format and data as well.
[ "Creates", "a", "composite", "struct", "format", "and", "the", "data", "to", "render", "with", "it", "." ]
96d2f543de248c6d993b5bfe6621167dd1eb8223
https://github.com/tipsi/aiozk/blob/96d2f543de248c6d993b5bfe6621167dd1eb8223/aiozk/protocol/primitives.py#L211-L236
train
tipsi/aiozk
aiozk/protocol/primitives.py
Vector.parse
def parse(cls, buff, offset): """ Parses a raw buffer at offset and returns the resulting array value. Starts off by `parse()`-ing the 32-bit element count, followed by parsing items out of the buffer "count" times. """ count, offset = Int.parse(buff, offset) va...
python
def parse(cls, buff, offset): """ Parses a raw buffer at offset and returns the resulting array value. Starts off by `parse()`-ing the 32-bit element count, followed by parsing items out of the buffer "count" times. """ count, offset = Int.parse(buff, offset) va...
[ "def", "parse", "(", "cls", ",", "buff", ",", "offset", ")", ":", "count", ",", "offset", "=", "Int", ".", "parse", "(", "buff", ",", "offset", ")", "values", "=", "[", "]", "for", "_", "in", "range", "(", "count", ")", ":", "value", ",", "new_...
Parses a raw buffer at offset and returns the resulting array value. Starts off by `parse()`-ing the 32-bit element count, followed by parsing items out of the buffer "count" times.
[ "Parses", "a", "raw", "buffer", "at", "offset", "and", "returns", "the", "resulting", "array", "value", "." ]
96d2f543de248c6d993b5bfe6621167dd1eb8223
https://github.com/tipsi/aiozk/blob/96d2f543de248c6d993b5bfe6621167dd1eb8223/aiozk/protocol/primitives.py#L239-L255
train
tipsi/aiozk
aiozk/recipes/allocator.py
round_robin
def round_robin(members, items): """ Default allocator with a round robin approach. In this algorithm, each member of the group is cycled over and given an item until there are no items left. This assumes roughly equal capacity for each member and aims for even distribution of item counts. """...
python
def round_robin(members, items): """ Default allocator with a round robin approach. In this algorithm, each member of the group is cycled over and given an item until there are no items left. This assumes roughly equal capacity for each member and aims for even distribution of item counts. """...
[ "def", "round_robin", "(", "members", ",", "items", ")", ":", "allocation", "=", "collections", ".", "defaultdict", "(", "set", ")", "for", "member", ",", "item", "in", "zip", "(", "itertools", ".", "cycle", "(", "members", ")", ",", "items", ")", ":",...
Default allocator with a round robin approach. In this algorithm, each member of the group is cycled over and given an item until there are no items left. This assumes roughly equal capacity for each member and aims for even distribution of item counts.
[ "Default", "allocator", "with", "a", "round", "robin", "approach", "." ]
96d2f543de248c6d993b5bfe6621167dd1eb8223
https://github.com/tipsi/aiozk/blob/96d2f543de248c6d993b5bfe6621167dd1eb8223/aiozk/recipes/allocator.py#L121-L134
train
sqlboy/fileseq
src/fileseq/utils.py
xfrange
def xfrange(start, stop, step=1, maxSize=-1): """ Returns a generator that yields the frames from start to stop, inclusive. In other words it adds or subtracts a frame, as necessary, to return the stop value as well, if the stepped range would touch that value. Args: start (int): st...
python
def xfrange(start, stop, step=1, maxSize=-1): """ Returns a generator that yields the frames from start to stop, inclusive. In other words it adds or subtracts a frame, as necessary, to return the stop value as well, if the stepped range would touch that value. Args: start (int): st...
[ "def", "xfrange", "(", "start", ",", "stop", ",", "step", "=", "1", ",", "maxSize", "=", "-", "1", ")", ":", "if", "start", "<=", "stop", ":", "stop", ",", "step", "=", "stop", "+", "1", ",", "abs", "(", "step", ")", "else", ":", "stop", ",",...
Returns a generator that yields the frames from start to stop, inclusive. In other words it adds or subtracts a frame, as necessary, to return the stop value as well, if the stepped range would touch that value. Args: start (int): stop (int): step (int): Note that the sign will be i...
[ "Returns", "a", "generator", "that", "yields", "the", "frames", "from", "start", "to", "stop", "inclusive", ".", "In", "other", "words", "it", "adds", "or", "subtracts", "a", "frame", "as", "necessary", "to", "return", "the", "stop", "value", "as", "well",...
f26c3c3c383134ce27d5dfe37793e1ebe88e69ad
https://github.com/sqlboy/fileseq/blob/f26c3c3c383134ce27d5dfe37793e1ebe88e69ad/src/fileseq/utils.py#L63-L94
train
sqlboy/fileseq
src/fileseq/utils.py
unique
def unique(seen, *iterables): """ Get the unique items in iterables while preserving order. Note that this mutates the seen set provided only when the returned generator is used. Args: seen (set): either an empty set, or the set of things already seen *iterables: one or more iterable l...
python
def unique(seen, *iterables): """ Get the unique items in iterables while preserving order. Note that this mutates the seen set provided only when the returned generator is used. Args: seen (set): either an empty set, or the set of things already seen *iterables: one or more iterable l...
[ "def", "unique", "(", "seen", ",", "*", "iterables", ")", ":", "_add", "=", "seen", ".", "add", "return", "(", "i", "for", "i", "in", "chain", "(", "*", "iterables", ")", "if", "i", "not", "in", "seen", "and", "not", "_add", "(", "i", ")", ")" ...
Get the unique items in iterables while preserving order. Note that this mutates the seen set provided only when the returned generator is used. Args: seen (set): either an empty set, or the set of things already seen *iterables: one or more iterable lists to chain together Returns: ...
[ "Get", "the", "unique", "items", "in", "iterables", "while", "preserving", "order", ".", "Note", "that", "this", "mutates", "the", "seen", "set", "provided", "only", "when", "the", "returned", "generator", "is", "used", "." ]
f26c3c3c383134ce27d5dfe37793e1ebe88e69ad
https://github.com/sqlboy/fileseq/blob/f26c3c3c383134ce27d5dfe37793e1ebe88e69ad/src/fileseq/utils.py#L97-L112
train
sqlboy/fileseq
src/fileseq/filesequence.py
FileSequence.copy
def copy(self): """ Create a deep copy of this sequence Returns: :obj:`.FileSequence`: """ fs = self.__class__.__new__(self.__class__) fs.__dict__ = self.__dict__.copy() fs._frameSet = None if self._frameSet is not None: fs._frameS...
python
def copy(self): """ Create a deep copy of this sequence Returns: :obj:`.FileSequence`: """ fs = self.__class__.__new__(self.__class__) fs.__dict__ = self.__dict__.copy() fs._frameSet = None if self._frameSet is not None: fs._frameS...
[ "def", "copy", "(", "self", ")", ":", "fs", "=", "self", ".", "__class__", ".", "__new__", "(", "self", ".", "__class__", ")", "fs", ".", "__dict__", "=", "self", ".", "__dict__", ".", "copy", "(", ")", "fs", ".", "_frameSet", "=", "None", "if", ...
Create a deep copy of this sequence Returns: :obj:`.FileSequence`:
[ "Create", "a", "deep", "copy", "of", "this", "sequence" ]
f26c3c3c383134ce27d5dfe37793e1ebe88e69ad
https://github.com/sqlboy/fileseq/blob/f26c3c3c383134ce27d5dfe37793e1ebe88e69ad/src/fileseq/filesequence.py#L79-L91
train
sqlboy/fileseq
src/fileseq/filesequence.py
FileSequence.format
def format(self, template="{basename}{range}{padding}{extension}"): """Return the file sequence as a formatted string according to the given template. Utilizes the python string format syntax. Available keys include: * basename - the basename of the sequence. * extensio...
python
def format(self, template="{basename}{range}{padding}{extension}"): """Return the file sequence as a formatted string according to the given template. Utilizes the python string format syntax. Available keys include: * basename - the basename of the sequence. * extensio...
[ "def", "format", "(", "self", ",", "template", "=", "\"{basename}{range}{padding}{extension}\"", ")", ":", "inverted", "=", "(", "self", ".", "invertedFrameRange", "(", ")", "or", "\"\"", ")", "if", "\"{inverted}\"", "in", "template", "else", "\"\"", "return", ...
Return the file sequence as a formatted string according to the given template. Utilizes the python string format syntax. Available keys include: * basename - the basename of the sequence. * extension - the file extension of the sequence. * start - the start frame. ...
[ "Return", "the", "file", "sequence", "as", "a", "formatted", "string", "according", "to", "the", "given", "template", "." ]
f26c3c3c383134ce27d5dfe37793e1ebe88e69ad
https://github.com/sqlboy/fileseq/blob/f26c3c3c383134ce27d5dfe37793e1ebe88e69ad/src/fileseq/filesequence.py#L93-L132
train
sqlboy/fileseq
src/fileseq/filesequence.py
FileSequence.setDirname
def setDirname(self, dirname): """ Set a new directory name for the sequence. Args: dirname (str): the new directory name """ # Make sure the dirname always ends in # a path separator character sep = utils._getPathSep(dirname) if not dirname.e...
python
def setDirname(self, dirname): """ Set a new directory name for the sequence. Args: dirname (str): the new directory name """ # Make sure the dirname always ends in # a path separator character sep = utils._getPathSep(dirname) if not dirname.e...
[ "def", "setDirname", "(", "self", ",", "dirname", ")", ":", "sep", "=", "utils", ".", "_getPathSep", "(", "dirname", ")", "if", "not", "dirname", ".", "endswith", "(", "sep", ")", ":", "dirname", "+=", "sep", "self", ".", "_dir", "=", "utils", ".", ...
Set a new directory name for the sequence. Args: dirname (str): the new directory name
[ "Set", "a", "new", "directory", "name", "for", "the", "sequence", "." ]
f26c3c3c383134ce27d5dfe37793e1ebe88e69ad
https://github.com/sqlboy/fileseq/blob/f26c3c3c383134ce27d5dfe37793e1ebe88e69ad/src/fileseq/filesequence.py#L157-L170
train
sqlboy/fileseq
src/fileseq/filesequence.py
FileSequence.setExtension
def setExtension(self, ext): """ Set a new file extension for the sequence. Note: A leading period will be added if none is provided. Args: ext (str): the new file extension """ if ext[0] != ".": ext = "." + ext self._ext = ut...
python
def setExtension(self, ext): """ Set a new file extension for the sequence. Note: A leading period will be added if none is provided. Args: ext (str): the new file extension """ if ext[0] != ".": ext = "." + ext self._ext = ut...
[ "def", "setExtension", "(", "self", ",", "ext", ")", ":", "if", "ext", "[", "0", "]", "!=", "\".\"", ":", "ext", "=", "\".\"", "+", "ext", "self", ".", "_ext", "=", "utils", ".", "asString", "(", "ext", ")" ]
Set a new file extension for the sequence. Note: A leading period will be added if none is provided. Args: ext (str): the new file extension
[ "Set", "a", "new", "file", "extension", "for", "the", "sequence", "." ]
f26c3c3c383134ce27d5dfe37793e1ebe88e69ad
https://github.com/sqlboy/fileseq/blob/f26c3c3c383134ce27d5dfe37793e1ebe88e69ad/src/fileseq/filesequence.py#L238-L250
train
sqlboy/fileseq
src/fileseq/filesequence.py
FileSequence.frame
def frame(self, frame): """ Return a path go the given frame in the sequence. Integer or string digits are treated as a frame number and padding is applied, all other values are passed though. Examples: >>> seq.frame(1) /foo/bar.0001.exr >>> ...
python
def frame(self, frame): """ Return a path go the given frame in the sequence. Integer or string digits are treated as a frame number and padding is applied, all other values are passed though. Examples: >>> seq.frame(1) /foo/bar.0001.exr >>> ...
[ "def", "frame", "(", "self", ",", "frame", ")", ":", "try", ":", "zframe", "=", "str", "(", "int", "(", "frame", ")", ")", ".", "zfill", "(", "self", ".", "_zfill", ")", "except", "ValueError", ":", "zframe", "=", "frame", "if", "self", ".", "_zf...
Return a path go the given frame in the sequence. Integer or string digits are treated as a frame number and padding is applied, all other values are passed though. Examples: >>> seq.frame(1) /foo/bar.0001.exr >>> seq.frame("#") /foo/bar.#.exr ...
[ "Return", "a", "path", "go", "the", "given", "frame", "in", "the", "sequence", ".", "Integer", "or", "string", "digits", "are", "treated", "as", "a", "frame", "number", "and", "padding", "is", "applied", "all", "other", "values", "are", "passed", "though",...
f26c3c3c383134ce27d5dfe37793e1ebe88e69ad
https://github.com/sqlboy/fileseq/blob/f26c3c3c383134ce27d5dfe37793e1ebe88e69ad/src/fileseq/filesequence.py#L334-L365
train
sqlboy/fileseq
src/fileseq/filesequence.py
FileSequence.yield_sequences_in_list
def yield_sequences_in_list(paths): """ Yield the discrete sequences within paths. This does not try to determine if the files actually exist on disk, it assumes you already know that. Args: paths (list[str]): a list of paths Yields: :obj:`FileS...
python
def yield_sequences_in_list(paths): """ Yield the discrete sequences within paths. This does not try to determine if the files actually exist on disk, it assumes you already know that. Args: paths (list[str]): a list of paths Yields: :obj:`FileS...
[ "def", "yield_sequences_in_list", "(", "paths", ")", ":", "seqs", "=", "{", "}", "_check", "=", "DISK_RE", ".", "match", "for", "match", "in", "ifilter", "(", "None", ",", "imap", "(", "_check", ",", "imap", "(", "utils", ".", "asString", ",", "paths",...
Yield the discrete sequences within paths. This does not try to determine if the files actually exist on disk, it assumes you already know that. Args: paths (list[str]): a list of paths Yields: :obj:`FileSequence`:
[ "Yield", "the", "discrete", "sequences", "within", "paths", ".", "This", "does", "not", "try", "to", "determine", "if", "the", "files", "actually", "exist", "on", "disk", "it", "assumes", "you", "already", "know", "that", "." ]
f26c3c3c383134ce27d5dfe37793e1ebe88e69ad
https://github.com/sqlboy/fileseq/blob/f26c3c3c383134ce27d5dfe37793e1ebe88e69ad/src/fileseq/filesequence.py#L470-L507
train
sqlboy/fileseq
src/fileseq/filesequence.py
FileSequence.findSequencesOnDisk
def findSequencesOnDisk(cls, pattern, include_hidden=False, strictPadding=False): """ Yield the sequences found in the given directory. Examples: >>> findSequencesOnDisk('/path/to/files') The `pattern` can also specify glob-like shell wildcards including the following: ...
python
def findSequencesOnDisk(cls, pattern, include_hidden=False, strictPadding=False): """ Yield the sequences found in the given directory. Examples: >>> findSequencesOnDisk('/path/to/files') The `pattern` can also specify glob-like shell wildcards including the following: ...
[ "def", "findSequencesOnDisk", "(", "cls", ",", "pattern", ",", "include_hidden", "=", "False", ",", "strictPadding", "=", "False", ")", ":", "_not_hidden", "=", "lambda", "f", ":", "not", "f", ".", "startswith", "(", "'.'", ")", "_match_pattern", "=", "Non...
Yield the sequences found in the given directory. Examples: >>> findSequencesOnDisk('/path/to/files') The `pattern` can also specify glob-like shell wildcards including the following: * ``?`` - 1 wildcard character * ``*`` - 1 or more wildcard charac...
[ "Yield", "the", "sequences", "found", "in", "the", "given", "directory", "." ]
f26c3c3c383134ce27d5dfe37793e1ebe88e69ad
https://github.com/sqlboy/fileseq/blob/f26c3c3c383134ce27d5dfe37793e1ebe88e69ad/src/fileseq/filesequence.py#L525-L633
train
sqlboy/fileseq
src/fileseq/filesequence.py
FileSequence.findSequenceOnDisk
def findSequenceOnDisk(cls, pattern, strictPadding=False): """ Search for a specific sequence on disk. The padding characters used in the `pattern` are used to filter the frame values of the files on disk (if `strictPadding` is True). Examples: Find sequence matchin...
python
def findSequenceOnDisk(cls, pattern, strictPadding=False): """ Search for a specific sequence on disk. The padding characters used in the `pattern` are used to filter the frame values of the files on disk (if `strictPadding` is True). Examples: Find sequence matchin...
[ "def", "findSequenceOnDisk", "(", "cls", ",", "pattern", ",", "strictPadding", "=", "False", ")", ":", "seq", "=", "cls", "(", "pattern", ")", "if", "seq", ".", "frameRange", "(", ")", "==", "''", "and", "seq", ".", "padding", "(", ")", "==", "''", ...
Search for a specific sequence on disk. The padding characters used in the `pattern` are used to filter the frame values of the files on disk (if `strictPadding` is True). Examples: Find sequence matching basename and extension, and a wildcard for any frame. ...
[ "Search", "for", "a", "specific", "sequence", "on", "disk", "." ]
f26c3c3c383134ce27d5dfe37793e1ebe88e69ad
https://github.com/sqlboy/fileseq/blob/f26c3c3c383134ce27d5dfe37793e1ebe88e69ad/src/fileseq/filesequence.py#L636-L690
train
sqlboy/fileseq
src/fileseq/filesequence.py
FileSequence._filterByPaddingNum
def _filterByPaddingNum(cls, iterable, num): """ Yield only path elements from iterable which have a frame padding that matches the given target padding number Args: iterable (collections.Iterable): num (int): Yields: str: """ ...
python
def _filterByPaddingNum(cls, iterable, num): """ Yield only path elements from iterable which have a frame padding that matches the given target padding number Args: iterable (collections.Iterable): num (int): Yields: str: """ ...
[ "def", "_filterByPaddingNum", "(", "cls", ",", "iterable", ",", "num", ")", ":", "_check", "=", "DISK_RE", ".", "match", "for", "item", "in", "iterable", ":", "matches", "=", "_check", "(", "item", ")", "if", "not", "matches", ":", "if", "num", "<=", ...
Yield only path elements from iterable which have a frame padding that matches the given target padding number Args: iterable (collections.Iterable): num (int): Yields: str:
[ "Yield", "only", "path", "elements", "from", "iterable", "which", "have", "a", "frame", "padding", "that", "matches", "the", "given", "target", "padding", "number" ]
f26c3c3c383134ce27d5dfe37793e1ebe88e69ad
https://github.com/sqlboy/fileseq/blob/f26c3c3c383134ce27d5dfe37793e1ebe88e69ad/src/fileseq/filesequence.py#L693-L742
train
sqlboy/fileseq
src/fileseq/filesequence.py
FileSequence.getPaddingNum
def getPaddingNum(chars): """ Given a supported group of padding characters, return the amount of padding. Args: chars (str): a supported group of padding characters Returns: int: Raises: ValueError: if unsupported padding character is detec...
python
def getPaddingNum(chars): """ Given a supported group of padding characters, return the amount of padding. Args: chars (str): a supported group of padding characters Returns: int: Raises: ValueError: if unsupported padding character is detec...
[ "def", "getPaddingNum", "(", "chars", ")", ":", "match", "=", "PRINTF_SYNTAX_PADDING_RE", ".", "match", "(", "chars", ")", "if", "match", ":", "return", "int", "(", "match", ".", "group", "(", "1", ")", ")", "try", ":", "return", "sum", "(", "[", "PA...
Given a supported group of padding characters, return the amount of padding. Args: chars (str): a supported group of padding characters Returns: int: Raises: ValueError: if unsupported padding character is detected
[ "Given", "a", "supported", "group", "of", "padding", "characters", "return", "the", "amount", "of", "padding", "." ]
f26c3c3c383134ce27d5dfe37793e1ebe88e69ad
https://github.com/sqlboy/fileseq/blob/f26c3c3c383134ce27d5dfe37793e1ebe88e69ad/src/fileseq/filesequence.py#L763-L786
train
sqlboy/fileseq
src/fileseq/filesequence.py
FileSequence.conformPadding
def conformPadding(cls, chars): """ Ensure alternate input padding formats are conformed to formats defined in PAD_MAP If chars is already a format defined in PAD_MAP, then it is returned unmodified. Example:: '#' -> '#' '@@@@' -> '@@@@' ...
python
def conformPadding(cls, chars): """ Ensure alternate input padding formats are conformed to formats defined in PAD_MAP If chars is already a format defined in PAD_MAP, then it is returned unmodified. Example:: '#' -> '#' '@@@@' -> '@@@@' ...
[ "def", "conformPadding", "(", "cls", ",", "chars", ")", ":", "pad", "=", "chars", "if", "pad", "and", "pad", "[", "0", "]", "not", "in", "PAD_MAP", ":", "pad", "=", "cls", ".", "getPaddingChars", "(", "cls", ".", "getPaddingNum", "(", "pad", ")", "...
Ensure alternate input padding formats are conformed to formats defined in PAD_MAP If chars is already a format defined in PAD_MAP, then it is returned unmodified. Example:: '#' -> '#' '@@@@' -> '@@@@' '%04d' -> '#' Args: char...
[ "Ensure", "alternate", "input", "padding", "formats", "are", "conformed", "to", "formats", "defined", "in", "PAD_MAP" ]
f26c3c3c383134ce27d5dfe37793e1ebe88e69ad
https://github.com/sqlboy/fileseq/blob/f26c3c3c383134ce27d5dfe37793e1ebe88e69ad/src/fileseq/filesequence.py#L789-L814
train
sqlboy/fileseq
src/fileseq/frameset.py
FrameSet._cast_to_frameset
def _cast_to_frameset(cls, other): """ Private method to simplify comparison operations. Args: other (:class:`FrameSet` or set or frozenset or or iterable): item to be compared Returns: :class:`FrameSet` Raises: :class:`NotImplemented`: if a...
python
def _cast_to_frameset(cls, other): """ Private method to simplify comparison operations. Args: other (:class:`FrameSet` or set or frozenset or or iterable): item to be compared Returns: :class:`FrameSet` Raises: :class:`NotImplemented`: if a...
[ "def", "_cast_to_frameset", "(", "cls", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "FrameSet", ")", ":", "return", "other", "try", ":", "return", "FrameSet", "(", "other", ")", "except", "Exception", ":", "return", "NotImplemented" ]
Private method to simplify comparison operations. Args: other (:class:`FrameSet` or set or frozenset or or iterable): item to be compared Returns: :class:`FrameSet` Raises: :class:`NotImplemented`: if a comparison is impossible
[ "Private", "method", "to", "simplify", "comparison", "operations", "." ]
f26c3c3c383134ce27d5dfe37793e1ebe88e69ad
https://github.com/sqlboy/fileseq/blob/f26c3c3c383134ce27d5dfe37793e1ebe88e69ad/src/fileseq/frameset.py#L243-L261
train
sqlboy/fileseq
src/fileseq/frameset.py
FrameSet.issubset
def issubset(self, other): """ Check if the contents of `self` is a subset of the contents of `other.` Args: other (:class:`FrameSet`): Returns: bool: :class:`NotImplemented`: if `other` fails to convert to a :class:`FrameSet` """ ...
python
def issubset(self, other): """ Check if the contents of `self` is a subset of the contents of `other.` Args: other (:class:`FrameSet`): Returns: bool: :class:`NotImplemented`: if `other` fails to convert to a :class:`FrameSet` """ ...
[ "def", "issubset", "(", "self", ",", "other", ")", ":", "other", "=", "self", ".", "_cast_to_frameset", "(", "other", ")", "if", "other", "is", "NotImplemented", ":", "return", "NotImplemented", "return", "self", ".", "items", "<=", "other", ".", "items" ]
Check if the contents of `self` is a subset of the contents of `other.` Args: other (:class:`FrameSet`): Returns: bool: :class:`NotImplemented`: if `other` fails to convert to a :class:`FrameSet`
[ "Check", "if", "the", "contents", "of", "self", "is", "a", "subset", "of", "the", "contents", "of", "other", "." ]
f26c3c3c383134ce27d5dfe37793e1ebe88e69ad
https://github.com/sqlboy/fileseq/blob/f26c3c3c383134ce27d5dfe37793e1ebe88e69ad/src/fileseq/frameset.py#L818-L833
train
sqlboy/fileseq
src/fileseq/frameset.py
FrameSet.issuperset
def issuperset(self, other): """ Check if the contents of `self` is a superset of the contents of `other.` Args: other (:class:`FrameSet`): Returns: bool: :class:`NotImplemented`: if `other` fails to convert to a :class:`FrameSet` """...
python
def issuperset(self, other): """ Check if the contents of `self` is a superset of the contents of `other.` Args: other (:class:`FrameSet`): Returns: bool: :class:`NotImplemented`: if `other` fails to convert to a :class:`FrameSet` """...
[ "def", "issuperset", "(", "self", ",", "other", ")", ":", "other", "=", "self", ".", "_cast_to_frameset", "(", "other", ")", "if", "other", "is", "NotImplemented", ":", "return", "NotImplemented", "return", "self", ".", "items", ">=", "other", ".", "items"...
Check if the contents of `self` is a superset of the contents of `other.` Args: other (:class:`FrameSet`): Returns: bool: :class:`NotImplemented`: if `other` fails to convert to a :class:`FrameSet`
[ "Check", "if", "the", "contents", "of", "self", "is", "a", "superset", "of", "the", "contents", "of", "other", "." ]
f26c3c3c383134ce27d5dfe37793e1ebe88e69ad
https://github.com/sqlboy/fileseq/blob/f26c3c3c383134ce27d5dfe37793e1ebe88e69ad/src/fileseq/frameset.py#L835-L850
train
sqlboy/fileseq
src/fileseq/frameset.py
FrameSet._maxSizeCheck
def _maxSizeCheck(cls, obj): """ Raise a MaxSizeException if ``obj`` exceeds MAX_FRAME_SIZE Args: obj (numbers.Number or collection): Raises: :class:`fileseq.exceptions.MaxSizeException`: """ fail = False size = 0 if isinstance(o...
python
def _maxSizeCheck(cls, obj): """ Raise a MaxSizeException if ``obj`` exceeds MAX_FRAME_SIZE Args: obj (numbers.Number or collection): Raises: :class:`fileseq.exceptions.MaxSizeException`: """ fail = False size = 0 if isinstance(o...
[ "def", "_maxSizeCheck", "(", "cls", ",", "obj", ")", ":", "fail", "=", "False", "size", "=", "0", "if", "isinstance", "(", "obj", ",", "numbers", ".", "Number", ")", ":", "if", "obj", ">", "constants", ".", "MAX_FRAME_SIZE", ":", "fail", "=", "True",...
Raise a MaxSizeException if ``obj`` exceeds MAX_FRAME_SIZE Args: obj (numbers.Number or collection): Raises: :class:`fileseq.exceptions.MaxSizeException`:
[ "Raise", "a", "MaxSizeException", "if", "obj", "exceeds", "MAX_FRAME_SIZE" ]
f26c3c3c383134ce27d5dfe37793e1ebe88e69ad
https://github.com/sqlboy/fileseq/blob/f26c3c3c383134ce27d5dfe37793e1ebe88e69ad/src/fileseq/frameset.py#L921-L945
train
sqlboy/fileseq
src/fileseq/frameset.py
FrameSet.padFrameRange
def padFrameRange(frange, zfill): """ Return the zero-padded version of the frame range string. Args: frange (str): a frame range to test zfill (int): Returns: str: """ def _do_pad(match): """ Substitutes padde...
python
def padFrameRange(frange, zfill): """ Return the zero-padded version of the frame range string. Args: frange (str): a frame range to test zfill (int): Returns: str: """ def _do_pad(match): """ Substitutes padde...
[ "def", "padFrameRange", "(", "frange", ",", "zfill", ")", ":", "def", "_do_pad", "(", "match", ")", ":", "result", "=", "list", "(", "match", ".", "groups", "(", ")", ")", "result", "[", "1", "]", "=", "pad", "(", "result", "[", "1", "]", ",", ...
Return the zero-padded version of the frame range string. Args: frange (str): a frame range to test zfill (int): Returns: str:
[ "Return", "the", "zero", "-", "padded", "version", "of", "the", "frame", "range", "string", "." ]
f26c3c3c383134ce27d5dfe37793e1ebe88e69ad
https://github.com/sqlboy/fileseq/blob/f26c3c3c383134ce27d5dfe37793e1ebe88e69ad/src/fileseq/frameset.py#L974-L994
train
sqlboy/fileseq
src/fileseq/frameset.py
FrameSet.framesToFrameRanges
def framesToFrameRanges(frames, zfill=0): """ Converts a sequence of frames to a series of padded frame range strings. Args: frames (collections.Iterable): sequence of frames to process zfill (int): width for zero padding Yields: str: ...
python
def framesToFrameRanges(frames, zfill=0): """ Converts a sequence of frames to a series of padded frame range strings. Args: frames (collections.Iterable): sequence of frames to process zfill (int): width for zero padding Yields: str: ...
[ "def", "framesToFrameRanges", "(", "frames", ",", "zfill", "=", "0", ")", ":", "_build", "=", "FrameSet", ".", "_build_frange_part", "curr_start", "=", "None", "curr_stride", "=", "None", "curr_frame", "=", "None", "last_frame", "=", "None", "curr_count", "=",...
Converts a sequence of frames to a series of padded frame range strings. Args: frames (collections.Iterable): sequence of frames to process zfill (int): width for zero padding Yields: str:
[ "Converts", "a", "sequence", "of", "frames", "to", "a", "series", "of", "padded", "frame", "range", "strings", "." ]
f26c3c3c383134ce27d5dfe37793e1ebe88e69ad
https://github.com/sqlboy/fileseq/blob/f26c3c3c383134ce27d5dfe37793e1ebe88e69ad/src/fileseq/frameset.py#L1058-L1103
train
sqlboy/fileseq
src/fileseq/frameset.py
FrameSet.framesToFrameRange
def framesToFrameRange(frames, sort=True, zfill=0, compress=False): """ Converts an iterator of frames into a frame range string. Args: frames (collections.Iterable): sequence of frames to process sort (bool): sort the sequence before processing zfill...
python
def framesToFrameRange(frames, sort=True, zfill=0, compress=False): """ Converts an iterator of frames into a frame range string. Args: frames (collections.Iterable): sequence of frames to process sort (bool): sort the sequence before processing zfill...
[ "def", "framesToFrameRange", "(", "frames", ",", "sort", "=", "True", ",", "zfill", "=", "0", ",", "compress", "=", "False", ")", ":", "if", "compress", ":", "frames", "=", "unique", "(", "set", "(", ")", ",", "frames", ")", "frames", "=", "list", ...
Converts an iterator of frames into a frame range string. Args: frames (collections.Iterable): sequence of frames to process sort (bool): sort the sequence before processing zfill (int): width for zero padding compress (bool): remove any duplicates before...
[ "Converts", "an", "iterator", "of", "frames", "into", "a", "frame", "range", "string", "." ]
f26c3c3c383134ce27d5dfe37793e1ebe88e69ad
https://github.com/sqlboy/fileseq/blob/f26c3c3c383134ce27d5dfe37793e1ebe88e69ad/src/fileseq/frameset.py#L1106-L1129
train
litl/rauth
rauth/session.py
OAuth1Session._parse_optional_params
def _parse_optional_params(self, oauth_params, req_kwargs): ''' Parses and sets optional OAuth parameters on a request. :param oauth_param: The OAuth parameter to parse. :type oauth_param: str :param req_kwargs: The keyworded arguments passed to the request method. ...
python
def _parse_optional_params(self, oauth_params, req_kwargs): ''' Parses and sets optional OAuth parameters on a request. :param oauth_param: The OAuth parameter to parse. :type oauth_param: str :param req_kwargs: The keyworded arguments passed to the request method. ...
[ "def", "_parse_optional_params", "(", "self", ",", "oauth_params", ",", "req_kwargs", ")", ":", "params", "=", "req_kwargs", ".", "get", "(", "'params'", ",", "{", "}", ")", "data", "=", "req_kwargs", ".", "get", "(", "'data'", ")", "or", "{", "}", "fo...
Parses and sets optional OAuth parameters on a request. :param oauth_param: The OAuth parameter to parse. :type oauth_param: str :param req_kwargs: The keyworded arguments passed to the request method. :type req_kwargs: dict
[ "Parses", "and", "sets", "optional", "OAuth", "parameters", "on", "a", "request", "." ]
a6d887d7737cf21ec896a8104f25c2754c694011
https://github.com/litl/rauth/blob/a6d887d7737cf21ec896a8104f25c2754c694011/rauth/session.py#L212-L235
train
litl/rauth
rauth/session.py
OAuth1Session._get_oauth_params
def _get_oauth_params(self, req_kwargs): '''Prepares OAuth params for signing.''' oauth_params = {} oauth_params['oauth_consumer_key'] = self.consumer_key oauth_params['oauth_nonce'] = sha1( str(random()).encode('ascii')).hexdigest() oauth_params['oauth_signature_met...
python
def _get_oauth_params(self, req_kwargs): '''Prepares OAuth params for signing.''' oauth_params = {} oauth_params['oauth_consumer_key'] = self.consumer_key oauth_params['oauth_nonce'] = sha1( str(random()).encode('ascii')).hexdigest() oauth_params['oauth_signature_met...
[ "def", "_get_oauth_params", "(", "self", ",", "req_kwargs", ")", ":", "oauth_params", "=", "{", "}", "oauth_params", "[", "'oauth_consumer_key'", "]", "=", "self", ".", "consumer_key", "oauth_params", "[", "'oauth_nonce'", "]", "=", "sha1", "(", "str", "(", ...
Prepares OAuth params for signing.
[ "Prepares", "OAuth", "params", "for", "signing", "." ]
a6d887d7737cf21ec896a8104f25c2754c694011
https://github.com/litl/rauth/blob/a6d887d7737cf21ec896a8104f25c2754c694011/rauth/session.py#L237-L254
train
litl/rauth
rauth/session.py
OflySession.sign
def sign(url, app_id, app_secret, hash_meth='sha1', **params): ''' A signature method which generates the necessary Ofly parameters. :param app_id: The oFlyAppId, i.e. "application ID". :type app_id: str :param app_secret: The oFlyAppSecret, i.e. "shared secret". :type a...
python
def sign(url, app_id, app_secret, hash_meth='sha1', **params): ''' A signature method which generates the necessary Ofly parameters. :param app_id: The oFlyAppId, i.e. "application ID". :type app_id: str :param app_secret: The oFlyAppSecret, i.e. "shared secret". :type a...
[ "def", "sign", "(", "url", ",", "app_id", ",", "app_secret", ",", "hash_meth", "=", "'sha1'", ",", "**", "params", ")", ":", "hash_meth_str", "=", "hash_meth", "if", "hash_meth", "==", "'sha1'", ":", "hash_meth", "=", "sha1", "elif", "hash_meth", "==", "...
A signature method which generates the necessary Ofly parameters. :param app_id: The oFlyAppId, i.e. "application ID". :type app_id: str :param app_secret: The oFlyAppSecret, i.e. "shared secret". :type app_secret: str :param hash_meth: The hash method to use for signing, defaul...
[ "A", "signature", "method", "which", "generates", "the", "necessary", "Ofly", "parameters", "." ]
a6d887d7737cf21ec896a8104f25c2754c694011
https://github.com/litl/rauth/blob/a6d887d7737cf21ec896a8104f25c2754c694011/rauth/session.py#L470-L515
train
litl/rauth
rauth/utils.py
OAuth1Auth._get_auth_header
def _get_auth_header(self): ''' Constructs and returns an authentication header. ''' realm = 'realm="{realm}"'.format(realm=self.realm) params = ['{k}="{v}"'.format(k=k, v=quote(str(v), safe='')) for k, v in self.oauth_params.items()] return 'OAuth ' + ','.join([realm] ...
python
def _get_auth_header(self): ''' Constructs and returns an authentication header. ''' realm = 'realm="{realm}"'.format(realm=self.realm) params = ['{k}="{v}"'.format(k=k, v=quote(str(v), safe='')) for k, v in self.oauth_params.items()] return 'OAuth ' + ','.join([realm] ...
[ "def", "_get_auth_header", "(", "self", ")", ":", "realm", "=", "'realm=\"{realm}\"'", ".", "format", "(", "realm", "=", "self", ".", "realm", ")", "params", "=", "[", "'{k}=\"{v}\"'", ".", "format", "(", "k", "=", "k", ",", "v", "=", "quote", "(", "...
Constructs and returns an authentication header.
[ "Constructs", "and", "returns", "an", "authentication", "header", "." ]
a6d887d7737cf21ec896a8104f25c2754c694011
https://github.com/litl/rauth/blob/a6d887d7737cf21ec896a8104f25c2754c694011/rauth/utils.py#L93-L98
train
litl/rauth
rauth/oauth.py
SignatureMethod._remove_qs
def _remove_qs(self, url): ''' Removes a query string from a URL before signing. :param url: The URL to strip. :type url: str ''' scheme, netloc, path, query, fragment = urlsplit(url) return urlunsplit((scheme, netloc, path, '', fragment))
python
def _remove_qs(self, url): ''' Removes a query string from a URL before signing. :param url: The URL to strip. :type url: str ''' scheme, netloc, path, query, fragment = urlsplit(url) return urlunsplit((scheme, netloc, path, '', fragment))
[ "def", "_remove_qs", "(", "self", ",", "url", ")", ":", "scheme", ",", "netloc", ",", "path", ",", "query", ",", "fragment", "=", "urlsplit", "(", "url", ")", "return", "urlunsplit", "(", "(", "scheme", ",", "netloc", ",", "path", ",", "''", ",", "...
Removes a query string from a URL before signing. :param url: The URL to strip. :type url: str
[ "Removes", "a", "query", "string", "from", "a", "URL", "before", "signing", "." ]
a6d887d7737cf21ec896a8104f25c2754c694011
https://github.com/litl/rauth/blob/a6d887d7737cf21ec896a8104f25c2754c694011/rauth/oauth.py#L37-L46
train
litl/rauth
rauth/oauth.py
SignatureMethod._normalize_request_parameters
def _normalize_request_parameters(self, oauth_params, req_kwargs): ''' This process normalizes the request parameters as detailed in the OAuth 1.0 spec. Additionally we apply a `Content-Type` header to the request of the `FORM_URLENCODE` type if the `Content-Type` was previously...
python
def _normalize_request_parameters(self, oauth_params, req_kwargs): ''' This process normalizes the request parameters as detailed in the OAuth 1.0 spec. Additionally we apply a `Content-Type` header to the request of the `FORM_URLENCODE` type if the `Content-Type` was previously...
[ "def", "_normalize_request_parameters", "(", "self", ",", "oauth_params", ",", "req_kwargs", ")", ":", "normalized", "=", "[", "]", "params", "=", "req_kwargs", ".", "get", "(", "'params'", ",", "{", "}", ")", "data", "=", "req_kwargs", ".", "get", "(", ...
This process normalizes the request parameters as detailed in the OAuth 1.0 spec. Additionally we apply a `Content-Type` header to the request of the `FORM_URLENCODE` type if the `Content-Type` was previously set, i.e. if this is a `POST` or `PUT` request. This ensures the correct heade...
[ "This", "process", "normalizes", "the", "request", "parameters", "as", "detailed", "in", "the", "OAuth", "1", ".", "0", "spec", "." ]
a6d887d7737cf21ec896a8104f25c2754c694011
https://github.com/litl/rauth/blob/a6d887d7737cf21ec896a8104f25c2754c694011/rauth/oauth.py#L48-L103
train
litl/rauth
rauth/oauth.py
PlaintextSignature.sign
def sign(self, consumer_secret, access_token_secret, method, url, oauth_params, req_kwargs): '''Sign request using PLAINTEXT method. :param consumer_secret: Consumer secret. :type consumer_secret: str :param access_token_secret: Access token secret (optional). :type...
python
def sign(self, consumer_secret, access_token_secret, method, url, oauth_params, req_kwargs): '''Sign request using PLAINTEXT method. :param consumer_secret: Consumer secret. :type consumer_secret: str :param access_token_secret: Access token secret (optional). :type...
[ "def", "sign", "(", "self", ",", "consumer_secret", ",", "access_token_secret", ",", "method", ",", "url", ",", "oauth_params", ",", "req_kwargs", ")", ":", "key", "=", "self", ".", "_escape", "(", "consumer_secret", ")", "+", "b'&'", "if", "access_token_sec...
Sign request using PLAINTEXT method. :param consumer_secret: Consumer secret. :type consumer_secret: str :param access_token_secret: Access token secret (optional). :type access_token_secret: str :param method: Unused :type method: str :param url: Unused ...
[ "Sign", "request", "using", "PLAINTEXT", "method", "." ]
a6d887d7737cf21ec896a8104f25c2754c694011
https://github.com/litl/rauth/blob/a6d887d7737cf21ec896a8104f25c2754c694011/rauth/oauth.py#L228-L248
train
litl/rauth
rauth/service.py
OAuth1Service.get_request_token
def get_request_token(self, method='GET', decoder=parse_utf8_qsl, key_token='oauth_token', key_token_secret='oauth_token_secret', **kwargs): ''' Return a request token pair. ...
python
def get_request_token(self, method='GET', decoder=parse_utf8_qsl, key_token='oauth_token', key_token_secret='oauth_token_secret', **kwargs): ''' Return a request token pair. ...
[ "def", "get_request_token", "(", "self", ",", "method", "=", "'GET'", ",", "decoder", "=", "parse_utf8_qsl", ",", "key_token", "=", "'oauth_token'", ",", "key_token_secret", "=", "'oauth_token_secret'", ",", "**", "kwargs", ")", ":", "r", "=", "self", ".", "...
Return a request token pair. :param method: A string representation of the HTTP method to be used, defaults to `GET`. :type method: str :param decoder: A function used to parse the Response content. Should return a dictionary. :type decoder: func :param k...
[ "Return", "a", "request", "token", "pair", "." ]
a6d887d7737cf21ec896a8104f25c2754c694011
https://github.com/litl/rauth/blob/a6d887d7737cf21ec896a8104f25c2754c694011/rauth/service.py#L218-L245
train
litl/rauth
rauth/service.py
OAuth1Service.get_access_token
def get_access_token(self, request_token, request_token_secret, method='GET', decoder=parse_utf8_qsl, key_token='oauth_token', key_token_secret='oauth_token_secret', ...
python
def get_access_token(self, request_token, request_token_secret, method='GET', decoder=parse_utf8_qsl, key_token='oauth_token', key_token_secret='oauth_token_secret', ...
[ "def", "get_access_token", "(", "self", ",", "request_token", ",", "request_token_secret", ",", "method", "=", "'GET'", ",", "decoder", "=", "parse_utf8_qsl", ",", "key_token", "=", "'oauth_token'", ",", "key_token_secret", "=", "'oauth_token_secret'", ",", "**", ...
Returns an access token pair. :param request_token: The request token as returned by :meth:`get_request_token`. :type request_token: str :param request_token_secret: The request token secret as returned by :meth:`get_request_token`. :type request_token_secret: st...
[ "Returns", "an", "access", "token", "pair", "." ]
a6d887d7737cf21ec896a8104f25c2754c694011
https://github.com/litl/rauth/blob/a6d887d7737cf21ec896a8104f25c2754c694011/rauth/service.py#L294-L333
train
litl/rauth
rauth/service.py
OAuth2Service.get_access_token
def get_access_token(self, method='POST', decoder=parse_utf8_qsl, key='access_token', **kwargs): ''' Returns an access token. :param method: A string representation of the HTTP method to be used,...
python
def get_access_token(self, method='POST', decoder=parse_utf8_qsl, key='access_token', **kwargs): ''' Returns an access token. :param method: A string representation of the HTTP method to be used,...
[ "def", "get_access_token", "(", "self", ",", "method", "=", "'POST'", ",", "decoder", "=", "parse_utf8_qsl", ",", "key", "=", "'access_token'", ",", "**", "kwargs", ")", ":", "r", "=", "self", ".", "get_raw_access_token", "(", "method", ",", "**", "kwargs"...
Returns an access token. :param method: A string representation of the HTTP method to be used, defaults to `POST`. :type method: str :param decoder: A function used to parse the Response content. Should return a dictionary. :type decoder: func :param key:...
[ "Returns", "an", "access", "token", "." ]
a6d887d7737cf21ec896a8104f25c2754c694011
https://github.com/litl/rauth/blob/a6d887d7737cf21ec896a8104f25c2754c694011/rauth/service.py#L521-L543
train
rochacbruno/flask_simplelogin
flask_simplelogin/__init__.py
is_logged_in
def is_logged_in(username=None): """Checks if user is logged in if `username` is passed check if specified user is logged in username can be a list""" if username: if not isinstance(username, (list, tuple)): username = [username] return 'simple_logged_in' in session and get_u...
python
def is_logged_in(username=None): """Checks if user is logged in if `username` is passed check if specified user is logged in username can be a list""" if username: if not isinstance(username, (list, tuple)): username = [username] return 'simple_logged_in' in session and get_u...
[ "def", "is_logged_in", "(", "username", "=", "None", ")", ":", "if", "username", ":", "if", "not", "isinstance", "(", "username", ",", "(", "list", ",", "tuple", ")", ")", ":", "username", "=", "[", "username", "]", "return", "'simple_logged_in'", "in", ...
Checks if user is logged in if `username` is passed check if specified user is logged in username can be a list
[ "Checks", "if", "user", "is", "logged", "in", "if", "username", "is", "passed", "check", "if", "specified", "user", "is", "logged", "in", "username", "can", "be", "a", "list" ]
5b319977053649352daa87a6b0632949eee0643c
https://github.com/rochacbruno/flask_simplelogin/blob/5b319977053649352daa87a6b0632949eee0643c/flask_simplelogin/__init__.py#L49-L57
train
rochacbruno/flask_simplelogin
flask_simplelogin/__init__.py
login_required
def login_required(function=None, username=None, basic=False, must=None): """Decorate views to require login @login_required @login_required() @login_required(username='admin') @login_required(username=['admin', 'jon']) @login_required(basic=True) @login_required(must=[function, another_func...
python
def login_required(function=None, username=None, basic=False, must=None): """Decorate views to require login @login_required @login_required() @login_required(username='admin') @login_required(username=['admin', 'jon']) @login_required(basic=True) @login_required(must=[function, another_func...
[ "def", "login_required", "(", "function", "=", "None", ",", "username", "=", "None", ",", "basic", "=", "False", ",", "must", "=", "None", ")", ":", "if", "function", "and", "not", "callable", "(", "function", ")", ":", "raise", "ValueError", "(", "'De...
Decorate views to require login @login_required @login_required() @login_required(username='admin') @login_required(username=['admin', 'jon']) @login_required(basic=True) @login_required(must=[function, another_function])
[ "Decorate", "views", "to", "require", "login" ]
5b319977053649352daa87a6b0632949eee0643c
https://github.com/rochacbruno/flask_simplelogin/blob/5b319977053649352daa87a6b0632949eee0643c/flask_simplelogin/__init__.py#L65-L125
train
rochacbruno/flask_simplelogin
flask_simplelogin/__init__.py
SimpleLogin.get_message
def get_message(message, *args, **kwargs): """Helper to get internal messages outside this instance""" msg = current_app.extensions['simplelogin'].messages.get(message) if msg and (args or kwargs): return msg.format(*args, **kwargs) return msg
python
def get_message(message, *args, **kwargs): """Helper to get internal messages outside this instance""" msg = current_app.extensions['simplelogin'].messages.get(message) if msg and (args or kwargs): return msg.format(*args, **kwargs) return msg
[ "def", "get_message", "(", "message", ",", "*", "args", ",", "**", "kwargs", ")", ":", "msg", "=", "current_app", ".", "extensions", "[", "'simplelogin'", "]", ".", "messages", ".", "get", "(", "message", ")", "if", "msg", "and", "(", "args", "or", "...
Helper to get internal messages outside this instance
[ "Helper", "to", "get", "internal", "messages", "outside", "this", "instance" ]
5b319977053649352daa87a6b0632949eee0643c
https://github.com/rochacbruno/flask_simplelogin/blob/5b319977053649352daa87a6b0632949eee0643c/flask_simplelogin/__init__.py#L142-L147
train
rochacbruno/flask_simplelogin
example/simple_app.py
check_my_users
def check_my_users(user): """Check if user exists and its credentials. Take a look at encrypt_app.py and encrypt_cli.py to see how to encrypt passwords """ user_data = my_users.get(user['username']) if not user_data: return False # <--- invalid credentials elif user_data.get('passw...
python
def check_my_users(user): """Check if user exists and its credentials. Take a look at encrypt_app.py and encrypt_cli.py to see how to encrypt passwords """ user_data = my_users.get(user['username']) if not user_data: return False # <--- invalid credentials elif user_data.get('passw...
[ "def", "check_my_users", "(", "user", ")", ":", "user_data", "=", "my_users", ".", "get", "(", "user", "[", "'username'", "]", ")", "if", "not", "user_data", ":", "return", "False", "elif", "user_data", ".", "get", "(", "'password'", ")", "==", "user", ...
Check if user exists and its credentials. Take a look at encrypt_app.py and encrypt_cli.py to see how to encrypt passwords
[ "Check", "if", "user", "exists", "and", "its", "credentials", ".", "Take", "a", "look", "at", "encrypt_app", ".", "py", "and", "encrypt_cli", ".", "py", "to", "see", "how", "to", "encrypt", "passwords" ]
5b319977053649352daa87a6b0632949eee0643c
https://github.com/rochacbruno/flask_simplelogin/blob/5b319977053649352daa87a6b0632949eee0643c/example/simple_app.py#L13-L24
train
rochacbruno/flask_simplelogin
example/manage.py
create_user
def create_user(**data): """Creates user with encrypted password""" if 'username' not in data or 'password' not in data: raise ValueError('username and password are required.') # Hash the user password data['password'] = generate_password_hash( data.pop('password'), method='pbkd...
python
def create_user(**data): """Creates user with encrypted password""" if 'username' not in data or 'password' not in data: raise ValueError('username and password are required.') # Hash the user password data['password'] = generate_password_hash( data.pop('password'), method='pbkd...
[ "def", "create_user", "(", "**", "data", ")", ":", "if", "'username'", "not", "in", "data", "or", "'password'", "not", "in", "data", ":", "raise", "ValueError", "(", "'username and password are required.'", ")", "data", "[", "'password'", "]", "=", "generate_p...
Creates user with encrypted password
[ "Creates", "user", "with", "encrypted", "password" ]
5b319977053649352daa87a6b0632949eee0643c
https://github.com/rochacbruno/flask_simplelogin/blob/5b319977053649352daa87a6b0632949eee0643c/example/manage.py#L23-L41
train
rochacbruno/flask_simplelogin
example/manage.py
with_app
def with_app(f): """Calls function passing app as first argument""" @wraps(f) def decorator(*args, **kwargs): app = create_app() configure_extensions(app) configure_views(app) return f(app=app, *args, **kwargs) return decorator
python
def with_app(f): """Calls function passing app as first argument""" @wraps(f) def decorator(*args, **kwargs): app = create_app() configure_extensions(app) configure_views(app) return f(app=app, *args, **kwargs) return decorator
[ "def", "with_app", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "decorator", "(", "*", "args", ",", "**", "kwargs", ")", ":", "app", "=", "create_app", "(", ")", "configure_extensions", "(", "app", ")", "configure_views", "(", "app", ")", ...
Calls function passing app as first argument
[ "Calls", "function", "passing", "app", "as", "first", "argument" ]
5b319977053649352daa87a6b0632949eee0643c
https://github.com/rochacbruno/flask_simplelogin/blob/5b319977053649352daa87a6b0632949eee0643c/example/manage.py#L83-L91
train
rochacbruno/flask_simplelogin
example/manage.py
adduser
def adduser(app, username, password): """Add new user with admin access""" with app.app_context(): create_user(username=username, password=password) click.echo('user created!')
python
def adduser(app, username, password): """Add new user with admin access""" with app.app_context(): create_user(username=username, password=password) click.echo('user created!')
[ "def", "adduser", "(", "app", ",", "username", ",", "password", ")", ":", "with", "app", ".", "app_context", "(", ")", ":", "create_user", "(", "username", "=", "username", ",", "password", "=", "password", ")", "click", ".", "echo", "(", "'user created!...
Add new user with admin access
[ "Add", "new", "user", "with", "admin", "access" ]
5b319977053649352daa87a6b0632949eee0643c
https://github.com/rochacbruno/flask_simplelogin/blob/5b319977053649352daa87a6b0632949eee0643c/example/manage.py#L104-L108
train
dbrgn/RPLCD
RPLCD/i2c.py
CharLCD._pulse_data
def _pulse_data(self, value): """Pulse the `enable` flag to process value.""" if self._i2c_expander == 'PCF8574': self.bus.write_byte(self._address, ((value & ~PCF8574_E) | self._backlight)) c.usleep(1) self.bus.write_byte(self._address, value | PCF8574_E | self._back...
python
def _pulse_data(self, value): """Pulse the `enable` flag to process value.""" if self._i2c_expander == 'PCF8574': self.bus.write_byte(self._address, ((value & ~PCF8574_E) | self._backlight)) c.usleep(1) self.bus.write_byte(self._address, value | PCF8574_E | self._back...
[ "def", "_pulse_data", "(", "self", ",", "value", ")", ":", "if", "self", ".", "_i2c_expander", "==", "'PCF8574'", ":", "self", ".", "bus", ".", "write_byte", "(", "self", ".", "_address", ",", "(", "(", "value", "&", "~", "PCF8574_E", ")", "|", "self...
Pulse the `enable` flag to process value.
[ "Pulse", "the", "enable", "flag", "to", "process", "value", "." ]
95fe5da1354d466d661cdc84e1637ce557700c8c
https://github.com/dbrgn/RPLCD/blob/95fe5da1354d466d661cdc84e1637ce557700c8c/RPLCD/i2c.py#L251-L271
train
dbrgn/RPLCD
RPLCD/gpio.py
CharLCD._write4bits
def _write4bits(self, value): """Write 4 bits of data into the data bus.""" for i in range(4): bit = (value >> i) & 0x01 GPIO.output(self.pins[i + 7], bit) self._pulse_enable()
python
def _write4bits(self, value): """Write 4 bits of data into the data bus.""" for i in range(4): bit = (value >> i) & 0x01 GPIO.output(self.pins[i + 7], bit) self._pulse_enable()
[ "def", "_write4bits", "(", "self", ",", "value", ")", ":", "for", "i", "in", "range", "(", "4", ")", ":", "bit", "=", "(", "value", ">>", "i", ")", "&", "0x01", "GPIO", ".", "output", "(", "self", ".", "pins", "[", "i", "+", "7", "]", ",", ...
Write 4 bits of data into the data bus.
[ "Write", "4", "bits", "of", "data", "into", "the", "data", "bus", "." ]
95fe5da1354d466d661cdc84e1637ce557700c8c
https://github.com/dbrgn/RPLCD/blob/95fe5da1354d466d661cdc84e1637ce557700c8c/RPLCD/gpio.py#L223-L228
train
dbrgn/RPLCD
RPLCD/gpio.py
CharLCD._pulse_enable
def _pulse_enable(self): """Pulse the `enable` flag to process data.""" GPIO.output(self.pins.e, 0) c.usleep(1) GPIO.output(self.pins.e, 1) c.usleep(1) GPIO.output(self.pins.e, 0) c.usleep(100)
python
def _pulse_enable(self): """Pulse the `enable` flag to process data.""" GPIO.output(self.pins.e, 0) c.usleep(1) GPIO.output(self.pins.e, 1) c.usleep(1) GPIO.output(self.pins.e, 0) c.usleep(100)
[ "def", "_pulse_enable", "(", "self", ")", ":", "GPIO", ".", "output", "(", "self", ".", "pins", ".", "e", ",", "0", ")", "c", ".", "usleep", "(", "1", ")", "GPIO", ".", "output", "(", "self", ".", "pins", ".", "e", ",", "1", ")", "c", ".", ...
Pulse the `enable` flag to process data.
[ "Pulse", "the", "enable", "flag", "to", "process", "data", "." ]
95fe5da1354d466d661cdc84e1637ce557700c8c
https://github.com/dbrgn/RPLCD/blob/95fe5da1354d466d661cdc84e1637ce557700c8c/RPLCD/gpio.py#L237-L244
train
dbrgn/RPLCD
RPLCD/lcd.py
BaseCharLCD.write_string
def write_string(self, value): """ Write the specified unicode string to the display. To control multiline behavior, use newline (``\\n``) and carriage return (``\\r``) characters. Lines that are too long automatically continue on next line, as long as ``auto_linebreaks...
python
def write_string(self, value): """ Write the specified unicode string to the display. To control multiline behavior, use newline (``\\n``) and carriage return (``\\r``) characters. Lines that are too long automatically continue on next line, as long as ``auto_linebreaks...
[ "def", "write_string", "(", "self", ",", "value", ")", ":", "encoded", "=", "self", ".", "codec", ".", "encode", "(", "value", ")", "ignored", "=", "False", "for", "[", "char", ",", "lookahead", "]", "in", "c", ".", "sliding_window", "(", "encoded", ...
Write the specified unicode string to the display. To control multiline behavior, use newline (``\\n``) and carriage return (``\\r``) characters. Lines that are too long automatically continue on next line, as long as ``auto_linebreaks`` has not been disabled. Make sure that y...
[ "Write", "the", "specified", "unicode", "string", "to", "the", "display", "." ]
95fe5da1354d466d661cdc84e1637ce557700c8c
https://github.com/dbrgn/RPLCD/blob/95fe5da1354d466d661cdc84e1637ce557700c8c/RPLCD/lcd.py#L244-L307
train
dbrgn/RPLCD
RPLCD/lcd.py
BaseCharLCD.clear
def clear(self): """Overwrite display with blank characters and reset cursor position.""" self.command(c.LCD_CLEARDISPLAY) self._cursor_pos = (0, 0) self._content = [[0x20] * self.lcd.cols for _ in range(self.lcd.rows)] c.msleep(2)
python
def clear(self): """Overwrite display with blank characters and reset cursor position.""" self.command(c.LCD_CLEARDISPLAY) self._cursor_pos = (0, 0) self._content = [[0x20] * self.lcd.cols for _ in range(self.lcd.rows)] c.msleep(2)
[ "def", "clear", "(", "self", ")", ":", "self", ".", "command", "(", "c", ".", "LCD_CLEARDISPLAY", ")", "self", ".", "_cursor_pos", "=", "(", "0", ",", "0", ")", "self", ".", "_content", "=", "[", "[", "0x20", "]", "*", "self", ".", "lcd", ".", ...
Overwrite display with blank characters and reset cursor position.
[ "Overwrite", "display", "with", "blank", "characters", "and", "reset", "cursor", "position", "." ]
95fe5da1354d466d661cdc84e1637ce557700c8c
https://github.com/dbrgn/RPLCD/blob/95fe5da1354d466d661cdc84e1637ce557700c8c/RPLCD/lcd.py#L309-L314
train
dbrgn/RPLCD
RPLCD/lcd.py
BaseCharLCD.home
def home(self): """Set cursor to initial position and reset any shifting.""" self.command(c.LCD_RETURNHOME) self._cursor_pos = (0, 0) c.msleep(2)
python
def home(self): """Set cursor to initial position and reset any shifting.""" self.command(c.LCD_RETURNHOME) self._cursor_pos = (0, 0) c.msleep(2)
[ "def", "home", "(", "self", ")", ":", "self", ".", "command", "(", "c", ".", "LCD_RETURNHOME", ")", "self", ".", "_cursor_pos", "=", "(", "0", ",", "0", ")", "c", ".", "msleep", "(", "2", ")" ]
Set cursor to initial position and reset any shifting.
[ "Set", "cursor", "to", "initial", "position", "and", "reset", "any", "shifting", "." ]
95fe5da1354d466d661cdc84e1637ce557700c8c
https://github.com/dbrgn/RPLCD/blob/95fe5da1354d466d661cdc84e1637ce557700c8c/RPLCD/lcd.py#L316-L320
train
dbrgn/RPLCD
RPLCD/lcd.py
BaseCharLCD.shift_display
def shift_display(self, amount): """Shift the display. Use negative amounts to shift left and positive amounts to shift right.""" if amount == 0: return direction = c.LCD_MOVERIGHT if amount > 0 else c.LCD_MOVELEFT for i in range(abs(amount)): self.command...
python
def shift_display(self, amount): """Shift the display. Use negative amounts to shift left and positive amounts to shift right.""" if amount == 0: return direction = c.LCD_MOVERIGHT if amount > 0 else c.LCD_MOVELEFT for i in range(abs(amount)): self.command...
[ "def", "shift_display", "(", "self", ",", "amount", ")", ":", "if", "amount", "==", "0", ":", "return", "direction", "=", "c", ".", "LCD_MOVERIGHT", "if", "amount", ">", "0", "else", "c", ".", "LCD_MOVELEFT", "for", "i", "in", "range", "(", "abs", "(...
Shift the display. Use negative amounts to shift left and positive amounts to shift right.
[ "Shift", "the", "display", ".", "Use", "negative", "amounts", "to", "shift", "left", "and", "positive", "amounts", "to", "shift", "right", "." ]
95fe5da1354d466d661cdc84e1637ce557700c8c
https://github.com/dbrgn/RPLCD/blob/95fe5da1354d466d661cdc84e1637ce557700c8c/RPLCD/lcd.py#L322-L330
train
dbrgn/RPLCD
RPLCD/lcd.py
BaseCharLCD.write
def write(self, value): # type: (int) -> None """Write a raw byte to the LCD.""" # Get current position row, col = self._cursor_pos # Write byte if changed try: if self._content[row][col] != value: self._send_data(value) self._conten...
python
def write(self, value): # type: (int) -> None """Write a raw byte to the LCD.""" # Get current position row, col = self._cursor_pos # Write byte if changed try: if self._content[row][col] != value: self._send_data(value) self._conten...
[ "def", "write", "(", "self", ",", "value", ")", ":", "row", ",", "col", "=", "self", ".", "_cursor_pos", "try", ":", "if", "self", ".", "_content", "[", "row", "]", "[", "col", "]", "!=", "value", ":", "self", ".", "_send_data", "(", "value", ")"...
Write a raw byte to the LCD.
[ "Write", "a", "raw", "byte", "to", "the", "LCD", "." ]
95fe5da1354d466d661cdc84e1637ce557700c8c
https://github.com/dbrgn/RPLCD/blob/95fe5da1354d466d661cdc84e1637ce557700c8c/RPLCD/lcd.py#L383-L436
train
dbrgn/RPLCD
RPLCD/contextmanagers.py
cursor
def cursor(lcd, row, col): """ Context manager to control cursor position. DEPRECATED. """ warnings.warn('The `cursor` context manager is deprecated', DeprecationWarning) lcd.cursor_pos = (row, col) yield
python
def cursor(lcd, row, col): """ Context manager to control cursor position. DEPRECATED. """ warnings.warn('The `cursor` context manager is deprecated', DeprecationWarning) lcd.cursor_pos = (row, col) yield
[ "def", "cursor", "(", "lcd", ",", "row", ",", "col", ")", ":", "warnings", ".", "warn", "(", "'The `cursor` context manager is deprecated'", ",", "DeprecationWarning", ")", "lcd", ".", "cursor_pos", "=", "(", "row", ",", "col", ")", "yield" ]
Context manager to control cursor position. DEPRECATED.
[ "Context", "manager", "to", "control", "cursor", "position", ".", "DEPRECATED", "." ]
95fe5da1354d466d661cdc84e1637ce557700c8c
https://github.com/dbrgn/RPLCD/blob/95fe5da1354d466d661cdc84e1637ce557700c8c/RPLCD/contextmanagers.py#L9-L15
train
dbrgn/RPLCD
RPLCD/common.py
sliding_window
def sliding_window(seq, lookahead): """ Create a sliding window with the specified number of lookahead characters. """ it = itertools.chain(iter(seq), ' ' * lookahead) # Padded iterator window_size = lookahead + 1 result = tuple(itertools.islice(it, window_size)) if len(result) == window_si...
python
def sliding_window(seq, lookahead): """ Create a sliding window with the specified number of lookahead characters. """ it = itertools.chain(iter(seq), ' ' * lookahead) # Padded iterator window_size = lookahead + 1 result = tuple(itertools.islice(it, window_size)) if len(result) == window_si...
[ "def", "sliding_window", "(", "seq", ",", "lookahead", ")", ":", "it", "=", "itertools", ".", "chain", "(", "iter", "(", "seq", ")", ",", "' '", "*", "lookahead", ")", "window_size", "=", "lookahead", "+", "1", "result", "=", "tuple", "(", "itertools",...
Create a sliding window with the specified number of lookahead characters.
[ "Create", "a", "sliding", "window", "with", "the", "specified", "number", "of", "lookahead", "characters", "." ]
95fe5da1354d466d661cdc84e1637ce557700c8c
https://github.com/dbrgn/RPLCD/blob/95fe5da1354d466d661cdc84e1637ce557700c8c/RPLCD/common.py#L108-L119
train
rgs1/zk_shell
zk_shell/cli.py
get_params
def get_params(): """ get the cmdline params """ parser = argparse.ArgumentParser() parser.add_argument("--connect-timeout", type=float, default=10.0, help="ZK connect timeout") parser.add_argument("--run-once", ...
python
def get_params(): """ get the cmdline params """ parser = argparse.ArgumentParser() parser.add_argument("--connect-timeout", type=float, default=10.0, help="ZK connect timeout") parser.add_argument("--run-once", ...
[ "def", "get_params", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "parser", ".", "add_argument", "(", "\"--connect-timeout\"", ",", "type", "=", "float", ",", "default", "=", "10.0", ",", "help", "=", "\"ZK connect timeout\"", "...
get the cmdline params
[ "get", "the", "cmdline", "params" ]
bbf34fdfcf1f81100e2a5816fad8af6afc782a54
https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/cli.py#L39-L83
train
rgs1/zk_shell
zk_shell/cli.py
set_unbuffered_mode
def set_unbuffered_mode(): """ make output unbuffered """ class Unbuffered(object): def __init__(self, stream): self.stream = stream def write(self, data): self.stream.write(data) self.stream.flush() def __getattr__(self, attr): ret...
python
def set_unbuffered_mode(): """ make output unbuffered """ class Unbuffered(object): def __init__(self, stream): self.stream = stream def write(self, data): self.stream.write(data) self.stream.flush() def __getattr__(self, attr): ret...
[ "def", "set_unbuffered_mode", "(", ")", ":", "class", "Unbuffered", "(", "object", ")", ":", "def", "__init__", "(", "self", ",", "stream", ")", ":", "self", ".", "stream", "=", "stream", "def", "write", "(", "self", ",", "data", ")", ":", "self", "....
make output unbuffered
[ "make", "output", "unbuffered" ]
bbf34fdfcf1f81100e2a5816fad8af6afc782a54
https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/cli.py#L97-L110
train
rgs1/zk_shell
zk_shell/acl.py
ACLReader.to_dict
def to_dict(cls, acl): """ transform an ACL to a dict """ return { "perms": acl.perms, "id": { "scheme": acl.id.scheme, "id": acl.id.id } }
python
def to_dict(cls, acl): """ transform an ACL to a dict """ return { "perms": acl.perms, "id": { "scheme": acl.id.scheme, "id": acl.id.id } }
[ "def", "to_dict", "(", "cls", ",", "acl", ")", ":", "return", "{", "\"perms\"", ":", "acl", ".", "perms", ",", "\"id\"", ":", "{", "\"scheme\"", ":", "acl", ".", "id", ".", "scheme", ",", "\"id\"", ":", "acl", ".", "id", ".", "id", "}", "}" ]
transform an ACL to a dict
[ "transform", "an", "ACL", "to", "a", "dict" ]
bbf34fdfcf1f81100e2a5816fad8af6afc782a54
https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/acl.py#L74-L82
train