repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
vsoch/helpme
helpme/utils/memory.py
get_pid
def get_pid(pid=None): '''get_pid will return a pid of interest. First we use given variable, then environmental variable PID, and then PID of running process ''' if pid == None: if os.environ.get("PID",None) != None: pid = int(os.environ.get("PID")) # Then use current runnin...
python
def get_pid(pid=None): '''get_pid will return a pid of interest. First we use given variable, then environmental variable PID, and then PID of running process ''' if pid == None: if os.environ.get("PID",None) != None: pid = int(os.environ.get("PID")) # Then use current runnin...
[ "def", "get_pid", "(", "pid", "=", "None", ")", ":", "if", "pid", "==", "None", ":", "if", "os", ".", "environ", ".", "get", "(", "\"PID\"", ",", "None", ")", "!=", "None", ":", "pid", "=", "int", "(", "os", ".", "environ", ".", "get", "(", "...
get_pid will return a pid of interest. First we use given variable, then environmental variable PID, and then PID of running process
[ "get_pid", "will", "return", "a", "pid", "of", "interest", ".", "First", "we", "use", "given", "variable", "then", "environmental", "variable", "PID", "and", "then", "PID", "of", "running", "process" ]
train
https://github.com/vsoch/helpme/blob/e609172260b10cddadb2d2023ab26da8082a9feb/helpme/utils/memory.py#L30-L41
vsoch/helpme
helpme/utils/memory.py
get_memory_usage
def get_memory_usage(pid=None,timeout=1): '''get_memory_usage returns a dictionary of resident set size (rss) and virtual memory size (vms) for a process of interest, for as long as the process is running :param pid: the pid to use: :param timeout: the timeout :: notes example: ...
python
def get_memory_usage(pid=None,timeout=1): '''get_memory_usage returns a dictionary of resident set size (rss) and virtual memory size (vms) for a process of interest, for as long as the process is running :param pid: the pid to use: :param timeout: the timeout :: notes example: ...
[ "def", "get_memory_usage", "(", "pid", "=", "None", ",", "timeout", "=", "1", ")", ":", "rss", "=", "[", "]", "vms", "=", "[", "]", "# If no pid is provided, look for environment variable", "pid", "=", "get_pid", "(", "pid", ")", "process", "=", "psutil", ...
get_memory_usage returns a dictionary of resident set size (rss) and virtual memory size (vms) for a process of interest, for as long as the process is running :param pid: the pid to use: :param timeout: the timeout :: notes example: sleep 3 & exec python -m memory "$!"
[ "get_memory_usage", "returns", "a", "dictionary", "of", "resident", "set", "size", "(", "rss", ")", "and", "virtual", "memory", "size", "(", "vms", ")", "for", "a", "process", "of", "interest", "for", "as", "long", "as", "the", "process", "is", "running", ...
train
https://github.com/vsoch/helpme/blob/e609172260b10cddadb2d2023ab26da8082a9feb/helpme/utils/memory.py#L44-L69
SetBased/py-stratum
pystratum/RoutineLoaderHelper.py
RoutineLoaderHelper.load_stored_routine
def load_stored_routine(self): """ Loads the stored routine into the instance of MySQL. Returns the metadata of the stored routine if the stored routine is loaded successfully. Otherwise returns False. :rtype: dict[str,str]|bool """ try: self._routin...
python
def load_stored_routine(self): """ Loads the stored routine into the instance of MySQL. Returns the metadata of the stored routine if the stored routine is loaded successfully. Otherwise returns False. :rtype: dict[str,str]|bool """ try: self._routin...
[ "def", "load_stored_routine", "(", "self", ")", ":", "try", ":", "self", ".", "_routine_name", "=", "os", ".", "path", ".", "splitext", "(", "os", ".", "path", ".", "basename", "(", "self", ".", "_source_filename", ")", ")", "[", "0", "]", "if", "os"...
Loads the stored routine into the instance of MySQL. Returns the metadata of the stored routine if the stored routine is loaded successfully. Otherwise returns False. :rtype: dict[str,str]|bool
[ "Loads", "the", "stored", "routine", "into", "the", "instance", "of", "MySQL", "." ]
train
https://github.com/SetBased/py-stratum/blob/7c5ffaa2fdd03f865832a5190b5897ff2c0e3155/pystratum/RoutineLoaderHelper.py#L190-L242
SetBased/py-stratum
pystratum/RoutineLoaderHelper.py
RoutineLoaderHelper.__read_source_file
def __read_source_file(self): """ Reads the file with the source of the stored routine. """ with open(self._source_filename, 'r', encoding=self._routine_file_encoding) as file: self._routine_source_code = file.read() self._routine_source_code_lines = self._routine_so...
python
def __read_source_file(self): """ Reads the file with the source of the stored routine. """ with open(self._source_filename, 'r', encoding=self._routine_file_encoding) as file: self._routine_source_code = file.read() self._routine_source_code_lines = self._routine_so...
[ "def", "__read_source_file", "(", "self", ")", ":", "with", "open", "(", "self", ".", "_source_filename", ",", "'r'", ",", "encoding", "=", "self", ".", "_routine_file_encoding", ")", "as", "file", ":", "self", ".", "_routine_source_code", "=", "file", ".", ...
Reads the file with the source of the stored routine.
[ "Reads", "the", "file", "with", "the", "source", "of", "the", "stored", "routine", "." ]
train
https://github.com/SetBased/py-stratum/blob/7c5ffaa2fdd03f865832a5190b5897ff2c0e3155/pystratum/RoutineLoaderHelper.py#L245-L252
SetBased/py-stratum
pystratum/RoutineLoaderHelper.py
RoutineLoaderHelper.__save_shadow_copy
def __save_shadow_copy(self): """ Saves a copy of the stored routine source with pure SQL (if shadow directory is set). """ if not self.shadow_directory: return destination_filename = os.path.join(self.shadow_directory, self._routine_name) + '.sql' if os.pat...
python
def __save_shadow_copy(self): """ Saves a copy of the stored routine source with pure SQL (if shadow directory is set). """ if not self.shadow_directory: return destination_filename = os.path.join(self.shadow_directory, self._routine_name) + '.sql' if os.pat...
[ "def", "__save_shadow_copy", "(", "self", ")", ":", "if", "not", "self", ".", "shadow_directory", ":", "return", "destination_filename", "=", "os", ".", "path", ".", "join", "(", "self", ".", "shadow_directory", ",", "self", ".", "_routine_name", ")", "+", ...
Saves a copy of the stored routine source with pure SQL (if shadow directory is set).
[ "Saves", "a", "copy", "of", "the", "stored", "routine", "source", "with", "pure", "SQL", "(", "if", "shadow", "directory", "is", "set", ")", "." ]
train
https://github.com/SetBased/py-stratum/blob/7c5ffaa2fdd03f865832a5190b5897ff2c0e3155/pystratum/RoutineLoaderHelper.py#L255-L277
SetBased/py-stratum
pystratum/RoutineLoaderHelper.py
RoutineLoaderHelper.__substitute_replace_pairs
def __substitute_replace_pairs(self): """ Substitutes all replace pairs in the source of the stored routine. """ self._set_magic_constants() routine_source = [] i = 0 for line in self._routine_source_code_lines: self._replace['__LINE__'] = "'%d'" % (i...
python
def __substitute_replace_pairs(self): """ Substitutes all replace pairs in the source of the stored routine. """ self._set_magic_constants() routine_source = [] i = 0 for line in self._routine_source_code_lines: self._replace['__LINE__'] = "'%d'" % (i...
[ "def", "__substitute_replace_pairs", "(", "self", ")", ":", "self", ".", "_set_magic_constants", "(", ")", "routine_source", "=", "[", "]", "i", "=", "0", "for", "line", "in", "self", ".", "_routine_source_code_lines", ":", "self", ".", "_replace", "[", "'__...
Substitutes all replace pairs in the source of the stored routine.
[ "Substitutes", "all", "replace", "pairs", "in", "the", "source", "of", "the", "stored", "routine", "." ]
train
https://github.com/SetBased/py-stratum/blob/7c5ffaa2fdd03f865832a5190b5897ff2c0e3155/pystratum/RoutineLoaderHelper.py#L280-L297
SetBased/py-stratum
pystratum/RoutineLoaderHelper.py
RoutineLoaderHelper._log_exception
def _log_exception(self, exception): """ Logs an exception. :param Exception exception: The exception. :rtype: None """ self._io.error(str(exception).strip().split(os.linesep))
python
def _log_exception(self, exception): """ Logs an exception. :param Exception exception: The exception. :rtype: None """ self._io.error(str(exception).strip().split(os.linesep))
[ "def", "_log_exception", "(", "self", ",", "exception", ")", ":", "self", ".", "_io", ".", "error", "(", "str", "(", "exception", ")", ".", "strip", "(", ")", ".", "split", "(", "os", ".", "linesep", ")", ")" ]
Logs an exception. :param Exception exception: The exception. :rtype: None
[ "Logs", "an", "exception", "." ]
train
https://github.com/SetBased/py-stratum/blob/7c5ffaa2fdd03f865832a5190b5897ff2c0e3155/pystratum/RoutineLoaderHelper.py#L300-L308
SetBased/py-stratum
pystratum/RoutineLoaderHelper.py
RoutineLoaderHelper.__get_placeholders
def __get_placeholders(self): """ Extracts the placeholders from the stored routine source. """ ret = True pattern = re.compile('(@[A-Za-z0-9_.]+(%(max-)?type)?@)') matches = pattern.findall(self._routine_source_code) placeholders = [] if len(matches) !...
python
def __get_placeholders(self): """ Extracts the placeholders from the stored routine source. """ ret = True pattern = re.compile('(@[A-Za-z0-9_.]+(%(max-)?type)?@)') matches = pattern.findall(self._routine_source_code) placeholders = [] if len(matches) !...
[ "def", "__get_placeholders", "(", "self", ")", ":", "ret", "=", "True", "pattern", "=", "re", ".", "compile", "(", "'(@[A-Za-z0-9_.]+(%(max-)?type)?@)'", ")", "matches", "=", "pattern", ".", "findall", "(", "self", ".", "_routine_source_code", ")", "placeholders...
Extracts the placeholders from the stored routine source.
[ "Extracts", "the", "placeholders", "from", "the", "stored", "routine", "source", "." ]
train
https://github.com/SetBased/py-stratum/blob/7c5ffaa2fdd03f865832a5190b5897ff2c0e3155/pystratum/RoutineLoaderHelper.py#L321-L345
SetBased/py-stratum
pystratum/RoutineLoaderHelper.py
RoutineLoaderHelper._get_designation_type
def _get_designation_type(self): """ Extracts the designation type of the stored routine. """ positions = self._get_specification_positions() if positions[0] != -1 and positions[1] != -1: pattern = re.compile(r'^\s*--\s+type\s*:\s*(\w+)\s*(.+)?\s*', re.IGNORECASE) ...
python
def _get_designation_type(self): """ Extracts the designation type of the stored routine. """ positions = self._get_specification_positions() if positions[0] != -1 and positions[1] != -1: pattern = re.compile(r'^\s*--\s+type\s*:\s*(\w+)\s*(.+)?\s*', re.IGNORECASE) ...
[ "def", "_get_designation_type", "(", "self", ")", ":", "positions", "=", "self", ".", "_get_specification_positions", "(", ")", "if", "positions", "[", "0", "]", "!=", "-", "1", "and", "positions", "[", "1", "]", "!=", "-", "1", ":", "pattern", "=", "r...
Extracts the designation type of the stored routine.
[ "Extracts", "the", "designation", "type", "of", "the", "stored", "routine", "." ]
train
https://github.com/SetBased/py-stratum/blob/7c5ffaa2fdd03f865832a5190b5897ff2c0e3155/pystratum/RoutineLoaderHelper.py#L348-L377
SetBased/py-stratum
pystratum/RoutineLoaderHelper.py
RoutineLoaderHelper._get_specification_positions
def _get_specification_positions(self): """ Returns a tuple with the start and end line numbers of the stored routine specification. :rtype: tuple """ start = -1 for (i, line) in enumerate(self._routine_source_code_lines): if self._is_start_of_stored_routine(...
python
def _get_specification_positions(self): """ Returns a tuple with the start and end line numbers of the stored routine specification. :rtype: tuple """ start = -1 for (i, line) in enumerate(self._routine_source_code_lines): if self._is_start_of_stored_routine(...
[ "def", "_get_specification_positions", "(", "self", ")", ":", "start", "=", "-", "1", "for", "(", "i", ",", "line", ")", "in", "enumerate", "(", "self", ".", "_routine_source_code_lines", ")", ":", "if", "self", ".", "_is_start_of_stored_routine", "(", "line...
Returns a tuple with the start and end line numbers of the stored routine specification. :rtype: tuple
[ "Returns", "a", "tuple", "with", "the", "start", "and", "end", "line", "numbers", "of", "the", "stored", "routine", "specification", "." ]
train
https://github.com/SetBased/py-stratum/blob/7c5ffaa2fdd03f865832a5190b5897ff2c0e3155/pystratum/RoutineLoaderHelper.py#L380-L396
SetBased/py-stratum
pystratum/RoutineLoaderHelper.py
RoutineLoaderHelper.__get_doc_block_lines
def __get_doc_block_lines(self): """ Returns the start and end line of the DOcBlock of the stored routine code. """ line1 = None line2 = None i = 0 for line in self._routine_source_code_lines: if re.match(r'\s*/\*\*', line): line1 = i ...
python
def __get_doc_block_lines(self): """ Returns the start and end line of the DOcBlock of the stored routine code. """ line1 = None line2 = None i = 0 for line in self._routine_source_code_lines: if re.match(r'\s*/\*\*', line): line1 = i ...
[ "def", "__get_doc_block_lines", "(", "self", ")", ":", "line1", "=", "None", "line2", "=", "None", "i", "=", "0", "for", "line", "in", "self", ".", "_routine_source_code_lines", ":", "if", "re", ".", "match", "(", "r'\\s*/\\*\\*'", ",", "line", ")", ":",...
Returns the start and end line of the DOcBlock of the stored routine code.
[ "Returns", "the", "start", "and", "end", "line", "of", "the", "DOcBlock", "of", "the", "stored", "routine", "code", "." ]
train
https://github.com/SetBased/py-stratum/blob/7c5ffaa2fdd03f865832a5190b5897ff2c0e3155/pystratum/RoutineLoaderHelper.py#L422-L442
SetBased/py-stratum
pystratum/RoutineLoaderHelper.py
RoutineLoaderHelper.__get_doc_block_parts_source
def __get_doc_block_parts_source(self): """ Extracts the DocBlock (in parts) from the source of the stored routine source. """ line1, line2 = self.__get_doc_block_lines() if line1 is not None and line2 is not None and line1 <= line2: doc_block = self._routine_source_...
python
def __get_doc_block_parts_source(self): """ Extracts the DocBlock (in parts) from the source of the stored routine source. """ line1, line2 = self.__get_doc_block_lines() if line1 is not None and line2 is not None and line1 <= line2: doc_block = self._routine_source_...
[ "def", "__get_doc_block_parts_source", "(", "self", ")", ":", "line1", ",", "line2", "=", "self", ".", "__get_doc_block_lines", "(", ")", "if", "line1", "is", "not", "None", "and", "line2", "is", "not", "None", "and", "line1", "<=", "line2", ":", "doc_bloc...
Extracts the DocBlock (in parts) from the source of the stored routine source.
[ "Extracts", "the", "DocBlock", "(", "in", "parts", ")", "from", "the", "source", "of", "the", "stored", "routine", "source", "." ]
train
https://github.com/SetBased/py-stratum/blob/7c5ffaa2fdd03f865832a5190b5897ff2c0e3155/pystratum/RoutineLoaderHelper.py#L445-L465
SetBased/py-stratum
pystratum/RoutineLoaderHelper.py
RoutineLoaderHelper.__get_doc_block_parts_wrapper
def __get_doc_block_parts_wrapper(self): """ Generates the DocBlock parts to be used by the wrapper generator. """ self.__get_doc_block_parts_source() helper = self._get_data_type_helper() parameters = list() for parameter_info in self._parameters: p...
python
def __get_doc_block_parts_wrapper(self): """ Generates the DocBlock parts to be used by the wrapper generator. """ self.__get_doc_block_parts_source() helper = self._get_data_type_helper() parameters = list() for parameter_info in self._parameters: p...
[ "def", "__get_doc_block_parts_wrapper", "(", "self", ")", ":", "self", ".", "__get_doc_block_parts_source", "(", ")", "helper", "=", "self", ".", "_get_data_type_helper", "(", ")", "parameters", "=", "list", "(", ")", "for", "parameter_info", "in", "self", ".", ...
Generates the DocBlock parts to be used by the wrapper generator.
[ "Generates", "the", "DocBlock", "parts", "to", "be", "used", "by", "the", "wrapper", "generator", "." ]
train
https://github.com/SetBased/py-stratum/blob/7c5ffaa2fdd03f865832a5190b5897ff2c0e3155/pystratum/RoutineLoaderHelper.py#L493-L510
SetBased/py-stratum
pystratum/RoutineLoaderHelper.py
RoutineLoaderHelper._update_metadata
def _update_metadata(self): """ Updates the metadata of the stored routine. """ self._pystratum_metadata['routine_name'] = self._routine_name self._pystratum_metadata['designation'] = self._designation_type self._pystratum_metadata['table_name'] = self._table_name ...
python
def _update_metadata(self): """ Updates the metadata of the stored routine. """ self._pystratum_metadata['routine_name'] = self._routine_name self._pystratum_metadata['designation'] = self._designation_type self._pystratum_metadata['table_name'] = self._table_name ...
[ "def", "_update_metadata", "(", "self", ")", ":", "self", ".", "_pystratum_metadata", "[", "'routine_name'", "]", "=", "self", ".", "_routine_name", "self", ".", "_pystratum_metadata", "[", "'designation'", "]", "=", "self", ".", "_designation_type", "self", "."...
Updates the metadata of the stored routine.
[ "Updates", "the", "metadata", "of", "the", "stored", "routine", "." ]
train
https://github.com/SetBased/py-stratum/blob/7c5ffaa2fdd03f865832a5190b5897ff2c0e3155/pystratum/RoutineLoaderHelper.py#L547-L560
SetBased/py-stratum
pystratum/RoutineLoaderHelper.py
RoutineLoaderHelper._set_magic_constants
def _set_magic_constants(self): """ Adds magic constants to replace list. """ real_path = os.path.realpath(self._source_filename) self._replace['__FILE__'] = "'%s'" % real_path self._replace['__ROUTINE__'] = "'%s'" % self._routine_name self._replace['__DIR__'] = ...
python
def _set_magic_constants(self): """ Adds magic constants to replace list. """ real_path = os.path.realpath(self._source_filename) self._replace['__FILE__'] = "'%s'" % real_path self._replace['__ROUTINE__'] = "'%s'" % self._routine_name self._replace['__DIR__'] = ...
[ "def", "_set_magic_constants", "(", "self", ")", ":", "real_path", "=", "os", ".", "path", ".", "realpath", "(", "self", ".", "_source_filename", ")", "self", ".", "_replace", "[", "'__FILE__'", "]", "=", "\"'%s'\"", "%", "real_path", "self", ".", "_replac...
Adds magic constants to replace list.
[ "Adds", "magic", "constants", "to", "replace", "list", "." ]
train
https://github.com/SetBased/py-stratum/blob/7c5ffaa2fdd03f865832a5190b5897ff2c0e3155/pystratum/RoutineLoaderHelper.py#L571-L579
SetBased/py-stratum
pystratum/RoutineLoaderHelper.py
RoutineLoaderHelper._unset_magic_constants
def _unset_magic_constants(self): """ Removes magic constants from current replace list. """ if '__FILE__' in self._replace: del self._replace['__FILE__'] if '__ROUTINE__' in self._replace: del self._replace['__ROUTINE__'] if '__DIR__' in self._r...
python
def _unset_magic_constants(self): """ Removes magic constants from current replace list. """ if '__FILE__' in self._replace: del self._replace['__FILE__'] if '__ROUTINE__' in self._replace: del self._replace['__ROUTINE__'] if '__DIR__' in self._r...
[ "def", "_unset_magic_constants", "(", "self", ")", ":", "if", "'__FILE__'", "in", "self", ".", "_replace", ":", "del", "self", ".", "_replace", "[", "'__FILE__'", "]", "if", "'__ROUTINE__'", "in", "self", ".", "_replace", ":", "del", "self", ".", "_replace...
Removes magic constants from current replace list.
[ "Removes", "magic", "constants", "from", "current", "replace", "list", "." ]
train
https://github.com/SetBased/py-stratum/blob/7c5ffaa2fdd03f865832a5190b5897ff2c0e3155/pystratum/RoutineLoaderHelper.py#L582-L596
SetBased/py-stratum
pystratum/RoutineLoaderHelper.py
RoutineLoaderHelper._print_sql_with_error
def _print_sql_with_error(self, sql, error_line): """ Writes a SQL statement with an syntax error to the output. The line where the error occurs is highlighted. :param str sql: The SQL statement. :param int error_line: The line where the error occurs. """ if os.linesep i...
python
def _print_sql_with_error(self, sql, error_line): """ Writes a SQL statement with an syntax error to the output. The line where the error occurs is highlighted. :param str sql: The SQL statement. :param int error_line: The line where the error occurs. """ if os.linesep i...
[ "def", "_print_sql_with_error", "(", "self", ",", "sql", ",", "error_line", ")", ":", "if", "os", ".", "linesep", "in", "sql", ":", "lines", "=", "sql", ".", "split", "(", "os", ".", "linesep", ")", "digits", "=", "math", ".", "ceil", "(", "math", ...
Writes a SQL statement with an syntax error to the output. The line where the error occurs is highlighted. :param str sql: The SQL statement. :param int error_line: The line where the error occurs.
[ "Writes", "a", "SQL", "statement", "with", "an", "syntax", "error", "to", "the", "output", ".", "The", "line", "where", "the", "error", "occurs", "is", "highlighted", "." ]
train
https://github.com/SetBased/py-stratum/blob/7c5ffaa2fdd03f865832a5190b5897ff2c0e3155/pystratum/RoutineLoaderHelper.py#L599-L617
mjirik/io3d
io3d/dili.py
list_filter
def list_filter(lst, startswith=None, notstartswith=None, contain=None, notcontain=None): """ Keep in list items according to filter parameters. :param lst: item list :param startswith: keep items starting with :param notstartswith: remove items starting with :return: """ ke...
python
def list_filter(lst, startswith=None, notstartswith=None, contain=None, notcontain=None): """ Keep in list items according to filter parameters. :param lst: item list :param startswith: keep items starting with :param notstartswith: remove items starting with :return: """ ke...
[ "def", "list_filter", "(", "lst", ",", "startswith", "=", "None", ",", "notstartswith", "=", "None", ",", "contain", "=", "None", ",", "notcontain", "=", "None", ")", ":", "keeped", "=", "[", "]", "for", "item", "in", "lst", ":", "keep", "=", "False"...
Keep in list items according to filter parameters. :param lst: item list :param startswith: keep items starting with :param notstartswith: remove items starting with :return:
[ "Keep", "in", "list", "items", "according", "to", "filter", "parameters", "." ]
train
https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/dili.py#L41-L68
mjirik/io3d
io3d/dili.py
split_dict
def split_dict(dct, keys): """ Split dict into two subdicts based on keys. :param dct: :param keys: :return: dict_in, dict_out """ if type(dct) == collections.OrderedDict: dict_in = collections.OrderedDict() dict_out = collections.OrderedDict() else: dict_in = {}...
python
def split_dict(dct, keys): """ Split dict into two subdicts based on keys. :param dct: :param keys: :return: dict_in, dict_out """ if type(dct) == collections.OrderedDict: dict_in = collections.OrderedDict() dict_out = collections.OrderedDict() else: dict_in = {}...
[ "def", "split_dict", "(", "dct", ",", "keys", ")", ":", "if", "type", "(", "dct", ")", "==", "collections", ".", "OrderedDict", ":", "dict_in", "=", "collections", ".", "OrderedDict", "(", ")", "dict_out", "=", "collections", ".", "OrderedDict", "(", ")"...
Split dict into two subdicts based on keys. :param dct: :param keys: :return: dict_in, dict_out
[ "Split", "dict", "into", "two", "subdicts", "based", "on", "keys", "." ]
train
https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/dili.py#L82-L102
mjirik/io3d
io3d/dili.py
recursive_update
def recursive_update(d, u): """ Dict recursive update. Based on Alex Martelli code on stackoverflow http://stackoverflow.com/questions/3232943/update-value-of-a-nested-dictionary-of-varying-depth?answertab=votes#tab-top :param d: dict to update :param u: dict with new data :return: """...
python
def recursive_update(d, u): """ Dict recursive update. Based on Alex Martelli code on stackoverflow http://stackoverflow.com/questions/3232943/update-value-of-a-nested-dictionary-of-varying-depth?answertab=votes#tab-top :param d: dict to update :param u: dict with new data :return: """...
[ "def", "recursive_update", "(", "d", ",", "u", ")", ":", "for", "k", ",", "v", "in", "u", ".", "iteritems", "(", ")", ":", "if", "isinstance", "(", "v", ",", "collections", ".", "Mapping", ")", ":", "r", "=", "recursive_update", "(", "d", ".", "g...
Dict recursive update. Based on Alex Martelli code on stackoverflow http://stackoverflow.com/questions/3232943/update-value-of-a-nested-dictionary-of-varying-depth?answertab=votes#tab-top :param d: dict to update :param u: dict with new data :return:
[ "Dict", "recursive", "update", "." ]
train
https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/dili.py#L104-L121
mjirik/io3d
io3d/dili.py
flatten_dict_join_keys
def flatten_dict_join_keys(dct, join_symbol=" "): """ Flatten dict with defined key join symbol. :param dct: dict to flatten :param join_symbol: default value is " " :return: """ return dict( flatten_dict(dct, join=lambda a,b:a+join_symbol+b) )
python
def flatten_dict_join_keys(dct, join_symbol=" "): """ Flatten dict with defined key join symbol. :param dct: dict to flatten :param join_symbol: default value is " " :return: """ return dict( flatten_dict(dct, join=lambda a,b:a+join_symbol+b) )
[ "def", "flatten_dict_join_keys", "(", "dct", ",", "join_symbol", "=", "\" \"", ")", ":", "return", "dict", "(", "flatten_dict", "(", "dct", ",", "join", "=", "lambda", "a", ",", "b", ":", "a", "+", "join_symbol", "+", "b", ")", ")" ]
Flatten dict with defined key join symbol. :param dct: dict to flatten :param join_symbol: default value is " " :return:
[ "Flatten", "dict", "with", "defined", "key", "join", "symbol", "." ]
train
https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/dili.py#L128-L135
mjirik/io3d
io3d/dili.py
list_contains
def list_contains(list_of_strings, substring, return_true_false_array=False): """ Get strings in list which contains substring. """ key_tf = [keyi.find(substring) != -1 for keyi in list_of_strings] if return_true_false_array: return key_tf keys_to_remove = list_of_strings[key_tf] return...
python
def list_contains(list_of_strings, substring, return_true_false_array=False): """ Get strings in list which contains substring. """ key_tf = [keyi.find(substring) != -1 for keyi in list_of_strings] if return_true_false_array: return key_tf keys_to_remove = list_of_strings[key_tf] return...
[ "def", "list_contains", "(", "list_of_strings", ",", "substring", ",", "return_true_false_array", "=", "False", ")", ":", "key_tf", "=", "[", "keyi", ".", "find", "(", "substring", ")", "!=", "-", "1", "for", "keyi", "in", "list_of_strings", "]", "if", "re...
Get strings in list which contains substring.
[ "Get", "strings", "in", "list", "which", "contains", "substring", "." ]
train
https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/dili.py#L176-L184
mjirik/io3d
io3d/dili.py
df_drop_duplicates
def df_drop_duplicates(df, ignore_key_pattern="time"): """ Drop duplicates from dataframe ignore columns with keys containing defined pattern. :param df: :param noinfo_key_pattern: :return: """ keys_to_remove = list_contains(df.keys(), ignore_key_pattern) #key_tf = [key.find(noinfo_key...
python
def df_drop_duplicates(df, ignore_key_pattern="time"): """ Drop duplicates from dataframe ignore columns with keys containing defined pattern. :param df: :param noinfo_key_pattern: :return: """ keys_to_remove = list_contains(df.keys(), ignore_key_pattern) #key_tf = [key.find(noinfo_key...
[ "def", "df_drop_duplicates", "(", "df", ",", "ignore_key_pattern", "=", "\"time\"", ")", ":", "keys_to_remove", "=", "list_contains", "(", "df", ".", "keys", "(", ")", ",", "ignore_key_pattern", ")", "#key_tf = [key.find(noinfo_key_pattern) != -1 for key in df.keys()]", ...
Drop duplicates from dataframe ignore columns with keys containing defined pattern. :param df: :param noinfo_key_pattern: :return:
[ "Drop", "duplicates", "from", "dataframe", "ignore", "columns", "with", "keys", "containing", "defined", "pattern", "." ]
train
https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/dili.py#L187-L205
mjirik/io3d
io3d/dili.py
ndarray_to_list_in_structure
def ndarray_to_list_in_structure(item, squeeze=True): """ Change ndarray in structure of lists and dicts into lists. """ tp = type(item) if tp == np.ndarray: if squeeze: item = item.squeeze() item = item.tolist() elif tp == list: for i in range(len(item)): ...
python
def ndarray_to_list_in_structure(item, squeeze=True): """ Change ndarray in structure of lists and dicts into lists. """ tp = type(item) if tp == np.ndarray: if squeeze: item = item.squeeze() item = item.tolist() elif tp == list: for i in range(len(item)): ...
[ "def", "ndarray_to_list_in_structure", "(", "item", ",", "squeeze", "=", "True", ")", ":", "tp", "=", "type", "(", "item", ")", "if", "tp", "==", "np", ".", "ndarray", ":", "if", "squeeze", ":", "item", "=", "item", ".", "squeeze", "(", ")", "item", ...
Change ndarray in structure of lists and dicts into lists.
[ "Change", "ndarray", "in", "structure", "of", "lists", "and", "dicts", "into", "lists", "." ]
train
https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/dili.py#L208-L224
mjirik/io3d
io3d/dili.py
dict_find_key
def dict_find_key(dd, value): """ Find first suitable key in dict. :param dd: :param value: :return: """ key = next(key for key, val in dd.items() if val == value) return key
python
def dict_find_key(dd, value): """ Find first suitable key in dict. :param dd: :param value: :return: """ key = next(key for key, val in dd.items() if val == value) return key
[ "def", "dict_find_key", "(", "dd", ",", "value", ")", ":", "key", "=", "next", "(", "key", "for", "key", ",", "val", "in", "dd", ".", "items", "(", ")", "if", "val", "==", "value", ")", "return", "key" ]
Find first suitable key in dict. :param dd: :param value: :return:
[ "Find", "first", "suitable", "key", "in", "dict", "." ]
train
https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/dili.py#L227-L235
mjirik/io3d
io3d/dili.py
sort_list_of_dicts
def sort_list_of_dicts(lst_of_dct, keys, reverse=False, **sort_args): """ Sort list of dicts by one or multiple keys. If the key is not available, sort these to the end. :param lst_of_dct: input structure. List of dicts. :param keys: one or more keys in list :param reverse: :param sort_arg...
python
def sort_list_of_dicts(lst_of_dct, keys, reverse=False, **sort_args): """ Sort list of dicts by one or multiple keys. If the key is not available, sort these to the end. :param lst_of_dct: input structure. List of dicts. :param keys: one or more keys in list :param reverse: :param sort_arg...
[ "def", "sort_list_of_dicts", "(", "lst_of_dct", ",", "keys", ",", "reverse", "=", "False", ",", "*", "*", "sort_args", ")", ":", "if", "type", "(", "keys", ")", "!=", "list", ":", "keys", "=", "[", "keys", "]", "# dcmdir = lst_of_dct[:]", "# lst_of_dct.sor...
Sort list of dicts by one or multiple keys. If the key is not available, sort these to the end. :param lst_of_dct: input structure. List of dicts. :param keys: one or more keys in list :param reverse: :param sort_args: :return:
[ "Sort", "list", "of", "dicts", "by", "one", "or", "multiple", "keys", "." ]
train
https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/dili.py#L238-L256
mjirik/io3d
io3d/dili.py
ordered_dict_to_dict
def ordered_dict_to_dict(config): """ Use dict instead of ordered dict in structure. """ if type(config) == collections.OrderedDict: config = dict(config) if type(config) == list: for i in range(0, len(config)): config[i] = ordered_dict_to_dict(config[i]) elif type(c...
python
def ordered_dict_to_dict(config): """ Use dict instead of ordered dict in structure. """ if type(config) == collections.OrderedDict: config = dict(config) if type(config) == list: for i in range(0, len(config)): config[i] = ordered_dict_to_dict(config[i]) elif type(c...
[ "def", "ordered_dict_to_dict", "(", "config", ")", ":", "if", "type", "(", "config", ")", "==", "collections", ".", "OrderedDict", ":", "config", "=", "dict", "(", "config", ")", "if", "type", "(", "config", ")", "==", "list", ":", "for", "i", "in", ...
Use dict instead of ordered dict in structure.
[ "Use", "dict", "instead", "of", "ordered", "dict", "in", "structure", "." ]
train
https://github.com/mjirik/io3d/blob/ccaf3e378dcc967f2565d477fc27583fd0f61fcc/io3d/dili.py#L258-L272
SetBased/py-stratum
pystratum/command/WrapperCommand.py
WrapperCommand.run_command
def run_command(self, config_file): """ :param str config_file: The name of config file. """ config = configparser.ConfigParser() config.read(config_file) rdbms = config.get('database', 'rdbms').lower() wrapper = self.create_routine_wrapper_generator(rdbms) ...
python
def run_command(self, config_file): """ :param str config_file: The name of config file. """ config = configparser.ConfigParser() config.read(config_file) rdbms = config.get('database', 'rdbms').lower() wrapper = self.create_routine_wrapper_generator(rdbms) ...
[ "def", "run_command", "(", "self", ",", "config_file", ")", ":", "config", "=", "configparser", ".", "ConfigParser", "(", ")", "config", ".", "read", "(", "config_file", ")", "rdbms", "=", "config", ".", "get", "(", "'database'", ",", "'rdbms'", ")", "."...
:param str config_file: The name of config file.
[ ":", "param", "str", "config_file", ":", "The", "name", "of", "config", "file", "." ]
train
https://github.com/SetBased/py-stratum/blob/7c5ffaa2fdd03f865832a5190b5897ff2c0e3155/pystratum/command/WrapperCommand.py#L38-L48
SetBased/py-stratum
pystratum/command/WrapperCommand.py
WrapperCommand.create_routine_wrapper_generator
def create_routine_wrapper_generator(self, rdbms): """ Factory for creating a Constants objects (i.e. objects for generating a class with wrapper methods for calling stored routines in a database). :param str rdbms: The target RDBMS (i.e. mysql, mssql or pgsql). :rtype: pystrat...
python
def create_routine_wrapper_generator(self, rdbms): """ Factory for creating a Constants objects (i.e. objects for generating a class with wrapper methods for calling stored routines in a database). :param str rdbms: The target RDBMS (i.e. mysql, mssql or pgsql). :rtype: pystrat...
[ "def", "create_routine_wrapper_generator", "(", "self", ",", "rdbms", ")", ":", "# Note: We load modules and classes dynamically such that on the end user's system only the required modules", "# and other dependencies for the targeted RDBMS must be installed (and required modules and other",...
Factory for creating a Constants objects (i.e. objects for generating a class with wrapper methods for calling stored routines in a database). :param str rdbms: The target RDBMS (i.e. mysql, mssql or pgsql). :rtype: pystratum.RoutineWrapperGenerator.RoutineWrapperGenerator
[ "Factory", "for", "creating", "a", "Constants", "objects", "(", "i", ".", "e", ".", "objects", "for", "generating", "a", "class", "with", "wrapper", "methods", "for", "calling", "stored", "routines", "in", "a", "database", ")", "." ]
train
https://github.com/SetBased/py-stratum/blob/7c5ffaa2fdd03f865832a5190b5897ff2c0e3155/pystratum/command/WrapperCommand.py#L51-L76
SetBased/py-stratum
pystratum/Connection.py
Connection._get_option
def _get_option(config, supplement, section, option, fallback=None): """ Reads an option for a configuration file. :param configparser.ConfigParser config: The main config file. :param configparser.ConfigParser supplement: The supplement config file. :param str section: The name...
python
def _get_option(config, supplement, section, option, fallback=None): """ Reads an option for a configuration file. :param configparser.ConfigParser config: The main config file. :param configparser.ConfigParser supplement: The supplement config file. :param str section: The name...
[ "def", "_get_option", "(", "config", ",", "supplement", ",", "section", ",", "option", ",", "fallback", "=", "None", ")", ":", "if", "supplement", ":", "return_value", "=", "supplement", ".", "get", "(", "section", ",", "option", ",", "fallback", "=", "c...
Reads an option for a configuration file. :param configparser.ConfigParser config: The main config file. :param configparser.ConfigParser supplement: The supplement config file. :param str section: The name of the section op the option. :param str option: The name of the option. ...
[ "Reads", "an", "option", "for", "a", "configuration", "file", "." ]
train
https://github.com/SetBased/py-stratum/blob/7c5ffaa2fdd03f865832a5190b5897ff2c0e3155/pystratum/Connection.py#L28-L50
SetBased/py-stratum
pystratum/Connection.py
Connection._read_configuration
def _read_configuration(config_filename): """ Checks the supplement file. :param str config_filename: The name of the configuration file. :rtype: (configparser.ConfigParser,configparser.ConfigParser) """ config = ConfigParser() config.read(config_filename) ...
python
def _read_configuration(config_filename): """ Checks the supplement file. :param str config_filename: The name of the configuration file. :rtype: (configparser.ConfigParser,configparser.ConfigParser) """ config = ConfigParser() config.read(config_filename) ...
[ "def", "_read_configuration", "(", "config_filename", ")", ":", "config", "=", "ConfigParser", "(", ")", "config", ".", "read", "(", "config_filename", ")", "if", "'supplement'", "in", "config", "[", "'database'", "]", ":", "path", "=", "os", ".", "path", ...
Checks the supplement file. :param str config_filename: The name of the configuration file. :rtype: (configparser.ConfigParser,configparser.ConfigParser)
[ "Checks", "the", "supplement", "file", "." ]
train
https://github.com/SetBased/py-stratum/blob/7c5ffaa2fdd03f865832a5190b5897ff2c0e3155/pystratum/Connection.py#L54-L72
vsoch/helpme
helpme/action/record.py
record_asciinema
def record_asciinema(): '''a wrapper around generation of an asciinema.api.Api and a custom recorder to pull out the input arguments to the Record from argparse. The function generates a filename in advance and a return code so we can check the final status. ''' import asciinema.conf...
python
def record_asciinema(): '''a wrapper around generation of an asciinema.api.Api and a custom recorder to pull out the input arguments to the Record from argparse. The function generates a filename in advance and a return code so we can check the final status. ''' import asciinema.conf...
[ "def", "record_asciinema", "(", ")", ":", "import", "asciinema", ".", "config", "as", "aconfig", "from", "asciinema", ".", "api", "import", "Api", "# Load the API class", "cfg", "=", "aconfig", ".", "load", "(", ")", "api", "=", "Api", "(", "cfg", ".", "...
a wrapper around generation of an asciinema.api.Api and a custom recorder to pull out the input arguments to the Record from argparse. The function generates a filename in advance and a return code so we can check the final status.
[ "a", "wrapper", "around", "generation", "of", "an", "asciinema", ".", "api", ".", "Api", "and", "a", "custom", "recorder", "to", "pull", "out", "the", "input", "arguments", "to", "the", "Record", "from", "argparse", ".", "The", "function", "generates", "a"...
train
https://github.com/vsoch/helpme/blob/e609172260b10cddadb2d2023ab26da8082a9feb/helpme/action/record.py#L80-L101
bpannier/simpletr64
simpletr64/actions/fritz.py
Fritz.sendWakeOnLan
def sendWakeOnLan(self, macAddress, lanInterfaceId=1, timeout=1): """Send a wake up package to a device specified by its MAC address. :param str macAddress: MAC address in the form ``38:C9:86:26:7E:38``; be aware that the MAC address might be case sensitive, depending on the router ...
python
def sendWakeOnLan(self, macAddress, lanInterfaceId=1, timeout=1): """Send a wake up package to a device specified by its MAC address. :param str macAddress: MAC address in the form ``38:C9:86:26:7E:38``; be aware that the MAC address might be case sensitive, depending on the router ...
[ "def", "sendWakeOnLan", "(", "self", ",", "macAddress", ",", "lanInterfaceId", "=", "1", ",", "timeout", "=", "1", ")", ":", "namespace", "=", "Fritz", ".", "getServiceType", "(", "\"sendWakeOnLan\"", ")", "+", "str", "(", "lanInterfaceId", ")", "uri", "="...
Send a wake up package to a device specified by its MAC address. :param str macAddress: MAC address in the form ``38:C9:86:26:7E:38``; be aware that the MAC address might be case sensitive, depending on the router :param int lanInterfaceId: the id of the LAN interface :param float t...
[ "Send", "a", "wake", "up", "package", "to", "a", "device", "specified", "by", "its", "MAC", "address", "." ]
train
https://github.com/bpannier/simpletr64/blob/31081139f4e6c85084a56de1617df73927135466/simpletr64/actions/fritz.py#L91-L107
bpannier/simpletr64
simpletr64/actions/fritz.py
Fritz.doUpdate
def doUpdate(self, timeout=1): """Do a software update of the Fritz Box if available. :param float timeout: the timeout to wait for the action to be executed :return: a list of if an update was available and the update state (bool, str) :rtype: tuple(bool, str) """ names...
python
def doUpdate(self, timeout=1): """Do a software update of the Fritz Box if available. :param float timeout: the timeout to wait for the action to be executed :return: a list of if an update was available and the update state (bool, str) :rtype: tuple(bool, str) """ names...
[ "def", "doUpdate", "(", "self", ",", "timeout", "=", "1", ")", ":", "namespace", "=", "Fritz", ".", "getServiceType", "(", "\"doUpdate\"", ")", "uri", "=", "self", ".", "getControlURL", "(", "namespace", ")", "results", "=", "self", ".", "execute", "(", ...
Do a software update of the Fritz Box if available. :param float timeout: the timeout to wait for the action to be executed :return: a list of if an update was available and the update state (bool, str) :rtype: tuple(bool, str)
[ "Do", "a", "software", "update", "of", "the", "Fritz", "Box", "if", "available", "." ]
train
https://github.com/bpannier/simpletr64/blob/31081139f4e6c85084a56de1617df73927135466/simpletr64/actions/fritz.py#L109-L121
bpannier/simpletr64
simpletr64/actions/fritz.py
Fritz.isOptimizedForIPTV
def isOptimizedForIPTV(self, wifiInterfaceId=1, timeout=1): """Return if the Wifi interface is optimized for IP TV :param int wifiInterfaceId: the id of the Wifi interface :param float timeout: the timeout to wait for the action to be executed :return: if the Wifi interface is optimized...
python
def isOptimizedForIPTV(self, wifiInterfaceId=1, timeout=1): """Return if the Wifi interface is optimized for IP TV :param int wifiInterfaceId: the id of the Wifi interface :param float timeout: the timeout to wait for the action to be executed :return: if the Wifi interface is optimized...
[ "def", "isOptimizedForIPTV", "(", "self", ",", "wifiInterfaceId", "=", "1", ",", "timeout", "=", "1", ")", ":", "namespace", "=", "Fritz", ".", "getServiceType", "(", "\"isOptimizedForIPTV\"", ")", "+", "str", "(", "wifiInterfaceId", ")", "uri", "=", "self",...
Return if the Wifi interface is optimized for IP TV :param int wifiInterfaceId: the id of the Wifi interface :param float timeout: the timeout to wait for the action to be executed :return: if the Wifi interface is optimized for IP TV :rtype: bool .. seealso:: :meth:`~simpletr6...
[ "Return", "if", "the", "Wifi", "interface", "is", "optimized", "for", "IP", "TV" ]
train
https://github.com/bpannier/simpletr64/blob/31081139f4e6c85084a56de1617df73927135466/simpletr64/actions/fritz.py#L123-L138
bpannier/simpletr64
simpletr64/actions/fritz.py
Fritz.setOptimizedForIPTV
def setOptimizedForIPTV(self, status, wifiInterfaceId=1, timeout=1): """Set if the Wifi interface is optimized for IP TV :param bool status: set if Wifi interface should be optimized :param int wifiInterfaceId: the id of the Wifi interface :param float timeout: the timeout to wait for t...
python
def setOptimizedForIPTV(self, status, wifiInterfaceId=1, timeout=1): """Set if the Wifi interface is optimized for IP TV :param bool status: set if Wifi interface should be optimized :param int wifiInterfaceId: the id of the Wifi interface :param float timeout: the timeout to wait for t...
[ "def", "setOptimizedForIPTV", "(", "self", ",", "status", ",", "wifiInterfaceId", "=", "1", ",", "timeout", "=", "1", ")", ":", "namespace", "=", "Fritz", ".", "getServiceType", "(", "\"setOptimizedForIPTV\"", ")", "+", "str", "(", "wifiInterfaceId", ")", "u...
Set if the Wifi interface is optimized for IP TV :param bool status: set if Wifi interface should be optimized :param int wifiInterfaceId: the id of the Wifi interface :param float timeout: the timeout to wait for the action to be executed .. seealso:: :meth:`~simpletr64.actions.Fritz....
[ "Set", "if", "the", "Wifi", "interface", "is", "optimized", "for", "IP", "TV" ]
train
https://github.com/bpannier/simpletr64/blob/31081139f4e6c85084a56de1617df73927135466/simpletr64/actions/fritz.py#L140-L159
bpannier/simpletr64
simpletr64/actions/fritz.py
Fritz.getCallList
def getCallList(self, timeout=1): """Get the list of phone calls made Example of a phone call result: :: [{'Count': None, 'Name': None, 'CalledNumber': '030868709971', 'Numbertype': 'sip', 'Duration': '0:01', 'Caller': '015155255399', 'Called': 'SIP: 030868729971', 'Da...
python
def getCallList(self, timeout=1): """Get the list of phone calls made Example of a phone call result: :: [{'Count': None, 'Name': None, 'CalledNumber': '030868709971', 'Numbertype': 'sip', 'Duration': '0:01', 'Caller': '015155255399', 'Called': 'SIP: 030868729971', 'Da...
[ "def", "getCallList", "(", "self", ",", "timeout", "=", "1", ")", ":", "namespace", "=", "Fritz", ".", "getServiceType", "(", "\"getCallList\"", ")", "uri", "=", "self", ".", "getControlURL", "(", "namespace", ")", "results", "=", "self", ".", "execute", ...
Get the list of phone calls made Example of a phone call result: :: [{'Count': None, 'Name': None, 'CalledNumber': '030868709971', 'Numbertype': 'sip', 'Duration': '0:01', 'Caller': '015155255399', 'Called': 'SIP: 030868729971', 'Date': '02.01.14 13:14', 'Device': ...
[ "Get", "the", "list", "of", "phone", "calls", "made" ]
train
https://github.com/bpannier/simpletr64/blob/31081139f4e6c85084a56de1617df73927135466/simpletr64/actions/fritz.py#L161-L221
metachris/RPIO
source/RPIO/__init__.py
add_tcp_callback
def add_tcp_callback(port, callback, threaded_callback=False): """ Adds a unix socket server callback, which will be invoked when values arrive from a connected socket client. The callback must accept two parameters, eg. ``def callback(socket, msg)``. """ _rpio.add_tcp_callback(port, callback, t...
python
def add_tcp_callback(port, callback, threaded_callback=False): """ Adds a unix socket server callback, which will be invoked when values arrive from a connected socket client. The callback must accept two parameters, eg. ``def callback(socket, msg)``. """ _rpio.add_tcp_callback(port, callback, t...
[ "def", "add_tcp_callback", "(", "port", ",", "callback", ",", "threaded_callback", "=", "False", ")", ":", "_rpio", ".", "add_tcp_callback", "(", "port", ",", "callback", ",", "threaded_callback", ")" ]
Adds a unix socket server callback, which will be invoked when values arrive from a connected socket client. The callback must accept two parameters, eg. ``def callback(socket, msg)``.
[ "Adds", "a", "unix", "socket", "server", "callback", "which", "will", "be", "invoked", "when", "values", "arrive", "from", "a", "connected", "socket", "client", ".", "The", "callback", "must", "accept", "two", "parameters", "eg", ".", "def", "callback", "(",...
train
https://github.com/metachris/RPIO/blob/be1942a69b2592ddacd9dc833d2668a19aafd8d2/source/RPIO/__init__.py#L194-L200
metachris/RPIO
source/RPIO/__init__.py
add_interrupt_callback
def add_interrupt_callback(gpio_id, callback, edge='both', \ pull_up_down=PUD_OFF, threaded_callback=False, \ debounce_timeout_ms=None): """ Add a callback to be executed when the value on 'gpio_id' changes to the edge specified via the 'edge' parameter (default='both'). `pull_up_down` ...
python
def add_interrupt_callback(gpio_id, callback, edge='both', \ pull_up_down=PUD_OFF, threaded_callback=False, \ debounce_timeout_ms=None): """ Add a callback to be executed when the value on 'gpio_id' changes to the edge specified via the 'edge' parameter (default='both'). `pull_up_down` ...
[ "def", "add_interrupt_callback", "(", "gpio_id", ",", "callback", ",", "edge", "=", "'both'", ",", "pull_up_down", "=", "PUD_OFF", ",", "threaded_callback", "=", "False", ",", "debounce_timeout_ms", "=", "None", ")", ":", "_rpio", ".", "add_interrupt_callback", ...
Add a callback to be executed when the value on 'gpio_id' changes to the edge specified via the 'edge' parameter (default='both'). `pull_up_down` can be set to `RPIO.PUD_UP`, `RPIO.PUD_DOWN`, and `RPIO.PUD_OFF`. If `threaded_callback` is True, the callback will be started inside a Thread. If ...
[ "Add", "a", "callback", "to", "be", "executed", "when", "the", "value", "on", "gpio_id", "changes", "to", "the", "edge", "specified", "via", "the", "edge", "parameter", "(", "default", "=", "both", ")", "." ]
train
https://github.com/metachris/RPIO/blob/be1942a69b2592ddacd9dc833d2668a19aafd8d2/source/RPIO/__init__.py#L203-L220
metachris/RPIO
source/RPIO/__init__.py
wait_for_interrupts
def wait_for_interrupts(threaded=False, epoll_timeout=1): """ Blocking loop to listen for GPIO interrupts and distribute them to associated callbacks. epoll_timeout is an easy way to shutdown the blocking function. Per default the timeout is set to 1 second; if `_is_waiting_for_interrupts` is set to...
python
def wait_for_interrupts(threaded=False, epoll_timeout=1): """ Blocking loop to listen for GPIO interrupts and distribute them to associated callbacks. epoll_timeout is an easy way to shutdown the blocking function. Per default the timeout is set to 1 second; if `_is_waiting_for_interrupts` is set to...
[ "def", "wait_for_interrupts", "(", "threaded", "=", "False", ",", "epoll_timeout", "=", "1", ")", ":", "if", "threaded", ":", "t", "=", "Thread", "(", "target", "=", "_rpio", ".", "wait_for_interrupts", ",", "args", "=", "(", "epoll_timeout", ",", ")", "...
Blocking loop to listen for GPIO interrupts and distribute them to associated callbacks. epoll_timeout is an easy way to shutdown the blocking function. Per default the timeout is set to 1 second; if `_is_waiting_for_interrupts` is set to False the loop will exit. If an exception occurs while waiting f...
[ "Blocking", "loop", "to", "listen", "for", "GPIO", "interrupts", "and", "distribute", "them", "to", "associated", "callbacks", ".", "epoll_timeout", "is", "an", "easy", "way", "to", "shutdown", "the", "blocking", "function", ".", "Per", "default", "the", "time...
train
https://github.com/metachris/RPIO/blob/be1942a69b2592ddacd9dc833d2668a19aafd8d2/source/RPIO/__init__.py#L233-L254
metachris/RPIO
fabfile.py
build_gpio
def build_gpio(): """ Builds source with Python 2.7 and 3.2, and tests import """ with cd("/tmp/source/c_gpio"): test = "import _GPIO; print(_GPIO.VERSION_GPIO)" run("make gpio2.7 && cp build/_GPIO.so .") run('sudo python2.7 -c "%s"' % test) run("cp _GPIO.so ../RPIO/") ru...
python
def build_gpio(): """ Builds source with Python 2.7 and 3.2, and tests import """ with cd("/tmp/source/c_gpio"): test = "import _GPIO; print(_GPIO.VERSION_GPIO)" run("make gpio2.7 && cp build/_GPIO.so .") run('sudo python2.7 -c "%s"' % test) run("cp _GPIO.so ../RPIO/") ru...
[ "def", "build_gpio", "(", ")", ":", "with", "cd", "(", "\"/tmp/source/c_gpio\"", ")", ":", "test", "=", "\"import _GPIO; print(_GPIO.VERSION_GPIO)\"", "run", "(", "\"make gpio2.7 && cp build/_GPIO.so .\"", ")", "run", "(", "'sudo python2.7 -c \"%s\"'", "%", "test", ")",...
Builds source with Python 2.7 and 3.2, and tests import
[ "Builds", "source", "with", "Python", "2", ".", "7", "and", "3", ".", "2", "and", "tests", "import" ]
train
https://github.com/metachris/RPIO/blob/be1942a69b2592ddacd9dc833d2668a19aafd8d2/fabfile.py#L107-L117
metachris/RPIO
fabfile.py
build_pwm
def build_pwm(): """ Builds source with Python 2.7 and 3.2, and tests import """ with cd("/tmp/source/c_pwm"): test = "import _PWM; print(_PWM.VERSION)" run("make py2.7") run('sudo python2.7 -c "%s"' % test) run("cp _PWM.so ../RPIO/PWM/") run("mv _PWM.so ../RPIO/PWM/_PWM2...
python
def build_pwm(): """ Builds source with Python 2.7 and 3.2, and tests import """ with cd("/tmp/source/c_pwm"): test = "import _PWM; print(_PWM.VERSION)" run("make py2.7") run('sudo python2.7 -c "%s"' % test) run("cp _PWM.so ../RPIO/PWM/") run("mv _PWM.so ../RPIO/PWM/_PWM2...
[ "def", "build_pwm", "(", ")", ":", "with", "cd", "(", "\"/tmp/source/c_pwm\"", ")", ":", "test", "=", "\"import _PWM; print(_PWM.VERSION)\"", "run", "(", "\"make py2.7\"", ")", "run", "(", "'sudo python2.7 -c \"%s\"'", "%", "test", ")", "run", "(", "\"cp _PWM.so ....
Builds source with Python 2.7 and 3.2, and tests import
[ "Builds", "source", "with", "Python", "2", ".", "7", "and", "3", ".", "2", "and", "tests", "import" ]
train
https://github.com/metachris/RPIO/blob/be1942a69b2592ddacd9dc833d2668a19aafd8d2/fabfile.py#L120-L130
metachris/RPIO
fabfile.py
upload_to_pypi
def upload_to_pypi(): """ Upload sdist and bdist_eggs to pypi """ # One more safety input and then we are ready to go :) x = prompt("Are you sure to upload the current version to pypi?") if not x or not x.lower() in ["y", "yes"]: return local("rm -rf dist") local("python setup.py sdist"...
python
def upload_to_pypi(): """ Upload sdist and bdist_eggs to pypi """ # One more safety input and then we are ready to go :) x = prompt("Are you sure to upload the current version to pypi?") if not x or not x.lower() in ["y", "yes"]: return local("rm -rf dist") local("python setup.py sdist"...
[ "def", "upload_to_pypi", "(", ")", ":", "# One more safety input and then we are ready to go :)", "x", "=", "prompt", "(", "\"Are you sure to upload the current version to pypi?\"", ")", "if", "not", "x", "or", "not", "x", ".", "lower", "(", ")", "in", "[", "\"y\"", ...
Upload sdist and bdist_eggs to pypi
[ "Upload", "sdist", "and", "bdist_eggs", "to", "pypi" ]
train
https://github.com/metachris/RPIO/blob/be1942a69b2592ddacd9dc833d2668a19aafd8d2/fabfile.py#L181-L199
metachris/RPIO
source/RPIO/_RPIO.py
_threaded_callback
def _threaded_callback(callback, *args): """ Internal wrapper to start a callback in threaded mode. Using the daemon mode to not block the main thread from exiting. """ t = Thread(target=callback, args=args) t.daemon = True t.start()
python
def _threaded_callback(callback, *args): """ Internal wrapper to start a callback in threaded mode. Using the daemon mode to not block the main thread from exiting. """ t = Thread(target=callback, args=args) t.daemon = True t.start()
[ "def", "_threaded_callback", "(", "callback", ",", "*", "args", ")", ":", "t", "=", "Thread", "(", "target", "=", "callback", ",", "args", "=", "args", ")", "t", ".", "daemon", "=", "True", "t", ".", "start", "(", ")" ]
Internal wrapper to start a callback in threaded mode. Using the daemon mode to not block the main thread from exiting.
[ "Internal", "wrapper", "to", "start", "a", "callback", "in", "threaded", "mode", ".", "Using", "the", "daemon", "mode", "to", "not", "block", "the", "main", "thread", "from", "exiting", "." ]
train
https://github.com/metachris/RPIO/blob/be1942a69b2592ddacd9dc833d2668a19aafd8d2/source/RPIO/_RPIO.py#L48-L55
metachris/RPIO
source/RPIO/_RPIO.py
Interruptor.add_tcp_callback
def add_tcp_callback(self, port, callback, threaded_callback=False): """ Adds a unix socket server callback, which will be invoked when values arrive from a connected socket client. The callback must accept two parameters, eg. ``def callback(socket, msg)``. """ if not cal...
python
def add_tcp_callback(self, port, callback, threaded_callback=False): """ Adds a unix socket server callback, which will be invoked when values arrive from a connected socket client. The callback must accept two parameters, eg. ``def callback(socket, msg)``. """ if not cal...
[ "def", "add_tcp_callback", "(", "self", ",", "port", ",", "callback", ",", "threaded_callback", "=", "False", ")", ":", "if", "not", "callback", ":", "raise", "AttributeError", "(", "\"No callback\"", ")", "serversocket", "=", "socket", ".", "socket", "(", "...
Adds a unix socket server callback, which will be invoked when values arrive from a connected socket client. The callback must accept two parameters, eg. ``def callback(socket, msg)``.
[ "Adds", "a", "unix", "socket", "server", "callback", "which", "will", "be", "invoked", "when", "values", "arrive", "from", "a", "connected", "socket", "client", ".", "The", "callback", "must", "accept", "two", "parameters", "eg", ".", "def", "callback", "(",...
train
https://github.com/metachris/RPIO/blob/be1942a69b2592ddacd9dc833d2668a19aafd8d2/source/RPIO/_RPIO.py#L91-L112
metachris/RPIO
source/RPIO/_RPIO.py
Interruptor.add_interrupt_callback
def add_interrupt_callback(self, gpio_id, callback, edge='both', pull_up_down=_GPIO.PUD_OFF, threaded_callback=False, debounce_timeout_ms=None): """ Add a callback to be executed when the value on 'gpio_id' changes to the edge specified via the 'edge' parameter (default='...
python
def add_interrupt_callback(self, gpio_id, callback, edge='both', pull_up_down=_GPIO.PUD_OFF, threaded_callback=False, debounce_timeout_ms=None): """ Add a callback to be executed when the value on 'gpio_id' changes to the edge specified via the 'edge' parameter (default='...
[ "def", "add_interrupt_callback", "(", "self", ",", "gpio_id", ",", "callback", ",", "edge", "=", "'both'", ",", "pull_up_down", "=", "_GPIO", ".", "PUD_OFF", ",", "threaded_callback", "=", "False", ",", "debounce_timeout_ms", "=", "None", ")", ":", "gpio_id", ...
Add a callback to be executed when the value on 'gpio_id' changes to the edge specified via the 'edge' parameter (default='both'). `pull_up_down` can be set to `RPIO.PUD_UP`, `RPIO.PUD_DOWN`, and `RPIO.PUD_OFF`. If `threaded_callback` is True, the callback will be started insid...
[ "Add", "a", "callback", "to", "be", "executed", "when", "the", "value", "on", "gpio_id", "changes", "to", "the", "edge", "specified", "via", "the", "edge", "parameter", "(", "default", "=", "both", ")", "." ]
train
https://github.com/metachris/RPIO/blob/be1942a69b2592ddacd9dc833d2668a19aafd8d2/source/RPIO/_RPIO.py#L114-L217
metachris/RPIO
source/RPIO/_RPIO.py
Interruptor.del_interrupt_callback
def del_interrupt_callback(self, gpio_id): """ Delete all interrupt callbacks from a certain gpio """ debug("- removing interrupts on gpio %s" % gpio_id) gpio_id = _GPIO.channel_to_gpio(gpio_id) fileno = self._map_gpioid_to_fileno[gpio_id] # 1. Remove from epoll self._ep...
python
def del_interrupt_callback(self, gpio_id): """ Delete all interrupt callbacks from a certain gpio """ debug("- removing interrupts on gpio %s" % gpio_id) gpio_id = _GPIO.channel_to_gpio(gpio_id) fileno = self._map_gpioid_to_fileno[gpio_id] # 1. Remove from epoll self._ep...
[ "def", "del_interrupt_callback", "(", "self", ",", "gpio_id", ")", ":", "debug", "(", "\"- removing interrupts on gpio %s\"", "%", "gpio_id", ")", "gpio_id", "=", "_GPIO", ".", "channel_to_gpio", "(", "gpio_id", ")", "fileno", "=", "self", ".", "_map_gpioid_to_fil...
Delete all interrupt callbacks from a certain gpio
[ "Delete", "all", "interrupt", "callbacks", "from", "a", "certain", "gpio" ]
train
https://github.com/metachris/RPIO/blob/be1942a69b2592ddacd9dc833d2668a19aafd8d2/source/RPIO/_RPIO.py#L219-L239
metachris/RPIO
source/RPIO/_RPIO.py
Interruptor._handle_interrupt
def _handle_interrupt(self, fileno, val): """ Internally distributes interrupts to all attached callbacks """ val = int(val) # Filter invalid edge values (sometimes 1 comes in when edge=falling) edge = self._map_fileno_to_options[fileno]["edge"] if (edge == 'rising' and val == 0...
python
def _handle_interrupt(self, fileno, val): """ Internally distributes interrupts to all attached callbacks """ val = int(val) # Filter invalid edge values (sometimes 1 comes in when edge=falling) edge = self._map_fileno_to_options[fileno]["edge"] if (edge == 'rising' and val == 0...
[ "def", "_handle_interrupt", "(", "self", ",", "fileno", ",", "val", ")", ":", "val", "=", "int", "(", "val", ")", "# Filter invalid edge values (sometimes 1 comes in when edge=falling)", "edge", "=", "self", ".", "_map_fileno_to_options", "[", "fileno", "]", "[", ...
Internally distributes interrupts to all attached callbacks
[ "Internally", "distributes", "interrupts", "to", "all", "attached", "callbacks" ]
train
https://github.com/metachris/RPIO/blob/be1942a69b2592ddacd9dc833d2668a19aafd8d2/source/RPIO/_RPIO.py#L241-L264
metachris/RPIO
source/RPIO/_RPIO.py
Interruptor.wait_for_interrupts
def wait_for_interrupts(self, epoll_timeout=1): """ Blocking loop to listen for GPIO interrupts and distribute them to associated callbacks. epoll_timeout is an easy way to shutdown the blocking function. Per default the timeout is set to 1 second; if `_is_waiting_for_interrupts`...
python
def wait_for_interrupts(self, epoll_timeout=1): """ Blocking loop to listen for GPIO interrupts and distribute them to associated callbacks. epoll_timeout is an easy way to shutdown the blocking function. Per default the timeout is set to 1 second; if `_is_waiting_for_interrupts`...
[ "def", "wait_for_interrupts", "(", "self", ",", "epoll_timeout", "=", "1", ")", ":", "self", ".", "_is_waiting_for_interrupts", "=", "True", "while", "self", ".", "_is_waiting_for_interrupts", ":", "events", "=", "self", ".", "_epoll", ".", "poll", "(", "epoll...
Blocking loop to listen for GPIO interrupts and distribute them to associated callbacks. epoll_timeout is an easy way to shutdown the blocking function. Per default the timeout is set to 1 second; if `_is_waiting_for_interrupts` is set to False the loop will exit. If an exception occurs...
[ "Blocking", "loop", "to", "listen", "for", "GPIO", "interrupts", "and", "distribute", "them", "to", "associated", "callbacks", ".", "epoll_timeout", "is", "an", "easy", "way", "to", "shutdown", "the", "blocking", "function", ".", "Per", "default", "the", "time...
train
https://github.com/metachris/RPIO/blob/be1942a69b2592ddacd9dc833d2668a19aafd8d2/source/RPIO/_RPIO.py#L273-L322
metachris/RPIO
source/RPIO/_RPIO.py
Interruptor.cleanup_interfaces
def cleanup_interfaces(self): """ Removes all /sys/class/gpio/gpioN interfaces that this script created, and deletes callback bindings. Should be used after using interrupts. """ debug("Cleaning up interfaces...") for gpio_id in self._gpio_kernel_interfaces_created: ...
python
def cleanup_interfaces(self): """ Removes all /sys/class/gpio/gpioN interfaces that this script created, and deletes callback bindings. Should be used after using interrupts. """ debug("Cleaning up interfaces...") for gpio_id in self._gpio_kernel_interfaces_created: ...
[ "def", "cleanup_interfaces", "(", "self", ")", ":", "debug", "(", "\"Cleaning up interfaces...\"", ")", "for", "gpio_id", "in", "self", ".", "_gpio_kernel_interfaces_created", ":", "# Close the value-file and remove interrupt bindings", "self", ".", "del_interrupt_callback", ...
Removes all /sys/class/gpio/gpioN interfaces that this script created, and deletes callback bindings. Should be used after using interrupts.
[ "Removes", "all", "/", "sys", "/", "class", "/", "gpio", "/", "gpioN", "interfaces", "that", "this", "script", "created", "and", "deletes", "callback", "bindings", ".", "Should", "be", "used", "after", "using", "interrupts", "." ]
train
https://github.com/metachris/RPIO/blob/be1942a69b2592ddacd9dc833d2668a19aafd8d2/source/RPIO/_RPIO.py#L331-L347
metachris/RPIO
source/RPIO/_RPIO.py
Interruptor.cleanup_tcpsockets
def cleanup_tcpsockets(self): """ Closes all TCP connections and then the socket servers """ for fileno in self._tcp_client_sockets.keys(): self.close_tcp_client(fileno) for fileno, items in self._tcp_server_sockets.items(): socket, cb = items ...
python
def cleanup_tcpsockets(self): """ Closes all TCP connections and then the socket servers """ for fileno in self._tcp_client_sockets.keys(): self.close_tcp_client(fileno) for fileno, items in self._tcp_server_sockets.items(): socket, cb = items ...
[ "def", "cleanup_tcpsockets", "(", "self", ")", ":", "for", "fileno", "in", "self", ".", "_tcp_client_sockets", ".", "keys", "(", ")", ":", "self", ".", "close_tcp_client", "(", "fileno", ")", "for", "fileno", ",", "items", "in", "self", ".", "_tcp_server_s...
Closes all TCP connections and then the socket servers
[ "Closes", "all", "TCP", "connections", "and", "then", "the", "socket", "servers" ]
train
https://github.com/metachris/RPIO/blob/be1942a69b2592ddacd9dc833d2668a19aafd8d2/source/RPIO/_RPIO.py#L349-L360
metachris/RPIO
source/RPIO/PWM/__init__.py
add_channel_pulse
def add_channel_pulse(dma_channel, gpio, start, width): """ Add a pulse for a specific GPIO to a dma channel subcycle. `start` and `width` are multiples of the pulse-width increment granularity. """ return _PWM.add_channel_pulse(dma_channel, gpio, start, width)
python
def add_channel_pulse(dma_channel, gpio, start, width): """ Add a pulse for a specific GPIO to a dma channel subcycle. `start` and `width` are multiples of the pulse-width increment granularity. """ return _PWM.add_channel_pulse(dma_channel, gpio, start, width)
[ "def", "add_channel_pulse", "(", "dma_channel", ",", "gpio", ",", "start", ",", "width", ")", ":", "return", "_PWM", ".", "add_channel_pulse", "(", "dma_channel", ",", "gpio", ",", "start", ",", "width", ")" ]
Add a pulse for a specific GPIO to a dma channel subcycle. `start` and `width` are multiples of the pulse-width increment granularity.
[ "Add", "a", "pulse", "for", "a", "specific", "GPIO", "to", "a", "dma", "channel", "subcycle", ".", "start", "and", "width", "are", "multiples", "of", "the", "pulse", "-", "width", "increment", "granularity", "." ]
train
https://github.com/metachris/RPIO/blob/be1942a69b2592ddacd9dc833d2668a19aafd8d2/source/RPIO/PWM/__init__.py#L110-L115
metachris/RPIO
source/RPIO/PWM/__init__.py
Servo.set_servo
def set_servo(self, gpio, pulse_width_us): """ Sets a pulse-width on a gpio to repeat every subcycle (by default every 20ms). """ # Make sure we can set the exact pulse_width_us _pulse_incr_us = _PWM.get_pulse_incr_us() if pulse_width_us % _pulse_incr_us: ...
python
def set_servo(self, gpio, pulse_width_us): """ Sets a pulse-width on a gpio to repeat every subcycle (by default every 20ms). """ # Make sure we can set the exact pulse_width_us _pulse_incr_us = _PWM.get_pulse_incr_us() if pulse_width_us % _pulse_incr_us: ...
[ "def", "set_servo", "(", "self", ",", "gpio", ",", "pulse_width_us", ")", ":", "# Make sure we can set the exact pulse_width_us", "_pulse_incr_us", "=", "_PWM", ".", "get_pulse_incr_us", "(", ")", "if", "pulse_width_us", "%", "_pulse_incr_us", ":", "# No clean division ...
Sets a pulse-width on a gpio to repeat every subcycle (by default every 20ms).
[ "Sets", "a", "pulse", "-", "width", "on", "a", "gpio", "to", "repeat", "every", "subcycle", "(", "by", "default", "every", "20ms", ")", "." ]
train
https://github.com/metachris/RPIO/blob/be1942a69b2592ddacd9dc833d2668a19aafd8d2/source/RPIO/PWM/__init__.py#L190-L216
macbre/sql-metadata
sql_metadata.py
unique
def unique(_list): """ Makes the list have unique items only and maintains the order list(set()) won't provide that :type _list list :rtype: list """ ret = [] for item in _list: if item not in ret: ret.append(item) return ret
python
def unique(_list): """ Makes the list have unique items only and maintains the order list(set()) won't provide that :type _list list :rtype: list """ ret = [] for item in _list: if item not in ret: ret.append(item) return ret
[ "def", "unique", "(", "_list", ")", ":", "ret", "=", "[", "]", "for", "item", "in", "_list", ":", "if", "item", "not", "in", "ret", ":", "ret", ".", "append", "(", "item", ")", "return", "ret" ]
Makes the list have unique items only and maintains the order list(set()) won't provide that :type _list list :rtype: list
[ "Makes", "the", "list", "have", "unique", "items", "only", "and", "maintains", "the", "order" ]
train
https://github.com/macbre/sql-metadata/blob/4b7b4ae0a961d568075aefe78535cf5aee74583c/sql_metadata.py#L12-L27
macbre/sql-metadata
sql_metadata.py
preprocess_query
def preprocess_query(query): """ Perform initial query cleanup :type query str :rtype str """ # 1. remove aliases # FROM `dimension_wikis` `dw` # INNER JOIN `fact_wam_scores` `fwN` query = re.sub(r'(\s(FROM|JOIN)\s`[^`]+`)\s`[^`]+`', r'\1', query, flags=re.IGNORECASE) # 2. `dat...
python
def preprocess_query(query): """ Perform initial query cleanup :type query str :rtype str """ # 1. remove aliases # FROM `dimension_wikis` `dw` # INNER JOIN `fact_wam_scores` `fwN` query = re.sub(r'(\s(FROM|JOIN)\s`[^`]+`)\s`[^`]+`', r'\1', query, flags=re.IGNORECASE) # 2. `dat...
[ "def", "preprocess_query", "(", "query", ")", ":", "# 1. remove aliases", "# FROM `dimension_wikis` `dw`", "# INNER JOIN `fact_wam_scores` `fwN`", "query", "=", "re", ".", "sub", "(", "r'(\\s(FROM|JOIN)\\s`[^`]+`)\\s`[^`]+`'", ",", "r'\\1'", ",", "query", ",", "flags", "=...
Perform initial query cleanup :type query str :rtype str
[ "Perform", "initial", "query", "cleanup" ]
train
https://github.com/macbre/sql-metadata/blob/4b7b4ae0a961d568075aefe78535cf5aee74583c/sql_metadata.py#L30-L48
macbre/sql-metadata
sql_metadata.py
get_query_tokens
def get_query_tokens(query): """ :type query str :rtype: list[sqlparse.sql.Token] """ query = preprocess_query(query) parsed = sqlparse.parse(query) # handle empty queries (#12) if not parsed: return [] tokens = TokenList(parsed[0].tokens).flatten() # print([(token.valu...
python
def get_query_tokens(query): """ :type query str :rtype: list[sqlparse.sql.Token] """ query = preprocess_query(query) parsed = sqlparse.parse(query) # handle empty queries (#12) if not parsed: return [] tokens = TokenList(parsed[0].tokens).flatten() # print([(token.valu...
[ "def", "get_query_tokens", "(", "query", ")", ":", "query", "=", "preprocess_query", "(", "query", ")", "parsed", "=", "sqlparse", ".", "parse", "(", "query", ")", "# handle empty queries (#12)", "if", "not", "parsed", ":", "return", "[", "]", "tokens", "=",...
:type query str :rtype: list[sqlparse.sql.Token]
[ ":", "type", "query", "str", ":", "rtype", ":", "list", "[", "sqlparse", ".", "sql", ".", "Token", "]" ]
train
https://github.com/macbre/sql-metadata/blob/4b7b4ae0a961d568075aefe78535cf5aee74583c/sql_metadata.py#L51-L66
macbre/sql-metadata
sql_metadata.py
get_query_columns
def get_query_columns(query): """ :type query str :rtype: list[str] """ columns = [] last_keyword = None last_token = None # print(preprocess_query(query)) # these keywords should not change the state of a parser # and not "reset" previously found SELECT keyword keywords_ig...
python
def get_query_columns(query): """ :type query str :rtype: list[str] """ columns = [] last_keyword = None last_token = None # print(preprocess_query(query)) # these keywords should not change the state of a parser # and not "reset" previously found SELECT keyword keywords_ig...
[ "def", "get_query_columns", "(", "query", ")", ":", "columns", "=", "[", "]", "last_keyword", "=", "None", "last_token", "=", "None", "# print(preprocess_query(query))", "# these keywords should not change the state of a parser", "# and not \"reset\" previously found SELECT keywo...
:type query str :rtype: list[str]
[ ":", "type", "query", "str", ":", "rtype", ":", "list", "[", "str", "]" ]
train
https://github.com/macbre/sql-metadata/blob/4b7b4ae0a961d568075aefe78535cf5aee74583c/sql_metadata.py#L69-L128
macbre/sql-metadata
sql_metadata.py
get_query_tables
def get_query_tables(query): """ :type query str :rtype: list[str] """ tables = [] last_keyword = None last_token = None table_syntax_keywords = [ # SELECT queries 'FROM', 'WHERE', 'JOIN', 'INNER JOIN', 'LEFT JOIN', 'RIGHT JOIN', 'ON', # INSERT queries 'I...
python
def get_query_tables(query): """ :type query str :rtype: list[str] """ tables = [] last_keyword = None last_token = None table_syntax_keywords = [ # SELECT queries 'FROM', 'WHERE', 'JOIN', 'INNER JOIN', 'LEFT JOIN', 'RIGHT JOIN', 'ON', # INSERT queries 'I...
[ "def", "get_query_tables", "(", "query", ")", ":", "tables", "=", "[", "]", "last_keyword", "=", "None", "last_token", "=", "None", "table_syntax_keywords", "=", "[", "# SELECT queries", "'FROM'", ",", "'WHERE'", ",", "'JOIN'", ",", "'INNER JOIN'", ",", "'LEFT...
:type query str :rtype: list[str]
[ ":", "type", "query", "str", ":", "rtype", ":", "list", "[", "str", "]" ]
train
https://github.com/macbre/sql-metadata/blob/4b7b4ae0a961d568075aefe78535cf5aee74583c/sql_metadata.py#L131-L193
macbre/sql-metadata
sql_metadata.py
get_query_limit_and_offset
def get_query_limit_and_offset(query): """ :type query str :rtype: (int, int) """ limit = None offset = None last_keyword = None last_token = None # print(query) for token in get_query_tokens(query): # print([token, token.ttype, last_keyword]) if token.is_keywor...
python
def get_query_limit_and_offset(query): """ :type query str :rtype: (int, int) """ limit = None offset = None last_keyword = None last_token = None # print(query) for token in get_query_tokens(query): # print([token, token.ttype, last_keyword]) if token.is_keywor...
[ "def", "get_query_limit_and_offset", "(", "query", ")", ":", "limit", "=", "None", "offset", "=", "None", "last_keyword", "=", "None", "last_token", "=", "None", "# print(query)", "for", "token", "in", "get_query_tokens", "(", "query", ")", ":", "# print([token,...
:type query str :rtype: (int, int)
[ ":", "type", "query", "str", ":", "rtype", ":", "(", "int", "int", ")" ]
train
https://github.com/macbre/sql-metadata/blob/4b7b4ae0a961d568075aefe78535cf5aee74583c/sql_metadata.py#L196-L232
macbre/sql-metadata
sql_metadata.py
normalize_likes
def normalize_likes(sql): """ Normalize and wrap LIKE statements :type sql str :rtype: str """ sql = sql.replace('%', '') # LIKE '%bot' sql = re.sub(r"LIKE '[^\']+'", 'LIKE X', sql) # or all_groups LIKE X or all_groups LIKE X matches = re.finditer(r'(or|and) [^\s]+ LIKE X', sq...
python
def normalize_likes(sql): """ Normalize and wrap LIKE statements :type sql str :rtype: str """ sql = sql.replace('%', '') # LIKE '%bot' sql = re.sub(r"LIKE '[^\']+'", 'LIKE X', sql) # or all_groups LIKE X or all_groups LIKE X matches = re.finditer(r'(or|and) [^\s]+ LIKE X', sq...
[ "def", "normalize_likes", "(", "sql", ")", ":", "sql", "=", "sql", ".", "replace", "(", "'%'", ",", "''", ")", "# LIKE '%bot'", "sql", "=", "re", ".", "sub", "(", "r\"LIKE '[^\\']+'\"", ",", "'LIKE X'", ",", "sql", ")", "# or all_groups LIKE X or all_groups ...
Normalize and wrap LIKE statements :type sql str :rtype: str
[ "Normalize", "and", "wrap", "LIKE", "statements" ]
train
https://github.com/macbre/sql-metadata/blob/4b7b4ae0a961d568075aefe78535cf5aee74583c/sql_metadata.py#L236-L256
macbre/sql-metadata
sql_metadata.py
generalize_sql
def generalize_sql(sql): """ Removes most variables from an SQL query and replaces them with X or N for numbers. Based on Mediawiki's DatabaseBase::generalizeSQL :type sql str|None :rtype: str """ if sql is None: return None # multiple spaces sql = re.sub(r'\s{2,}', ' ', s...
python
def generalize_sql(sql): """ Removes most variables from an SQL query and replaces them with X or N for numbers. Based on Mediawiki's DatabaseBase::generalizeSQL :type sql str|None :rtype: str """ if sql is None: return None # multiple spaces sql = re.sub(r'\s{2,}', ' ', s...
[ "def", "generalize_sql", "(", "sql", ")", ":", "if", "sql", "is", "None", ":", "return", "None", "# multiple spaces", "sql", "=", "re", ".", "sub", "(", "r'\\s{2,}'", ",", "' '", ",", "sql", ")", "# MW comments", "# e.g. /* CategoryDataService::getMostVisited N....
Removes most variables from an SQL query and replaces them with X or N for numbers. Based on Mediawiki's DatabaseBase::generalizeSQL :type sql str|None :rtype: str
[ "Removes", "most", "variables", "from", "an", "SQL", "query", "and", "replaces", "them", "with", "X", "or", "N", "for", "numbers", "." ]
train
https://github.com/macbre/sql-metadata/blob/4b7b4ae0a961d568075aefe78535cf5aee74583c/sql_metadata.py#L269-L306
biocore/deblur
deblur/parallel_deblur.py
deblur_system_call
def deblur_system_call(params, input_fp): """Build deblur command for subprocess. Parameters ---------- params: list of str parameter settings to pass to deblur CLI input_fp : str name of the input fasta file to deblur Returns ------- stdout: string process outp...
python
def deblur_system_call(params, input_fp): """Build deblur command for subprocess. Parameters ---------- params: list of str parameter settings to pass to deblur CLI input_fp : str name of the input fasta file to deblur Returns ------- stdout: string process outp...
[ "def", "deblur_system_call", "(", "params", ",", "input_fp", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "logger", ".", "debug", "(", "'[%s] deblur system call params %s, input_fp %s'", "%", "(", "mp", ".", "current_process", "(", ...
Build deblur command for subprocess. Parameters ---------- params: list of str parameter settings to pass to deblur CLI input_fp : str name of the input fasta file to deblur Returns ------- stdout: string process output directed to standard output stderr: string...
[ "Build", "deblur", "command", "for", "subprocess", "." ]
train
https://github.com/biocore/deblur/blob/4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b/deblur/parallel_deblur.py#L17-L53
biocore/deblur
deblur/parallel_deblur.py
run_functor
def run_functor(functor, *args, **kwargs): """ Given a functor, run it and return its result. We can use this with multiprocessing.map and map it over a list of job functors to do them. Handles getting more than multiprocessing's pitiful exception output This function was derived from: http://...
python
def run_functor(functor, *args, **kwargs): """ Given a functor, run it and return its result. We can use this with multiprocessing.map and map it over a list of job functors to do them. Handles getting more than multiprocessing's pitiful exception output This function was derived from: http://...
[ "def", "run_functor", "(", "functor", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "# This is where you do your actual work", "return", "functor", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "Exception", ":", "# Put all exce...
Given a functor, run it and return its result. We can use this with multiprocessing.map and map it over a list of job functors to do them. Handles getting more than multiprocessing's pitiful exception output This function was derived from: http://stackoverflow.com/a/16618842/19741 This code was a...
[ "Given", "a", "functor", "run", "it", "and", "return", "its", "result", ".", "We", "can", "use", "this", "with", "multiprocessing", ".", "map", "and", "map", "it", "over", "a", "list", "of", "job", "functors", "to", "do", "them", "." ]
train
https://github.com/biocore/deblur/blob/4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b/deblur/parallel_deblur.py#L56-L74
biocore/deblur
deblur/parallel_deblur.py
parallel_deblur
def parallel_deblur(inputs, params, pos_ref_db_fp, neg_ref_dp_fp, jobs_to_start=1): """Dispatch execution over a pool of processors This code was adopted from the American Gut project: https://github.com/biocore/American-Gut/blob/master/americangut/parallel.py Parameters ------...
python
def parallel_deblur(inputs, params, pos_ref_db_fp, neg_ref_dp_fp, jobs_to_start=1): """Dispatch execution over a pool of processors This code was adopted from the American Gut project: https://github.com/biocore/American-Gut/blob/master/americangut/parallel.py Parameters ------...
[ "def", "parallel_deblur", "(", "inputs", ",", "params", ",", "pos_ref_db_fp", ",", "neg_ref_dp_fp", ",", "jobs_to_start", "=", "1", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "logger", ".", "info", "(", "'parallel deblur starte...
Dispatch execution over a pool of processors This code was adopted from the American Gut project: https://github.com/biocore/American-Gut/blob/master/americangut/parallel.py Parameters ---------- inputs : iterable of str File paths to input per-sample sequence files params : list of st...
[ "Dispatch", "execution", "over", "a", "pool", "of", "processors" ]
train
https://github.com/biocore/deblur/blob/4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b/deblur/parallel_deblur.py#L77-L142
biocore/deblur
deblur/workflow.py
sequence_generator
def sequence_generator(input_fp): """Yield (id, sequence) from an input file Parameters ---------- input_fp : filepath A filepath, which can be any valid fasta or fastq file within the limitations of scikit-bio's IO registry. Notes ----- The use of this method is a stopgap ...
python
def sequence_generator(input_fp): """Yield (id, sequence) from an input file Parameters ---------- input_fp : filepath A filepath, which can be any valid fasta or fastq file within the limitations of scikit-bio's IO registry. Notes ----- The use of this method is a stopgap ...
[ "def", "sequence_generator", "(", "input_fp", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "kw", "=", "{", "}", "if", "sniff_fasta", "(", "input_fp", ")", "[", "0", "]", ":", "format", "=", "'fasta'", "elif", "sniff_fastq",...
Yield (id, sequence) from an input file Parameters ---------- input_fp : filepath A filepath, which can be any valid fasta or fastq file within the limitations of scikit-bio's IO registry. Notes ----- The use of this method is a stopgap to replicate the existing `parse_fasta` ...
[ "Yield", "(", "id", "sequence", ")", "from", "an", "input", "file" ]
train
https://github.com/biocore/deblur/blob/4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b/deblur/workflow.py#L54-L100
biocore/deblur
deblur/workflow.py
trim_seqs
def trim_seqs(input_seqs, trim_len, left_trim_len): """Trim FASTA sequences to specified length. Parameters ---------- input_seqs : iterable of (str, str) The list of input sequences in (label, sequence) format trim_len : int Sequence trimming length. Specify a value of -1 to disabl...
python
def trim_seqs(input_seqs, trim_len, left_trim_len): """Trim FASTA sequences to specified length. Parameters ---------- input_seqs : iterable of (str, str) The list of input sequences in (label, sequence) format trim_len : int Sequence trimming length. Specify a value of -1 to disabl...
[ "def", "trim_seqs", "(", "input_seqs", ",", "trim_len", ",", "left_trim_len", ")", ":", "# counters for the number of trimmed and total sequences", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "okseqs", "=", "0", "totseqs", "=", "0", "if", "tr...
Trim FASTA sequences to specified length. Parameters ---------- input_seqs : iterable of (str, str) The list of input sequences in (label, sequence) format trim_len : int Sequence trimming length. Specify a value of -1 to disable trimming. left_trim_len : int Sequence trimmi...
[ "Trim", "FASTA", "sequences", "to", "specified", "length", "." ]
train
https://github.com/biocore/deblur/blob/4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b/deblur/workflow.py#L103-L150
biocore/deblur
deblur/workflow.py
dereplicate_seqs
def dereplicate_seqs(seqs_fp, output_fp, min_size=2, use_log=False, threads=1): """Dereplicate FASTA sequences and remove singletons using VSEARCH. Parameters ---------- seqs_fp : string filepath to FASTA sequen...
python
def dereplicate_seqs(seqs_fp, output_fp, min_size=2, use_log=False, threads=1): """Dereplicate FASTA sequences and remove singletons using VSEARCH. Parameters ---------- seqs_fp : string filepath to FASTA sequen...
[ "def", "dereplicate_seqs", "(", "seqs_fp", ",", "output_fp", ",", "min_size", "=", "2", ",", "use_log", "=", "False", ",", "threads", "=", "1", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "logger", ".", "info", "(", "'de...
Dereplicate FASTA sequences and remove singletons using VSEARCH. Parameters ---------- seqs_fp : string filepath to FASTA sequence file output_fp : string file path to dereplicated sequences (FASTA format) min_size : integer, optional discard sequences with an abundance valu...
[ "Dereplicate", "FASTA", "sequences", "and", "remove", "singletons", "using", "VSEARCH", "." ]
train
https://github.com/biocore/deblur/blob/4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b/deblur/workflow.py#L153-L193
biocore/deblur
deblur/workflow.py
build_index_sortmerna
def build_index_sortmerna(ref_fp, working_dir): """Build a SortMeRNA index for all reference databases. Parameters ---------- ref_fp: tuple filepaths to FASTA reference databases working_dir: string working directory path where to store the indexed database Returns ------- ...
python
def build_index_sortmerna(ref_fp, working_dir): """Build a SortMeRNA index for all reference databases. Parameters ---------- ref_fp: tuple filepaths to FASTA reference databases working_dir: string working directory path where to store the indexed database Returns ------- ...
[ "def", "build_index_sortmerna", "(", "ref_fp", ",", "working_dir", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "logger", ".", "info", "(", "'build_index_sortmerna files %s to'", "' dir %s'", "%", "(", "ref_fp", ",", "working_dir", ...
Build a SortMeRNA index for all reference databases. Parameters ---------- ref_fp: tuple filepaths to FASTA reference databases working_dir: string working directory path where to store the indexed database Returns ------- all_db: tuple filepaths to SortMeRNA indexe...
[ "Build", "a", "SortMeRNA", "index", "for", "all", "reference", "databases", "." ]
train
https://github.com/biocore/deblur/blob/4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b/deblur/workflow.py#L196-L232
biocore/deblur
deblur/workflow.py
filter_minreads_samples_from_table
def filter_minreads_samples_from_table(table, minreads=1, inplace=True): """Filter samples from biom table that have less than minreads reads total Paraneters ---------- table : biom.Table the biom table to filter minreads : int (optional) the minimal number of reads in a sample...
python
def filter_minreads_samples_from_table(table, minreads=1, inplace=True): """Filter samples from biom table that have less than minreads reads total Paraneters ---------- table : biom.Table the biom table to filter minreads : int (optional) the minimal number of reads in a sample...
[ "def", "filter_minreads_samples_from_table", "(", "table", ",", "minreads", "=", "1", ",", "inplace", "=", "True", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "logger", ".", "debug", "(", "'filter_minreads_started. minreads=%d'", ...
Filter samples from biom table that have less than minreads reads total Paraneters ---------- table : biom.Table the biom table to filter minreads : int (optional) the minimal number of reads in a sample in order to keep it inplace : bool (optional) if True, filter the b...
[ "Filter", "samples", "from", "biom", "table", "that", "have", "less", "than", "minreads", "reads", "total" ]
train
https://github.com/biocore/deblur/blob/4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b/deblur/workflow.py#L235-L265
biocore/deblur
deblur/workflow.py
fasta_from_biom
def fasta_from_biom(table, fasta_file_name): '''Save sequences from a biom table to a fasta file Parameters ---------- table : biom.Table The biom table containing the sequences fasta_file_name : str Name of the fasta output file ''' logger = logging.getLogger(__name__) ...
python
def fasta_from_biom(table, fasta_file_name): '''Save sequences from a biom table to a fasta file Parameters ---------- table : biom.Table The biom table containing the sequences fasta_file_name : str Name of the fasta output file ''' logger = logging.getLogger(__name__) ...
[ "def", "fasta_from_biom", "(", "table", ",", "fasta_file_name", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "logger", ".", "debug", "(", "'saving biom table sequences to fasta file %s'", "%", "fasta_file_name", ")", "with", "open", ...
Save sequences from a biom table to a fasta file Parameters ---------- table : biom.Table The biom table containing the sequences fasta_file_name : str Name of the fasta output file
[ "Save", "sequences", "from", "a", "biom", "table", "to", "a", "fasta", "file" ]
train
https://github.com/biocore/deblur/blob/4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b/deblur/workflow.py#L268-L284
biocore/deblur
deblur/workflow.py
remove_artifacts_from_biom_table
def remove_artifacts_from_biom_table(table_filename, fasta_filename, ref_fp, biom_table_dir, ref_db_fp, threads=1, ...
python
def remove_artifacts_from_biom_table(table_filename, fasta_filename, ref_fp, biom_table_dir, ref_db_fp, threads=1, ...
[ "def", "remove_artifacts_from_biom_table", "(", "table_filename", ",", "fasta_filename", ",", "ref_fp", ",", "biom_table_dir", ",", "ref_db_fp", ",", "threads", "=", "1", ",", "verbose", "=", "False", ",", "sim_thresh", "=", "None", ",", "coverage_thresh", "=", ...
Remove artifacts from a biom table using SortMeRNA Parameters ---------- table : str name of the biom table file fasta_filename : str the fasta file containing all the sequences of the biom table Returns ------- tmp_files : list of str The temp files created during ...
[ "Remove", "artifacts", "from", "a", "biom", "table", "using", "SortMeRNA" ]
train
https://github.com/biocore/deblur/blob/4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b/deblur/workflow.py#L287-L363
biocore/deblur
deblur/workflow.py
remove_artifacts_seqs
def remove_artifacts_seqs(seqs_fp, ref_fp, working_dir, ref_db_fp, negate=False, threads=1, verbose=False, sim_thresh=None, ...
python
def remove_artifacts_seqs(seqs_fp, ref_fp, working_dir, ref_db_fp, negate=False, threads=1, verbose=False, sim_thresh=None, ...
[ "def", "remove_artifacts_seqs", "(", "seqs_fp", ",", "ref_fp", ",", "working_dir", ",", "ref_db_fp", ",", "negate", "=", "False", ",", "threads", "=", "1", ",", "verbose", "=", "False", ",", "sim_thresh", "=", "None", ",", "coverage_thresh", "=", "None", "...
Remove artifacts from FASTA file using SortMeRNA. Parameters ---------- seqs_fp: string file path to FASTA input sequence file ref_fp: tuple file path(s) to FASTA database file working_dir: string working directory path ref_db_fp: tuple file path(s) to indexed FA...
[ "Remove", "artifacts", "from", "FASTA", "file", "using", "SortMeRNA", "." ]
train
https://github.com/biocore/deblur/blob/4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b/deblur/workflow.py#L366-L493
biocore/deblur
deblur/workflow.py
multiple_sequence_alignment
def multiple_sequence_alignment(seqs_fp, threads=1): """Perform multiple sequence alignment on FASTA file using MAFFT. Parameters ---------- seqs_fp: string filepath to FASTA file for multiple sequence alignment threads: integer, optional number of threads to use. 0 to use all threa...
python
def multiple_sequence_alignment(seqs_fp, threads=1): """Perform multiple sequence alignment on FASTA file using MAFFT. Parameters ---------- seqs_fp: string filepath to FASTA file for multiple sequence alignment threads: integer, optional number of threads to use. 0 to use all threa...
[ "def", "multiple_sequence_alignment", "(", "seqs_fp", ",", "threads", "=", "1", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "logger", ".", "info", "(", "'multiple_sequence_alignment seqs file %s'", "%", "seqs_fp", ")", "# for mafft ...
Perform multiple sequence alignment on FASTA file using MAFFT. Parameters ---------- seqs_fp: string filepath to FASTA file for multiple sequence alignment threads: integer, optional number of threads to use. 0 to use all threads Returns ------- msa_fp : str name of...
[ "Perform", "multiple", "sequence", "alignment", "on", "FASTA", "file", "using", "MAFFT", "." ]
train
https://github.com/biocore/deblur/blob/4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b/deblur/workflow.py#L496-L529
biocore/deblur
deblur/workflow.py
remove_chimeras_denovo_from_seqs
def remove_chimeras_denovo_from_seqs(seqs_fp, working_dir, threads=1): """Remove chimeras de novo using UCHIME (VSEARCH implementation). Parameters ---------- seqs_fp: string file path to FASTA input sequence file output_fp: string file path to store chimera-free results threads...
python
def remove_chimeras_denovo_from_seqs(seqs_fp, working_dir, threads=1): """Remove chimeras de novo using UCHIME (VSEARCH implementation). Parameters ---------- seqs_fp: string file path to FASTA input sequence file output_fp: string file path to store chimera-free results threads...
[ "def", "remove_chimeras_denovo_from_seqs", "(", "seqs_fp", ",", "working_dir", ",", "threads", "=", "1", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "logger", ".", "info", "(", "'remove_chimeras_denovo_from_seqs seqs file %s'", "'to w...
Remove chimeras de novo using UCHIME (VSEARCH implementation). Parameters ---------- seqs_fp: string file path to FASTA input sequence file output_fp: string file path to store chimera-free results threads : int number of threads (0 for all cores) Returns ------- ...
[ "Remove", "chimeras", "de", "novo", "using", "UCHIME", "(", "VSEARCH", "implementation", ")", "." ]
train
https://github.com/biocore/deblur/blob/4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b/deblur/workflow.py#L532-L570
biocore/deblur
deblur/workflow.py
split_sequence_file_on_sample_ids_to_files
def split_sequence_file_on_sample_ids_to_files(seqs, outdir): """Split FASTA file on sample IDs. Parameters ---------- seqs: file handler file handler to demultiplexed FASTA file outdir: string dirpath to output split FASTA files ""...
python
def split_sequence_file_on_sample_ids_to_files(seqs, outdir): """Split FASTA file on sample IDs. Parameters ---------- seqs: file handler file handler to demultiplexed FASTA file outdir: string dirpath to output split FASTA files ""...
[ "def", "split_sequence_file_on_sample_ids_to_files", "(", "seqs", ",", "outdir", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "logger", ".", "info", "(", "'split_sequence_file_on_sample_ids_to_files'", "' for file %s into dir %s'", "%", "(...
Split FASTA file on sample IDs. Parameters ---------- seqs: file handler file handler to demultiplexed FASTA file outdir: string dirpath to output split FASTA files
[ "Split", "FASTA", "file", "on", "sample", "IDs", "." ]
train
https://github.com/biocore/deblur/blob/4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b/deblur/workflow.py#L596-L621
biocore/deblur
deblur/workflow.py
write_biom_table
def write_biom_table(table, biom_fp): """Write BIOM table to file. Parameters ---------- table: biom.table an instance of a BIOM table biom_fp: string filepath to output BIOM table """ logger = logging.getLogger(__name__) logger.debug('write_biom_table to file %s' % biom...
python
def write_biom_table(table, biom_fp): """Write BIOM table to file. Parameters ---------- table: biom.table an instance of a BIOM table biom_fp: string filepath to output BIOM table """ logger = logging.getLogger(__name__) logger.debug('write_biom_table to file %s' % biom...
[ "def", "write_biom_table", "(", "table", ",", "biom_fp", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "logger", ".", "debug", "(", "'write_biom_table to file %s'", "%", "biom_fp", ")", "with", "biom_open", "(", "biom_fp", ",", ...
Write BIOM table to file. Parameters ---------- table: biom.table an instance of a BIOM table biom_fp: string filepath to output BIOM table
[ "Write", "BIOM", "table", "to", "file", "." ]
train
https://github.com/biocore/deblur/blob/4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b/deblur/workflow.py#L624-L638
biocore/deblur
deblur/workflow.py
get_files_for_table
def get_files_for_table(input_dir, file_end='.trim.derep.no_artifacts' '.msa.deblur.no_chimeras'): """Get a list of files to add to the output table Parameters: ----------- input_dir : string name of the directory containing the deblurred fasta fi...
python
def get_files_for_table(input_dir, file_end='.trim.derep.no_artifacts' '.msa.deblur.no_chimeras'): """Get a list of files to add to the output table Parameters: ----------- input_dir : string name of the directory containing the deblurred fasta fi...
[ "def", "get_files_for_table", "(", "input_dir", ",", "file_end", "=", "'.trim.derep.no_artifacts'", "'.msa.deblur.no_chimeras'", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "logger", ".", "debug", "(", "'get_files_for_table input dir %s, ...
Get a list of files to add to the output table Parameters: ----------- input_dir : string name of the directory containing the deblurred fasta files file_end : string the ending of all the fasta files to be added to the table (default '.fasta.trim.derep.no_artifacts.msa.deblur.n...
[ "Get", "a", "list", "of", "files", "to", "add", "to", "the", "output", "table" ]
train
https://github.com/biocore/deblur/blob/4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b/deblur/workflow.py#L641-L673
biocore/deblur
deblur/workflow.py
create_otu_table
def create_otu_table(output_fp, deblurred_list, outputfasta_fp=None, minreads=0): """Create a biom table out of all files in a directory Parameters ---------- output_fp : string filepath to output BIOM table deblurred_list : list of (str, str) list of file names...
python
def create_otu_table(output_fp, deblurred_list, outputfasta_fp=None, minreads=0): """Create a biom table out of all files in a directory Parameters ---------- output_fp : string filepath to output BIOM table deblurred_list : list of (str, str) list of file names...
[ "def", "create_otu_table", "(", "output_fp", ",", "deblurred_list", ",", "outputfasta_fp", "=", "None", ",", "minreads", "=", "0", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "logger", ".", "info", "(", "'create_otu_table for %d...
Create a biom table out of all files in a directory Parameters ---------- output_fp : string filepath to output BIOM table deblurred_list : list of (str, str) list of file names (including path), sampleid of all deblurred fasta files to add to the table outputfasta_fp : str,...
[ "Create", "a", "biom", "table", "out", "of", "all", "files", "in", "a", "directory" ]
train
https://github.com/biocore/deblur/blob/4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b/deblur/workflow.py#L676-L774
biocore/deblur
deblur/workflow.py
launch_workflow
def launch_workflow(seqs_fp, working_dir, mean_error, error_dist, indel_prob, indel_max, trim_length, left_trim_length, min_size, ref_fp, ref_db_fp, threads_per_sample=1, sim_thresh=None, coverage_thresh=None): """Launch full deblur workflow for a single p...
python
def launch_workflow(seqs_fp, working_dir, mean_error, error_dist, indel_prob, indel_max, trim_length, left_trim_length, min_size, ref_fp, ref_db_fp, threads_per_sample=1, sim_thresh=None, coverage_thresh=None): """Launch full deblur workflow for a single p...
[ "def", "launch_workflow", "(", "seqs_fp", ",", "working_dir", ",", "mean_error", ",", "error_dist", ",", "indel_prob", ",", "indel_max", ",", "trim_length", ",", "left_trim_length", ",", "min_size", ",", "ref_fp", ",", "ref_db_fp", ",", "threads_per_sample", "=", ...
Launch full deblur workflow for a single post split-libraries fasta file Parameters ---------- seqs_fp: string a post split library fasta file for debluring working_dir: string working directory path mean_error: float mean error for original sequence estimate error_dist:...
[ "Launch", "full", "deblur", "workflow", "for", "a", "single", "post", "split", "-", "libraries", "fasta", "file" ]
train
https://github.com/biocore/deblur/blob/4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b/deblur/workflow.py#L777-L895
biocore/deblur
deblur/workflow.py
start_log
def start_log(level=logging.DEBUG, filename=None): """start the logger for the run Parameters ---------- level : int, optional logging.DEBUG, logging.INFO etc. for the log level (between 0-50). filename : str, optional name of the filename to save the log to or None (default) to...
python
def start_log(level=logging.DEBUG, filename=None): """start the logger for the run Parameters ---------- level : int, optional logging.DEBUG, logging.INFO etc. for the log level (between 0-50). filename : str, optional name of the filename to save the log to or None (default) to...
[ "def", "start_log", "(", "level", "=", "logging", ".", "DEBUG", ",", "filename", "=", "None", ")", ":", "if", "filename", "is", "None", ":", "tstr", "=", "time", ".", "ctime", "(", ")", "tstr", "=", "tstr", ".", "replace", "(", "' '", ",", "'.'", ...
start the logger for the run Parameters ---------- level : int, optional logging.DEBUG, logging.INFO etc. for the log level (between 0-50). filename : str, optional name of the filename to save the log to or None (default) to use deblur.log.TIMESTAMP
[ "start", "the", "logger", "for", "the", "run" ]
train
https://github.com/biocore/deblur/blob/4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b/deblur/workflow.py#L898-L919
biocore/deblur
deblur/workflow.py
_system_call
def _system_call(cmd, stdoutfilename=None): """Execute the command `cmd` Parameters ---------- cmd : str The string containing the command to be run. stdoutfilename : str Name of the file to save stdout to or None (default) to not save to file stderrfilename : str ...
python
def _system_call(cmd, stdoutfilename=None): """Execute the command `cmd` Parameters ---------- cmd : str The string containing the command to be run. stdoutfilename : str Name of the file to save stdout to or None (default) to not save to file stderrfilename : str ...
[ "def", "_system_call", "(", "cmd", ",", "stdoutfilename", "=", "None", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "logger", ".", "debug", "(", "'system call: %s'", "%", "cmd", ")", "if", "stdoutfilename", ":", "with", "open...
Execute the command `cmd` Parameters ---------- cmd : str The string containing the command to be run. stdoutfilename : str Name of the file to save stdout to or None (default) to not save to file stderrfilename : str Name of the file to save stderr to or None ...
[ "Execute", "the", "command", "cmd", "Parameters", "----------", "cmd", ":", "str", "The", "string", "containing", "the", "command", "to", "be", "run", ".", "stdoutfilename", ":", "str", "Name", "of", "the", "file", "to", "save", "stdout", "to", "or", "None...
train
https://github.com/biocore/deblur/blob/4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b/deblur/workflow.py#L922-L965
biocore/deblur
deblur/deblurring.py
get_sequences
def get_sequences(input_seqs): """Returns a list of Sequences Parameters ---------- input_seqs : iterable of (str, str) The list of input sequences in (label, sequence) format Returns ------- list of Sequence Raises ------ ValueError If no sequences where found...
python
def get_sequences(input_seqs): """Returns a list of Sequences Parameters ---------- input_seqs : iterable of (str, str) The list of input sequences in (label, sequence) format Returns ------- list of Sequence Raises ------ ValueError If no sequences where found...
[ "def", "get_sequences", "(", "input_seqs", ")", ":", "try", ":", "seqs", "=", "[", "Sequence", "(", "id", ",", "seq", ")", "for", "id", ",", "seq", "in", "input_seqs", "]", "except", "Exception", ":", "seqs", "=", "[", "]", "if", "len", "(", "seqs"...
Returns a list of Sequences Parameters ---------- input_seqs : iterable of (str, str) The list of input sequences in (label, sequence) format Returns ------- list of Sequence Raises ------ ValueError If no sequences where found in `input_seqs` If all the se...
[ "Returns", "a", "list", "of", "Sequences" ]
train
https://github.com/biocore/deblur/blob/4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b/deblur/deblurring.py#L27-L68
biocore/deblur
deblur/deblurring.py
deblur
def deblur(input_seqs, mean_error=0.005, error_dist=None, indel_prob=0.01, indel_max=3): """Deblur the reads Parameters ---------- input_seqs : iterable of (str, str) The list of input sequences in (label, sequence) format. The label should include the sequence cou...
python
def deblur(input_seqs, mean_error=0.005, error_dist=None, indel_prob=0.01, indel_max=3): """Deblur the reads Parameters ---------- input_seqs : iterable of (str, str) The list of input sequences in (label, sequence) format. The label should include the sequence cou...
[ "def", "deblur", "(", "input_seqs", ",", "mean_error", "=", "0.005", ",", "error_dist", "=", "None", ",", "indel_prob", "=", "0.01", ",", "indel_max", "=", "3", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "if", "error_dist...
Deblur the reads Parameters ---------- input_seqs : iterable of (str, str) The list of input sequences in (label, sequence) format. The label should include the sequence count in the 'size=X' format. mean_error : float, optional The mean illumina error, used for original sequenc...
[ "Deblur", "the", "reads" ]
train
https://github.com/biocore/deblur/blob/4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b/deblur/deblurring.py#L71-L189
biocore/deblur
deblur/sequence.py
Sequence.to_fasta
def to_fasta(self): """Returns a string with the sequence in fasta format Returns ------- str The FASTA representation of the sequence """ prefix, suffix = re.split('(?<=size=)\w+', self.label, maxsplit=1) new_count = int(round(self.frequency)) ...
python
def to_fasta(self): """Returns a string with the sequence in fasta format Returns ------- str The FASTA representation of the sequence """ prefix, suffix = re.split('(?<=size=)\w+', self.label, maxsplit=1) new_count = int(round(self.frequency)) ...
[ "def", "to_fasta", "(", "self", ")", ":", "prefix", ",", "suffix", "=", "re", ".", "split", "(", "'(?<=size=)\\w+'", ",", "self", ".", "label", ",", "maxsplit", "=", "1", ")", "new_count", "=", "int", "(", "round", "(", "self", ".", "frequency", ")",...
Returns a string with the sequence in fasta format Returns ------- str The FASTA representation of the sequence
[ "Returns", "a", "string", "with", "the", "sequence", "in", "fasta", "format" ]
train
https://github.com/biocore/deblur/blob/4b4badccdbac8fe9d8f8b3f1349f3700e31b5d7b/deblur/sequence.py#L58-L69
asyncee/django-easy-select2
easy_select2/widgets.py
Select2Mixin.render_select2_options_code
def render_select2_options_code(self, options, id_): """Render options for select2.""" output = [] for key, value in options.items(): if isinstance(value, (dict, list)): value = json.dumps(value) output.append("data-{name}='{value}'".format( ...
python
def render_select2_options_code(self, options, id_): """Render options for select2.""" output = [] for key, value in options.items(): if isinstance(value, (dict, list)): value = json.dumps(value) output.append("data-{name}='{value}'".format( ...
[ "def", "render_select2_options_code", "(", "self", ",", "options", ",", "id_", ")", ":", "output", "=", "[", "]", "for", "key", ",", "value", "in", "options", ".", "items", "(", ")", ":", "if", "isinstance", "(", "value", ",", "(", "dict", ",", "list...
Render options for select2.
[ "Render", "options", "for", "select2", "." ]
train
https://github.com/asyncee/django-easy-select2/blob/f81bbaa91d0266029be7ef6d075d85f13273e3a5/easy_select2/widgets.py#L76-L85
asyncee/django-easy-select2
easy_select2/widgets.py
Select2Mixin.render_js_code
def render_js_code(self, id_, *args, **kwargs): """Render html container for Select2 widget with options.""" if id_: options = self.render_select2_options_code( dict(self.get_options()), id_) return mark_safe(self.html.format(id=id_, options=options)) ...
python
def render_js_code(self, id_, *args, **kwargs): """Render html container for Select2 widget with options.""" if id_: options = self.render_select2_options_code( dict(self.get_options()), id_) return mark_safe(self.html.format(id=id_, options=options)) ...
[ "def", "render_js_code", "(", "self", ",", "id_", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "id_", ":", "options", "=", "self", ".", "render_select2_options_code", "(", "dict", "(", "self", ".", "get_options", "(", ")", ")", ",", "id...
Render html container for Select2 widget with options.
[ "Render", "html", "container", "for", "Select2", "widget", "with", "options", "." ]
train
https://github.com/asyncee/django-easy-select2/blob/f81bbaa91d0266029be7ef6d075d85f13273e3a5/easy_select2/widgets.py#L87-L93
asyncee/django-easy-select2
easy_select2/widgets.py
Select2Mixin.render
def render(self, name, value, attrs=None, **kwargs): """ Extend base class's `render` method by appending javascript inline text to html output. """ output = super(Select2Mixin, self).render( name, value, attrs=attrs, **kwargs) id_ = attrs['id'] output...
python
def render(self, name, value, attrs=None, **kwargs): """ Extend base class's `render` method by appending javascript inline text to html output. """ output = super(Select2Mixin, self).render( name, value, attrs=attrs, **kwargs) id_ = attrs['id'] output...
[ "def", "render", "(", "self", ",", "name", ",", "value", ",", "attrs", "=", "None", ",", "*", "*", "kwargs", ")", ":", "output", "=", "super", "(", "Select2Mixin", ",", "self", ")", ".", "render", "(", "name", ",", "value", ",", "attrs", "=", "at...
Extend base class's `render` method by appending javascript inline text to html output.
[ "Extend", "base", "class", "s", "render", "method", "by", "appending", "javascript", "inline", "text", "to", "html", "output", "." ]
train
https://github.com/asyncee/django-easy-select2/blob/f81bbaa91d0266029be7ef6d075d85f13273e3a5/easy_select2/widgets.py#L95-L105
asyncee/django-easy-select2
docs/source/_ext/djangodocs.py
visit_console_html
def visit_console_html(self, node): """Generate HTML for the console directive.""" if self.builder.name in ('djangohtml', 'json') and node['win_console_text']: # Put a mark on the document object signaling the fact the directive # has been used on it. self.document._console_directive_use...
python
def visit_console_html(self, node): """Generate HTML for the console directive.""" if self.builder.name in ('djangohtml', 'json') and node['win_console_text']: # Put a mark on the document object signaling the fact the directive # has been used on it. self.document._console_directive_use...
[ "def", "visit_console_html", "(", "self", ",", "node", ")", ":", "if", "self", ".", "builder", ".", "name", "in", "(", "'djangohtml'", ",", "'json'", ")", "and", "node", "[", "'win_console_text'", "]", ":", "# Put a mark on the document object signaling the fact t...
Generate HTML for the console directive.
[ "Generate", "HTML", "for", "the", "console", "directive", "." ]
train
https://github.com/asyncee/django-easy-select2/blob/f81bbaa91d0266029be7ef6d075d85f13273e3a5/docs/source/_ext/djangodocs.py#L364-L403
asyncee/django-easy-select2
easy_select2/utils.py
select2_modelform_meta
def select2_modelform_meta(model, meta_fields=None, widgets=None, attrs=None, **kwargs): """ Return `Meta` class with Select2-enabled widgets for fields with choices (e.g. ForeignKey, CharField, etc)...
python
def select2_modelform_meta(model, meta_fields=None, widgets=None, attrs=None, **kwargs): """ Return `Meta` class with Select2-enabled widgets for fields with choices (e.g. ForeignKey, CharField, etc)...
[ "def", "select2_modelform_meta", "(", "model", ",", "meta_fields", "=", "None", ",", "widgets", "=", "None", ",", "attrs", "=", "None", ",", "*", "*", "kwargs", ")", ":", "widgets", "=", "widgets", "or", "{", "}", "meta_fields", "=", "meta_fields", "or",...
Return `Meta` class with Select2-enabled widgets for fields with choices (e.g. ForeignKey, CharField, etc) for use with ModelForm. Arguments: model - a model class to create `Meta` class for. meta_fields - dictionary with `Meta` class fields, for example, {'fields': ['id', 'nam...
[ "Return", "Meta", "class", "with", "Select2", "-", "enabled", "widgets", "for", "fields", "with", "choices", "(", "e", ".", "g", ".", "ForeignKey", "CharField", "etc", ")", "for", "use", "with", "ModelForm", "." ]
train
https://github.com/asyncee/django-easy-select2/blob/f81bbaa91d0266029be7ef6d075d85f13273e3a5/easy_select2/utils.py#L10-L49
asyncee/django-easy-select2
easy_select2/utils.py
select2_modelform
def select2_modelform( model, attrs=None, form_class=es2_forms.FixedModelForm): """ Return ModelForm class for model with select2 widgets. Arguments: attrs: select2 widget attributes (width, for example) of type `dict`. form_class: modelform base class, `forms.ModelForm` by default....
python
def select2_modelform( model, attrs=None, form_class=es2_forms.FixedModelForm): """ Return ModelForm class for model with select2 widgets. Arguments: attrs: select2 widget attributes (width, for example) of type `dict`. form_class: modelform base class, `forms.ModelForm` by default....
[ "def", "select2_modelform", "(", "model", ",", "attrs", "=", "None", ",", "form_class", "=", "es2_forms", ".", "FixedModelForm", ")", ":", "classname", "=", "'%sForm'", "%", "model", ".", "_meta", ".", "object_name", "meta", "=", "select2_modelform_meta", "(",...
Return ModelForm class for model with select2 widgets. Arguments: attrs: select2 widget attributes (width, for example) of type `dict`. form_class: modelform base class, `forms.ModelForm` by default. :: SomeModelForm = select2_modelform(models.SomeModelBanner) is the same like:: ...
[ "Return", "ModelForm", "class", "for", "model", "with", "select2", "widgets", "." ]
train
https://github.com/asyncee/django-easy-select2/blob/f81bbaa91d0266029be7ef6d075d85f13273e3a5/easy_select2/utils.py#L52-L72
scour-project/scour
scour/svg_transform.py
Lexer.lex
def lex(self, text): """ Yield (token_type, str_data) tokens. The last token will be (EOF, None) where EOF is the singleton object defined in this module. """ for match in self.regex.finditer(text): for name, _ in self.lexicon: m = match.group(name) ...
python
def lex(self, text): """ Yield (token_type, str_data) tokens. The last token will be (EOF, None) where EOF is the singleton object defined in this module. """ for match in self.regex.finditer(text): for name, _ in self.lexicon: m = match.group(name) ...
[ "def", "lex", "(", "self", ",", "text", ")", ":", "for", "match", "in", "self", ".", "regex", ".", "finditer", "(", "text", ")", ":", "for", "name", ",", "_", "in", "self", ".", "lexicon", ":", "m", "=", "match", ".", "group", "(", "name", ")",...
Yield (token_type, str_data) tokens. The last token will be (EOF, None) where EOF is the singleton object defined in this module.
[ "Yield", "(", "token_type", "str_data", ")", "tokens", "." ]
train
https://github.com/scour-project/scour/blob/049264eba6b1a54ae5ba1d6a5077d8e7b80e8835/scour/svg_transform.py#L105-L117
scour-project/scour
scour/svg_transform.py
SVGTransformationParser.parse
def parse(self, text): """ Parse a string of SVG transform="" data. """ gen = self.lexer.lex(text) next_val_fn = partial(next, *(gen,)) commands = [] token = next_val_fn() while token[0] is not EOF: command, token = self.rule_svg_transform(next_val_fn...
python
def parse(self, text): """ Parse a string of SVG transform="" data. """ gen = self.lexer.lex(text) next_val_fn = partial(next, *(gen,)) commands = [] token = next_val_fn() while token[0] is not EOF: command, token = self.rule_svg_transform(next_val_fn...
[ "def", "parse", "(", "self", ",", "text", ")", ":", "gen", "=", "self", ".", "lexer", ".", "lex", "(", "text", ")", "next_val_fn", "=", "partial", "(", "next", ",", "*", "(", "gen", ",", ")", ")", "commands", "=", "[", "]", "token", "=", "next_...
Parse a string of SVG transform="" data.
[ "Parse", "a", "string", "of", "SVG", "transform", "=", "data", "." ]
train
https://github.com/scour-project/scour/blob/049264eba6b1a54ae5ba1d6a5077d8e7b80e8835/scour/svg_transform.py#L154-L165
scour-project/scour
scour/svg_regex.py
SVGPathParser.parse
def parse(self, text): """ Parse a string of SVG <path> data. """ gen = self.lexer.lex(text) next_val_fn = partial(next, *(gen,)) token = next_val_fn() return self.rule_svg_path(next_val_fn, token)
python
def parse(self, text): """ Parse a string of SVG <path> data. """ gen = self.lexer.lex(text) next_val_fn = partial(next, *(gen,)) token = next_val_fn() return self.rule_svg_path(next_val_fn, token)
[ "def", "parse", "(", "self", ",", "text", ")", ":", "gen", "=", "self", ".", "lexer", ".", "lex", "(", "text", ")", "next_val_fn", "=", "partial", "(", "next", ",", "*", "(", "gen", ",", ")", ")", "token", "=", "next_val_fn", "(", ")", "return", ...
Parse a string of SVG <path> data.
[ "Parse", "a", "string", "of", "SVG", "<path", ">", "data", "." ]
train
https://github.com/scour-project/scour/blob/049264eba6b1a54ae5ba1d6a5077d8e7b80e8835/scour/svg_regex.py#L154-L160
scour-project/scour
scour/scour.py
findElementsWithId
def findElementsWithId(node, elems=None): """ Returns all elements with id attributes """ if elems is None: elems = {} id = node.getAttribute('id') if id != '': elems[id] = node if node.hasChildNodes(): for child in node.childNodes: # from http://www.w3.or...
python
def findElementsWithId(node, elems=None): """ Returns all elements with id attributes """ if elems is None: elems = {} id = node.getAttribute('id') if id != '': elems[id] = node if node.hasChildNodes(): for child in node.childNodes: # from http://www.w3.or...
[ "def", "findElementsWithId", "(", "node", ",", "elems", "=", "None", ")", ":", "if", "elems", "is", "None", ":", "elems", "=", "{", "}", "id", "=", "node", ".", "getAttribute", "(", "'id'", ")", "if", "id", "!=", "''", ":", "elems", "[", "id", "]...
Returns all elements with id attributes
[ "Returns", "all", "elements", "with", "id", "attributes" ]
train
https://github.com/scour-project/scour/blob/049264eba6b1a54ae5ba1d6a5077d8e7b80e8835/scour/scour.py#L524-L539
scour-project/scour
scour/scour.py
findReferencedElements
def findReferencedElements(node, ids=None): """ Returns IDs of all referenced elements - node is the node at which to start the search. - returns a map which has the id as key and each value is is a list of nodes Currently looks at 'xlink:href' and all attributes in 'referencingProps' """...
python
def findReferencedElements(node, ids=None): """ Returns IDs of all referenced elements - node is the node at which to start the search. - returns a map which has the id as key and each value is is a list of nodes Currently looks at 'xlink:href' and all attributes in 'referencingProps' """...
[ "def", "findReferencedElements", "(", "node", ",", "ids", "=", "None", ")", ":", "global", "referencingProps", "if", "ids", "is", "None", ":", "ids", "=", "{", "}", "# TODO: input argument ids is clunky here (see below how it is called)", "# GZ: alternative to passing dic...
Returns IDs of all referenced elements - node is the node at which to start the search. - returns a map which has the id as key and each value is is a list of nodes Currently looks at 'xlink:href' and all attributes in 'referencingProps'
[ "Returns", "IDs", "of", "all", "referenced", "elements", "-", "node", "is", "the", "node", "at", "which", "to", "start", "the", "search", ".", "-", "returns", "a", "map", "which", "has", "the", "id", "as", "key", "and", "each", "value", "is", "is", "...
train
https://github.com/scour-project/scour/blob/049264eba6b1a54ae5ba1d6a5077d8e7b80e8835/scour/scour.py#L545-L604
scour-project/scour
scour/scour.py
removeUnreferencedElements
def removeUnreferencedElements(doc, keepDefs): """ Removes all unreferenced elements except for <svg>, <font>, <metadata>, <title>, and <desc>. Also vacuums the defs of any non-referenced renderable elements. Returns the number of unreferenced elements removed from the document. """ global _num...
python
def removeUnreferencedElements(doc, keepDefs): """ Removes all unreferenced elements except for <svg>, <font>, <metadata>, <title>, and <desc>. Also vacuums the defs of any non-referenced renderable elements. Returns the number of unreferenced elements removed from the document. """ global _num...
[ "def", "removeUnreferencedElements", "(", "doc", ",", "keepDefs", ")", ":", "global", "_num_elements_removed", "num", "=", "0", "# Remove certain unreferenced elements outside of defs", "removeTags", "=", "[", "'linearGradient'", ",", "'radialGradient'", ",", "'pattern'", ...
Removes all unreferenced elements except for <svg>, <font>, <metadata>, <title>, and <desc>. Also vacuums the defs of any non-referenced renderable elements. Returns the number of unreferenced elements removed from the document.
[ "Removes", "all", "unreferenced", "elements", "except", "for", "<svg", ">", "<font", ">", "<metadata", ">", "<title", ">", "and", "<desc", ">", ".", "Also", "vacuums", "the", "defs", "of", "any", "non", "-", "referenced", "renderable", "elements", "." ]
train
https://github.com/scour-project/scour/blob/049264eba6b1a54ae5ba1d6a5077d8e7b80e8835/scour/scour.py#L656-L690
scour-project/scour
scour/scour.py
shortenIDs
def shortenIDs(doc, prefix, unprotectedElements=None): """ Shortens ID names used in the document. ID names referenced the most often are assigned the shortest ID names. If the list unprotectedElements is provided, only IDs from this list will be shortened. Returns the number of bytes saved by shor...
python
def shortenIDs(doc, prefix, unprotectedElements=None): """ Shortens ID names used in the document. ID names referenced the most often are assigned the shortest ID names. If the list unprotectedElements is provided, only IDs from this list will be shortened. Returns the number of bytes saved by shor...
[ "def", "shortenIDs", "(", "doc", ",", "prefix", ",", "unprotectedElements", "=", "None", ")", ":", "num", "=", "0", "identifiedElements", "=", "findElementsWithId", "(", "doc", ".", "documentElement", ")", "if", "unprotectedElements", "is", "None", ":", "unpro...
Shortens ID names used in the document. ID names referenced the most often are assigned the shortest ID names. If the list unprotectedElements is provided, only IDs from this list will be shortened. Returns the number of bytes saved by shortening ID names in the document.
[ "Shortens", "ID", "names", "used", "in", "the", "document", ".", "ID", "names", "referenced", "the", "most", "often", "are", "assigned", "the", "shortest", "ID", "names", ".", "If", "the", "list", "unprotectedElements", "is", "provided", "only", "IDs", "from...
train
https://github.com/scour-project/scour/blob/049264eba6b1a54ae5ba1d6a5077d8e7b80e8835/scour/scour.py#L693-L735
scour-project/scour
scour/scour.py
intToID
def intToID(idnum, prefix): """ Returns the ID name for the given ID number, spreadsheet-style, i.e. from a to z, then from aa to az, ba to bz, etc., until zz. """ rid = '' while idnum > 0: idnum -= 1 rid = chr((idnum % 26) + ord('a')) + rid idnum = int(idnum / 26) ...
python
def intToID(idnum, prefix): """ Returns the ID name for the given ID number, spreadsheet-style, i.e. from a to z, then from aa to az, ba to bz, etc., until zz. """ rid = '' while idnum > 0: idnum -= 1 rid = chr((idnum % 26) + ord('a')) + rid idnum = int(idnum / 26) ...
[ "def", "intToID", "(", "idnum", ",", "prefix", ")", ":", "rid", "=", "''", "while", "idnum", ">", "0", ":", "idnum", "-=", "1", "rid", "=", "chr", "(", "(", "idnum", "%", "26", ")", "+", "ord", "(", "'a'", ")", ")", "+", "rid", "idnum", "=", ...
Returns the ID name for the given ID number, spreadsheet-style, i.e. from a to z, then from aa to az, ba to bz, etc., until zz.
[ "Returns", "the", "ID", "name", "for", "the", "given", "ID", "number", "spreadsheet", "-", "style", "i", ".", "e", ".", "from", "a", "to", "z", "then", "from", "aa", "to", "az", "ba", "to", "bz", "etc", ".", "until", "zz", "." ]
train
https://github.com/scour-project/scour/blob/049264eba6b1a54ae5ba1d6a5077d8e7b80e8835/scour/scour.py#L738-L750
scour-project/scour
scour/scour.py
renameID
def renameID(doc, idFrom, idTo, identifiedElements, referencedIDs): """ Changes the ID name from idFrom to idTo, on the declaring element as well as all references in the document doc. Updates identifiedElements and referencedIDs. Does not handle the case where idTo is already the ID name of an...
python
def renameID(doc, idFrom, idTo, identifiedElements, referencedIDs): """ Changes the ID name from idFrom to idTo, on the declaring element as well as all references in the document doc. Updates identifiedElements and referencedIDs. Does not handle the case where idTo is already the ID name of an...
[ "def", "renameID", "(", "doc", ",", "idFrom", ",", "idTo", ",", "identifiedElements", ",", "referencedIDs", ")", ":", "num", "=", "0", "definingNode", "=", "identifiedElements", "[", "idFrom", "]", "definingNode", ".", "setAttribute", "(", "\"id\"", ",", "id...
Changes the ID name from idFrom to idTo, on the declaring element as well as all references in the document doc. Updates identifiedElements and referencedIDs. Does not handle the case where idTo is already the ID name of another element in doc. Returns the number of bytes saved by this replacement...
[ "Changes", "the", "ID", "name", "from", "idFrom", "to", "idTo", "on", "the", "declaring", "element", "as", "well", "as", "all", "references", "in", "the", "document", "doc", "." ]
train
https://github.com/scour-project/scour/blob/049264eba6b1a54ae5ba1d6a5077d8e7b80e8835/scour/scour.py#L753-L828
scour-project/scour
scour/scour.py
unprotected_ids
def unprotected_ids(doc, options): u"""Returns a list of unprotected IDs within the document doc.""" identifiedElements = findElementsWithId(doc.documentElement) if not (options.protect_ids_noninkscape or options.protect_ids_list or options.protect_ids_prefix): return identif...
python
def unprotected_ids(doc, options): u"""Returns a list of unprotected IDs within the document doc.""" identifiedElements = findElementsWithId(doc.documentElement) if not (options.protect_ids_noninkscape or options.protect_ids_list or options.protect_ids_prefix): return identif...
[ "def", "unprotected_ids", "(", "doc", ",", "options", ")", ":", "identifiedElements", "=", "findElementsWithId", "(", "doc", ".", "documentElement", ")", "if", "not", "(", "options", ".", "protect_ids_noninkscape", "or", "options", ".", "protect_ids_list", "or", ...
u"""Returns a list of unprotected IDs within the document doc.
[ "u", "Returns", "a", "list", "of", "unprotected", "IDs", "within", "the", "document", "doc", "." ]
train
https://github.com/scour-project/scour/blob/049264eba6b1a54ae5ba1d6a5077d8e7b80e8835/scour/scour.py#L831-L854