repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
3 values
summary
stringlengths
4
350
chriso/gauged
gauged/drivers/sqlite.py
SQLiteDriver.replace_blocks
def replace_blocks(self, blocks): """Replace multiple blocks. blocks must be a list of tuples where each tuple consists of (namespace, offset, key, data, flags)""" start = 0 bulk_insert = self.bulk_insert blocks_len = len(blocks) select = 'SELECT ?,?,?,?,?' query ...
python
def replace_blocks(self, blocks): """Replace multiple blocks. blocks must be a list of tuples where each tuple consists of (namespace, offset, key, data, flags)""" start = 0 bulk_insert = self.bulk_insert blocks_len = len(blocks) select = 'SELECT ?,?,?,?,?' query ...
[ "def", "replace_blocks", "(", "self", ",", "blocks", ")", ":", "start", "=", "0", "bulk_insert", "=", "self", ".", "bulk_insert", "blocks_len", "=", "len", "(", "blocks", ")", "select", "=", "'SELECT ?,?,?,?,?'", "query", "=", "'REPLACE INTO gauged_data (namespa...
Replace multiple blocks. blocks must be a list of tuples where each tuple consists of (namespace, offset, key, data, flags)
[ "Replace", "multiple", "blocks", ".", "blocks", "must", "be", "a", "list", "of", "tuples", "where", "each", "tuple", "consists", "of", "(", "namespace", "offset", "key", "data", "flags", ")" ]
cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976
https://github.com/chriso/gauged/blob/cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976/gauged/drivers/sqlite.py#L90-L105
train
Replace multiple blocks. blocks must be a list of tuples where each tuple consists of namespace offset key data flags
chriso/gauged
gauged/drivers/sqlite.py
SQLiteDriver.insert_or_append_blocks
def insert_or_append_blocks(self, blocks): """Insert multiple blocks. If a block already exists, the data is appended. blocks must be a list of tuples where each tuple consists of (namespace, offset, key, data)""" start = 0 bulk_insert = self.bulk_insert blocks_len = len(...
python
def insert_or_append_blocks(self, blocks): """Insert multiple blocks. If a block already exists, the data is appended. blocks must be a list of tuples where each tuple consists of (namespace, offset, key, data)""" start = 0 bulk_insert = self.bulk_insert blocks_len = len(...
[ "def", "insert_or_append_blocks", "(", "self", ",", "blocks", ")", ":", "start", "=", "0", "bulk_insert", "=", "self", ".", "bulk_insert", "blocks_len", "=", "len", "(", "blocks", ")", "select", "=", "'SELECT ?,?,?,\"\",0'", "query", "=", "'INSERT OR IGNORE INTO...
Insert multiple blocks. If a block already exists, the data is appended. blocks must be a list of tuples where each tuple consists of (namespace, offset, key, data)
[ "Insert", "multiple", "blocks", ".", "If", "a", "block", "already", "exists", "the", "data", "is", "appended", ".", "blocks", "must", "be", "a", "list", "of", "tuples", "where", "each", "tuple", "consists", "of", "(", "namespace", "offset", "key", "data", ...
cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976
https://github.com/chriso/gauged/blob/cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976/gauged/drivers/sqlite.py#L107-L129
train
Insert multiple blocks. If a block already exists the data is appended.
chriso/gauged
gauged/drivers/sqlite.py
SQLiteDriver.get_cache
def get_cache(self, namespace, query_hash, length, start, end): """Get a cached value for the specified date range and query""" query = 'SELECT start, value FROM gauged_cache WHERE namespace = ? ' \ 'AND hash = ? AND length = ? AND start BETWEEN ? AND ?' cursor = self.cursor ...
python
def get_cache(self, namespace, query_hash, length, start, end): """Get a cached value for the specified date range and query""" query = 'SELECT start, value FROM gauged_cache WHERE namespace = ? ' \ 'AND hash = ? AND length = ? AND start BETWEEN ? AND ?' cursor = self.cursor ...
[ "def", "get_cache", "(", "self", ",", "namespace", ",", "query_hash", ",", "length", ",", "start", ",", "end", ")", ":", "query", "=", "'SELECT start, value FROM gauged_cache WHERE namespace = ? '", "'AND hash = ? AND length = ? AND start BETWEEN ? AND ?'", "cursor", "=", ...
Get a cached value for the specified date range and query
[ "Get", "a", "cached", "value", "for", "the", "specified", "date", "range", "and", "query" ]
cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976
https://github.com/chriso/gauged/blob/cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976/gauged/drivers/sqlite.py#L237-L243
train
Get a cached value for the specified date range and query
ColinDuquesnoy/QCrash
qcrash/_dialogs/review.py
DlgReview.review
def review(cls, content, log, parent, window_icon): # pragma: no cover """ Reviews the final bug report. :param content: content of the final report, before review :param parent: parent widget :returns: the reviewed report content or None if the review was ca...
python
def review(cls, content, log, parent, window_icon): # pragma: no cover """ Reviews the final bug report. :param content: content of the final report, before review :param parent: parent widget :returns: the reviewed report content or None if the review was ca...
[ "def", "review", "(", "cls", ",", "content", ",", "log", ",", "parent", ",", "window_icon", ")", ":", "# pragma: no cover", "dlg", "=", "DlgReview", "(", "content", ",", "log", ",", "parent", ",", "window_icon", ")", "if", "dlg", ".", "exec_", "(", ")"...
Reviews the final bug report. :param content: content of the final report, before review :param parent: parent widget :returns: the reviewed report content or None if the review was canceled.
[ "Reviews", "the", "final", "bug", "report", "." ]
775e1b15764e2041a8f9a08bea938e4d6ce817c7
https://github.com/ColinDuquesnoy/QCrash/blob/775e1b15764e2041a8f9a08bea938e4d6ce817c7/qcrash/_dialogs/review.py#L44-L58
train
Reviews the final bug report.
rhazdon/django-sonic-screwdriver
django_sonic_screwdriver/version/version.py
Version.get_version
def get_version(): """ Return version from setup.py """ version_desc = open(os.path.join(os.path.abspath(APISettings.VERSION_FILE))) version_file = version_desc.read() try: version = re.search(r"version=['\"]([^'\"]+)['\"]", version_file).group(1) ...
python
def get_version(): """ Return version from setup.py """ version_desc = open(os.path.join(os.path.abspath(APISettings.VERSION_FILE))) version_file = version_desc.read() try: version = re.search(r"version=['\"]([^'\"]+)['\"]", version_file).group(1) ...
[ "def", "get_version", "(", ")", ":", "version_desc", "=", "open", "(", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "abspath", "(", "APISettings", ".", "VERSION_FILE", ")", ")", ")", "version_file", "=", "version_desc", ".", "read", "("...
Return version from setup.py
[ "Return", "version", "from", "setup", ".", "py" ]
89e885e8c1322fc5c3e0f79b03a55acdc6e63972
https://github.com/rhazdon/django-sonic-screwdriver/blob/89e885e8c1322fc5c3e0f79b03a55acdc6e63972/django_sonic_screwdriver/version/version.py#L13-L30
train
Return version from setup. py
rhazdon/django-sonic-screwdriver
django_sonic_screwdriver/version/version.py
Version.set_version
def set_version(old_version, new_version): """ Write new version into VERSION_FILE """ try: if APISettings.DEBUG: Shell.debug('* ' + old_version + ' --> ' + new_version) return True for line in fileinput.input(os.path.abspath(APISe...
python
def set_version(old_version, new_version): """ Write new version into VERSION_FILE """ try: if APISettings.DEBUG: Shell.debug('* ' + old_version + ' --> ' + new_version) return True for line in fileinput.input(os.path.abspath(APISe...
[ "def", "set_version", "(", "old_version", ",", "new_version", ")", ":", "try", ":", "if", "APISettings", ".", "DEBUG", ":", "Shell", ".", "debug", "(", "'* '", "+", "old_version", "+", "' --> '", "+", "new_version", ")", "return", "True", "for", "line", ...
Write new version into VERSION_FILE
[ "Write", "new", "version", "into", "VERSION_FILE" ]
89e885e8c1322fc5c3e0f79b03a55acdc6e63972
https://github.com/rhazdon/django-sonic-screwdriver/blob/89e885e8c1322fc5c3e0f79b03a55acdc6e63972/django_sonic_screwdriver/version/version.py#L33-L46
train
Write new version into VERSION_FILE
rhazdon/django-sonic-screwdriver
django_sonic_screwdriver/version/version.py
Version.set_major
def set_major(self): """ Increment the major number of project """ old_version = self.get_version() new_version = str(int(old_version.split('.', 5)[0])+1) + '.0.0' self.set_version(old_version, new_version)
python
def set_major(self): """ Increment the major number of project """ old_version = self.get_version() new_version = str(int(old_version.split('.', 5)[0])+1) + '.0.0' self.set_version(old_version, new_version)
[ "def", "set_major", "(", "self", ")", ":", "old_version", "=", "self", ".", "get_version", "(", ")", "new_version", "=", "str", "(", "int", "(", "old_version", ".", "split", "(", "'.'", ",", "5", ")", "[", "0", "]", ")", "+", "1", ")", "+", "'.0....
Increment the major number of project
[ "Increment", "the", "major", "number", "of", "project" ]
89e885e8c1322fc5c3e0f79b03a55acdc6e63972
https://github.com/rhazdon/django-sonic-screwdriver/blob/89e885e8c1322fc5c3e0f79b03a55acdc6e63972/django_sonic_screwdriver/version/version.py#L71-L77
train
Increment the major number of project
rhazdon/django-sonic-screwdriver
django_sonic_screwdriver/version/version.py
Version.set_minor
def set_minor(self): """ Increment the minor number of project """ old_version = self.get_version() new_version = str(int(old_version.split('.', 5)[0])) + '.' + \ str(int(old_version.split('.', 5)[1])+1) + '.0' self.set_version(old_version, new_version)
python
def set_minor(self): """ Increment the minor number of project """ old_version = self.get_version() new_version = str(int(old_version.split('.', 5)[0])) + '.' + \ str(int(old_version.split('.', 5)[1])+1) + '.0' self.set_version(old_version, new_version)
[ "def", "set_minor", "(", "self", ")", ":", "old_version", "=", "self", ".", "get_version", "(", ")", "new_version", "=", "str", "(", "int", "(", "old_version", ".", "split", "(", "'.'", ",", "5", ")", "[", "0", "]", ")", ")", "+", "'.'", "+", "st...
Increment the minor number of project
[ "Increment", "the", "minor", "number", "of", "project" ]
89e885e8c1322fc5c3e0f79b03a55acdc6e63972
https://github.com/rhazdon/django-sonic-screwdriver/blob/89e885e8c1322fc5c3e0f79b03a55acdc6e63972/django_sonic_screwdriver/version/version.py#L79-L86
train
Increment the minor number of project
rhazdon/django-sonic-screwdriver
django_sonic_screwdriver/version/version.py
Version.set_patch
def set_patch(self, pre_release_tag=''): """ Increment the patch number of project :var release_tag describes the tag ('a', 'b', 'rc', ...) :var release_tag_version describes the number behind the 'a', 'b' or 'rc' For e.g.: """ current_version = self.get_version...
python
def set_patch(self, pre_release_tag=''): """ Increment the patch number of project :var release_tag describes the tag ('a', 'b', 'rc', ...) :var release_tag_version describes the number behind the 'a', 'b' or 'rc' For e.g.: """ current_version = self.get_version...
[ "def", "set_patch", "(", "self", ",", "pre_release_tag", "=", "''", ")", ":", "current_version", "=", "self", ".", "get_version", "(", ")", "current_patch", "=", "self", ".", "get_patch_version", "(", "current_version", ")", "current_pre_release_tag", "=", "self...
Increment the patch number of project :var release_tag describes the tag ('a', 'b', 'rc', ...) :var release_tag_version describes the number behind the 'a', 'b' or 'rc' For e.g.:
[ "Increment", "the", "patch", "number", "of", "project" ]
89e885e8c1322fc5c3e0f79b03a55acdc6e63972
https://github.com/rhazdon/django-sonic-screwdriver/blob/89e885e8c1322fc5c3e0f79b03a55acdc6e63972/django_sonic_screwdriver/version/version.py#L88-L134
train
Set the patch number of project based on the current version and the pre_release_tag.
dsoprea/NsqSpinner
nsq/connection.py
_Buffer.flush
def flush(self): """Return all buffered data, and clear the stack.""" (slice_, self.__buffer) = (self.__buffer, '') self.__size = 0 return slice_
python
def flush(self): """Return all buffered data, and clear the stack.""" (slice_, self.__buffer) = (self.__buffer, '') self.__size = 0 return slice_
[ "def", "flush", "(", "self", ")", ":", "(", "slice_", ",", "self", ".", "__buffer", ")", "=", "(", "self", ".", "__buffer", ",", "''", ")", "self", ".", "__size", "=", "0", "return", "slice_" ]
Return all buffered data, and clear the stack.
[ "Return", "all", "buffered", "data", "and", "clear", "the", "stack", "." ]
972237b8ddce737983bfed001fde52e5236be695
https://github.com/dsoprea/NsqSpinner/blob/972237b8ddce737983bfed001fde52e5236be695/nsq/connection.py#L78-L84
train
Return all buffered data and clear the stack.
dsoprea/NsqSpinner
nsq/connection.py
_ManagedConnection.__send_hello
def __send_hello(self): """Initiate the handshake.""" _logger.debug("Saying hello: [%s]", self) self.__c.send(nsq.config.protocol.MAGIC_IDENTIFIER)
python
def __send_hello(self): """Initiate the handshake.""" _logger.debug("Saying hello: [%s]", self) self.__c.send(nsq.config.protocol.MAGIC_IDENTIFIER)
[ "def", "__send_hello", "(", "self", ")", ":", "_logger", ".", "debug", "(", "\"Saying hello: [%s]\"", ",", "self", ")", "self", ".", "__c", ".", "send", "(", "nsq", ".", "config", ".", "protocol", ".", "MAGIC_IDENTIFIER", ")" ]
Initiate the handshake.
[ "Initiate", "the", "handshake", "." ]
972237b8ddce737983bfed001fde52e5236be695
https://github.com/dsoprea/NsqSpinner/blob/972237b8ddce737983bfed001fde52e5236be695/nsq/connection.py#L137-L142
train
Initiate the handshake.
dsoprea/NsqSpinner
nsq/connection.py
_ManagedConnection.__read_frame
def __read_frame(self): """*Attempt* to read a frame. If we get an EAGAIN on the frame header, it'll raise to our caller. If we get it *after* we already got the header, wait-out the rest of the frame. """ if self.__frame_header_cache is None: _logger.debug("Readin...
python
def __read_frame(self): """*Attempt* to read a frame. If we get an EAGAIN on the frame header, it'll raise to our caller. If we get it *after* we already got the header, wait-out the rest of the frame. """ if self.__frame_header_cache is None: _logger.debug("Readin...
[ "def", "__read_frame", "(", "self", ")", ":", "if", "self", ".", "__frame_header_cache", "is", "None", ":", "_logger", ".", "debug", "(", "\"Reading frame header.\"", ")", "(", "length", ",", "frame_type", ")", "=", "struct", ".", "unpack", "(", "'!II'", "...
*Attempt* to read a frame. If we get an EAGAIN on the frame header, it'll raise to our caller. If we get it *after* we already got the header, wait-out the rest of the frame.
[ "*", "Attempt", "*", "to", "read", "a", "frame", ".", "If", "we", "get", "an", "EAGAIN", "on", "the", "frame", "header", "it", "ll", "raise", "to", "our", "caller", ".", "If", "we", "get", "it", "*", "after", "*", "we", "already", "got", "the", "...
972237b8ddce737983bfed001fde52e5236be695
https://github.com/dsoprea/NsqSpinner/blob/972237b8ddce737983bfed001fde52e5236be695/nsq/connection.py#L423-L443
train
Read a single message from the internal buffer.
dsoprea/NsqSpinner
nsq/connection.py
_ManagedConnection.__sender
def __sender(self): """Send-loop.""" # If we're ignoring the quit, the connections will have to be closed # by the server. while (self.__ignore_quit is True or \ self.__nice_quit_ev.is_set() is False) and \ self.__force_quit_ev.is_set() is False: # TODO(du...
python
def __sender(self): """Send-loop.""" # If we're ignoring the quit, the connections will have to be closed # by the server. while (self.__ignore_quit is True or \ self.__nice_quit_ev.is_set() is False) and \ self.__force_quit_ev.is_set() is False: # TODO(du...
[ "def", "__sender", "(", "self", ")", ":", "# If we're ignoring the quit, the connections will have to be closed ", "# by the server.", "while", "(", "self", ".", "__ignore_quit", "is", "True", "or", "self", ".", "__nice_quit_ev", ".", "is_set", "(", ")", "is", "False"...
Send-loop.
[ "Send", "-", "loop", "." ]
972237b8ddce737983bfed001fde52e5236be695
https://github.com/dsoprea/NsqSpinner/blob/972237b8ddce737983bfed001fde52e5236be695/nsq/connection.py#L479-L506
train
Send - loop.
dsoprea/NsqSpinner
nsq/connection.py
_ManagedConnection.__receiver
def __receiver(self): """Receive-loop.""" # If we're ignoring the quit, the connections will have to be closed # by the server. while (self.__ignore_quit is True or \ self.__nice_quit_ev.is_set() is False) and \ self.__force_quit_ev.is_set() is False: # TO...
python
def __receiver(self): """Receive-loop.""" # If we're ignoring the quit, the connections will have to be closed # by the server. while (self.__ignore_quit is True or \ self.__nice_quit_ev.is_set() is False) and \ self.__force_quit_ev.is_set() is False: # TO...
[ "def", "__receiver", "(", "self", ")", ":", "# If we're ignoring the quit, the connections will have to be closed ", "# by the server.", "while", "(", "self", ".", "__ignore_quit", "is", "True", "or", "self", ".", "__nice_quit_ev", ".", "is_set", "(", ")", "is", "Fals...
Receive-loop.
[ "Receive", "-", "loop", "." ]
972237b8ddce737983bfed001fde52e5236be695
https://github.com/dsoprea/NsqSpinner/blob/972237b8ddce737983bfed001fde52e5236be695/nsq/connection.py#L508-L529
train
Receives messages from the server.
dsoprea/NsqSpinner
nsq/connection.py
Connection.run
def run(self): """Connect the server, and maintain the connection. This shall not return until a connection has been determined to absolutely not be available. """ while self.__nice_quit_ev.is_set() is False: self.__connect() _logger.info("Connection re-co...
python
def run(self): """Connect the server, and maintain the connection. This shall not return until a connection has been determined to absolutely not be available. """ while self.__nice_quit_ev.is_set() is False: self.__connect() _logger.info("Connection re-co...
[ "def", "run", "(", "self", ")", ":", "while", "self", ".", "__nice_quit_ev", ".", "is_set", "(", ")", "is", "False", ":", "self", ".", "__connect", "(", ")", "_logger", ".", "info", "(", "\"Connection re-connect loop has terminated: %s\"", ",", "self", ".", ...
Connect the server, and maintain the connection. This shall not return until a connection has been determined to absolutely not be available.
[ "Connect", "the", "server", "and", "maintain", "the", "connection", ".", "This", "shall", "not", "return", "until", "a", "connection", "has", "been", "determined", "to", "absolutely", "not", "be", "available", "." ]
972237b8ddce737983bfed001fde52e5236be695
https://github.com/dsoprea/NsqSpinner/blob/972237b8ddce737983bfed001fde52e5236be695/nsq/connection.py#L598-L607
train
Connect the server and maintain the connection.
YuriyGuts/pygoose
pygoose/kg/io.py
save
def save(obj, filename, protocol=4): """ Serialize an object to disk using pickle protocol. Args: obj: The object to serialize. filename: Path to the output file. protocol: Version of the pickle protocol. """ with open(filename, 'wb') as f: pickle.dump(obj, f, proto...
python
def save(obj, filename, protocol=4): """ Serialize an object to disk using pickle protocol. Args: obj: The object to serialize. filename: Path to the output file. protocol: Version of the pickle protocol. """ with open(filename, 'wb') as f: pickle.dump(obj, f, proto...
[ "def", "save", "(", "obj", ",", "filename", ",", "protocol", "=", "4", ")", ":", "with", "open", "(", "filename", ",", "'wb'", ")", "as", "f", ":", "pickle", ".", "dump", "(", "obj", ",", "f", ",", "protocol", "=", "protocol", ")" ]
Serialize an object to disk using pickle protocol. Args: obj: The object to serialize. filename: Path to the output file. protocol: Version of the pickle protocol.
[ "Serialize", "an", "object", "to", "disk", "using", "pickle", "protocol", "." ]
4d9b8827c6d6c4b79949d1cd653393498c0bb3c2
https://github.com/YuriyGuts/pygoose/blob/4d9b8827c6d6c4b79949d1cd653393498c0bb3c2/pygoose/kg/io.py#L20-L31
train
Serialize an object to disk using pickle protocol.
YuriyGuts/pygoose
pygoose/kg/io.py
load_json
def load_json(filename, **kwargs): """ Load a JSON object from the specified file. Args: filename: Path to the input JSON file. **kwargs: Additional arguments to `json.load`. Returns: The object deserialized from JSON. """ with open(filename, 'r', encoding='utf-8') as ...
python
def load_json(filename, **kwargs): """ Load a JSON object from the specified file. Args: filename: Path to the input JSON file. **kwargs: Additional arguments to `json.load`. Returns: The object deserialized from JSON. """ with open(filename, 'r', encoding='utf-8') as ...
[ "def", "load_json", "(", "filename", ",", "*", "*", "kwargs", ")", ":", "with", "open", "(", "filename", ",", "'r'", ",", "encoding", "=", "'utf-8'", ")", "as", "f", ":", "return", "json", ".", "load", "(", "f", ",", "*", "*", "kwargs", ")" ]
Load a JSON object from the specified file. Args: filename: Path to the input JSON file. **kwargs: Additional arguments to `json.load`. Returns: The object deserialized from JSON.
[ "Load", "a", "JSON", "object", "from", "the", "specified", "file", "." ]
4d9b8827c6d6c4b79949d1cd653393498c0bb3c2
https://github.com/YuriyGuts/pygoose/blob/4d9b8827c6d6c4b79949d1cd653393498c0bb3c2/pygoose/kg/io.py#L34-L47
train
Load a JSON object from the specified file.
YuriyGuts/pygoose
pygoose/kg/io.py
save_json
def save_json(obj, filename, **kwargs): """ Save an object as a JSON file. Args: obj: The object to save. Must be JSON-serializable. filename: Path to the output file. **kwargs: Additional arguments to `json.dump`. """ with open(filename, 'w', encoding='utf-8') as f: ...
python
def save_json(obj, filename, **kwargs): """ Save an object as a JSON file. Args: obj: The object to save. Must be JSON-serializable. filename: Path to the output file. **kwargs: Additional arguments to `json.dump`. """ with open(filename, 'w', encoding='utf-8') as f: ...
[ "def", "save_json", "(", "obj", ",", "filename", ",", "*", "*", "kwargs", ")", ":", "with", "open", "(", "filename", ",", "'w'", ",", "encoding", "=", "'utf-8'", ")", "as", "f", ":", "json", ".", "dump", "(", "obj", ",", "f", ",", "*", "*", "kw...
Save an object as a JSON file. Args: obj: The object to save. Must be JSON-serializable. filename: Path to the output file. **kwargs: Additional arguments to `json.dump`.
[ "Save", "an", "object", "as", "a", "JSON", "file", "." ]
4d9b8827c6d6c4b79949d1cd653393498c0bb3c2
https://github.com/YuriyGuts/pygoose/blob/4d9b8827c6d6c4b79949d1cd653393498c0bb3c2/pygoose/kg/io.py#L50-L61
train
Save an object as a JSON file.
YuriyGuts/pygoose
pygoose/kg/io.py
load_lines
def load_lines(filename): """ Load a text file as an array of lines. Args: filename: Path to the input file. Returns: An array of strings, each representing an individual line. """ with open(filename, 'r', encoding='utf-8') as f: return [line.rstrip('\n') for line in f...
python
def load_lines(filename): """ Load a text file as an array of lines. Args: filename: Path to the input file. Returns: An array of strings, each representing an individual line. """ with open(filename, 'r', encoding='utf-8') as f: return [line.rstrip('\n') for line in f...
[ "def", "load_lines", "(", "filename", ")", ":", "with", "open", "(", "filename", ",", "'r'", ",", "encoding", "=", "'utf-8'", ")", "as", "f", ":", "return", "[", "line", ".", "rstrip", "(", "'\\n'", ")", "for", "line", "in", "f", ".", "readlines", ...
Load a text file as an array of lines. Args: filename: Path to the input file. Returns: An array of strings, each representing an individual line.
[ "Load", "a", "text", "file", "as", "an", "array", "of", "lines", "." ]
4d9b8827c6d6c4b79949d1cd653393498c0bb3c2
https://github.com/YuriyGuts/pygoose/blob/4d9b8827c6d6c4b79949d1cd653393498c0bb3c2/pygoose/kg/io.py#L64-L76
train
Load a text file as an array of strings each representing an individual line.
YuriyGuts/pygoose
pygoose/kg/io.py
save_lines
def save_lines(lines, filename): """ Save an array of lines to a file. Args: lines: An array of strings that will be saved as individual lines. filename: Path to the output file. """ with open(filename, 'w', encoding='utf-8') as f: f.write('\n'.join(lines))
python
def save_lines(lines, filename): """ Save an array of lines to a file. Args: lines: An array of strings that will be saved as individual lines. filename: Path to the output file. """ with open(filename, 'w', encoding='utf-8') as f: f.write('\n'.join(lines))
[ "def", "save_lines", "(", "lines", ",", "filename", ")", ":", "with", "open", "(", "filename", ",", "'w'", ",", "encoding", "=", "'utf-8'", ")", "as", "f", ":", "f", ".", "write", "(", "'\\n'", ".", "join", "(", "lines", ")", ")" ]
Save an array of lines to a file. Args: lines: An array of strings that will be saved as individual lines. filename: Path to the output file.
[ "Save", "an", "array", "of", "lines", "to", "a", "file", "." ]
4d9b8827c6d6c4b79949d1cd653393498c0bb3c2
https://github.com/YuriyGuts/pygoose/blob/4d9b8827c6d6c4b79949d1cd653393498c0bb3c2/pygoose/kg/io.py#L79-L89
train
Save an array of lines to a file.
LEMS/pylems
lems/model/component.py
Property.toxml
def toxml(self): """ Exports this object into a LEMS XML object """ return '<Property name="{0}"'.format(self.name) +\ (' dimension="{0}"'.format(self.dimension) if self.dimension else 'none') +\ (' defaultValue = "{0}"'.format(self.default_value) if self.default_val...
python
def toxml(self): """ Exports this object into a LEMS XML object """ return '<Property name="{0}"'.format(self.name) +\ (' dimension="{0}"'.format(self.dimension) if self.dimension else 'none') +\ (' defaultValue = "{0}"'.format(self.default_value) if self.default_val...
[ "def", "toxml", "(", "self", ")", ":", "return", "'<Property name=\"{0}\"'", ".", "format", "(", "self", ".", "name", ")", "+", "(", "' dimension=\"{0}\"'", ".", "format", "(", "self", ".", "dimension", ")", "if", "self", ".", "dimension", "else", "'none'"...
Exports this object into a LEMS XML object
[ "Exports", "this", "object", "into", "a", "LEMS", "XML", "object" ]
4eeb719d2f23650fe16c38626663b69b5c83818b
https://github.com/LEMS/pylems/blob/4eeb719d2f23650fe16c38626663b69b5c83818b/lems/model/component.py#L128-L136
train
Returns a LEMS XML property name.
LEMS/pylems
lems/model/component.py
DerivedParameter.toxml
def toxml(self): """ Exports this object into a LEMS XML object """ return '<DerivedParameter name="{0}"'.format(self.name) +\ (' dimension="{0}"'.format(self.dimension) if self.dimension else '') +\ (' value="{0}"'.format(self.value) if self.value else '') +\ ...
python
def toxml(self): """ Exports this object into a LEMS XML object """ return '<DerivedParameter name="{0}"'.format(self.name) +\ (' dimension="{0}"'.format(self.dimension) if self.dimension else '') +\ (' value="{0}"'.format(self.value) if self.value else '') +\ ...
[ "def", "toxml", "(", "self", ")", ":", "return", "'<DerivedParameter name=\"{0}\"'", ".", "format", "(", "self", ".", "name", ")", "+", "(", "' dimension=\"{0}\"'", ".", "format", "(", "self", ".", "dimension", ")", "if", "self", ".", "dimension", "else", ...
Exports this object into a LEMS XML object
[ "Exports", "this", "object", "into", "a", "LEMS", "XML", "object" ]
4eeb719d2f23650fe16c38626663b69b5c83818b
https://github.com/LEMS/pylems/blob/4eeb719d2f23650fe16c38626663b69b5c83818b/lems/model/component.py#L207-L215
train
Returns a LEMS XML object representation of this DerivedParameter.
LEMS/pylems
lems/model/component.py
Constant.toxml
def toxml(self): """ Exports this object into a LEMS XML object """ return '<Constant' +\ (' name = "{0}"'.format(self.name) if self.name else '') +\ (' symbol = "{0}"'.format(self.symbol) if self.symbol else '') +\ (' value = "{0}"'.format(self.value) if s...
python
def toxml(self): """ Exports this object into a LEMS XML object """ return '<Constant' +\ (' name = "{0}"'.format(self.name) if self.name else '') +\ (' symbol = "{0}"'.format(self.symbol) if self.symbol else '') +\ (' value = "{0}"'.format(self.value) if s...
[ "def", "toxml", "(", "self", ")", ":", "return", "'<Constant'", "+", "(", "' name = \"{0}\"'", ".", "format", "(", "self", ".", "name", ")", "if", "self", ".", "name", "else", "''", ")", "+", "(", "' symbol = \"{0}\"'", ".", "format", "(", "self", ".",...
Exports this object into a LEMS XML object
[ "Exports", "this", "object", "into", "a", "LEMS", "XML", "object" ]
4eeb719d2f23650fe16c38626663b69b5c83818b
https://github.com/LEMS/pylems/blob/4eeb719d2f23650fe16c38626663b69b5c83818b/lems/model/component.py#L253-L264
train
Returns a LEMS XML string representation of this Constant object.
LEMS/pylems
lems/model/component.py
ComponentRequirement.toxml
def toxml(self): """ Exports this object into a LEMS XML object """ return '<ComponentRequirement name="{0}"'.format(self.name) + '' + \ (' description = "{0}"'.format(self.description) if self.description else '') +\ '/>'
python
def toxml(self): """ Exports this object into a LEMS XML object """ return '<ComponentRequirement name="{0}"'.format(self.name) + '' + \ (' description = "{0}"'.format(self.description) if self.description else '') +\ '/>'
[ "def", "toxml", "(", "self", ")", ":", "return", "'<ComponentRequirement name=\"{0}\"'", ".", "format", "(", "self", ".", "name", ")", "+", "''", "+", "(", "' description = \"{0}\"'", ".", "format", "(", "self", ".", "description", ")", "if", "self", ".", ...
Exports this object into a LEMS XML object
[ "Exports", "this", "object", "into", "a", "LEMS", "XML", "object" ]
4eeb719d2f23650fe16c38626663b69b5c83818b
https://github.com/LEMS/pylems/blob/4eeb719d2f23650fe16c38626663b69b5c83818b/lems/model/component.py#L353-L360
train
Returns a LEMS XML string representation of this component requirement.
LEMS/pylems
lems/model/component.py
ComponentReference.toxml
def toxml(self): """ Exports this object into a LEMS XML object """ return '<ComponentReference name="{0}" type="{1}"'.format(self.name, self.type) + \ (' local = "{0}"'.format(self.local) if self.local else '') + \ '/>'
python
def toxml(self): """ Exports this object into a LEMS XML object """ return '<ComponentReference name="{0}" type="{1}"'.format(self.name, self.type) + \ (' local = "{0}"'.format(self.local) if self.local else '') + \ '/>'
[ "def", "toxml", "(", "self", ")", ":", "return", "'<ComponentReference name=\"{0}\" type=\"{1}\"'", ".", "format", "(", "self", ".", "name", ",", "self", ".", "type", ")", "+", "(", "' local = \"{0}\"'", ".", "format", "(", "self", ".", "local", ")", "if", ...
Exports this object into a LEMS XML object
[ "Exports", "this", "object", "into", "a", "LEMS", "XML", "object" ]
4eeb719d2f23650fe16c38626663b69b5c83818b
https://github.com/LEMS/pylems/blob/4eeb719d2f23650fe16c38626663b69b5c83818b/lems/model/component.py#L604-L611
train
Returns a LEMS XML string representation of this ComponentReference.
LEMS/pylems
lems/model/component.py
Fat.add
def add(self, child): """ Adds a typed child object to the component type. @param child: Child object to be added. """ if isinstance(child, Parameter): self.add_parameter(child) elif isinstance(child, Property): self.add_property(child) e...
python
def add(self, child): """ Adds a typed child object to the component type. @param child: Child object to be added. """ if isinstance(child, Parameter): self.add_parameter(child) elif isinstance(child, Property): self.add_property(child) e...
[ "def", "add", "(", "self", ",", "child", ")", ":", "if", "isinstance", "(", "child", ",", "Parameter", ")", ":", "self", ".", "add_parameter", "(", "child", ")", "elif", "isinstance", "(", "child", ",", "Property", ")", ":", "self", ".", "add_property"...
Adds a typed child object to the component type. @param child: Child object to be added.
[ "Adds", "a", "typed", "child", "object", "to", "the", "component", "type", "." ]
4eeb719d2f23650fe16c38626663b69b5c83818b
https://github.com/LEMS/pylems/blob/4eeb719d2f23650fe16c38626663b69b5c83818b/lems/model/component.py#L906-L946
train
Adds a typed child object to the component type.
LEMS/pylems
lems/model/component.py
ComponentType.toxml
def toxml(self): """ Exports this object into a LEMS XML object """ xmlstr = '<ComponentType name="{0}"'.format(self.name) +\ (' extends="{0}"'.format(self.extends) if self.extends else '') +\ (' description="{0}"'.format(self.description) if self.description else ''...
python
def toxml(self): """ Exports this object into a LEMS XML object """ xmlstr = '<ComponentType name="{0}"'.format(self.name) +\ (' extends="{0}"'.format(self.extends) if self.extends else '') +\ (' description="{0}"'.format(self.description) if self.description else ''...
[ "def", "toxml", "(", "self", ")", ":", "xmlstr", "=", "'<ComponentType name=\"{0}\"'", ".", "format", "(", "self", ".", "name", ")", "+", "(", "' extends=\"{0}\"'", ".", "format", "(", "self", ".", "extends", ")", "if", "self", ".", "extends", "else", "'...
Exports this object into a LEMS XML object
[ "Exports", "this", "object", "into", "a", "LEMS", "XML", "object" ]
4eeb719d2f23650fe16c38626663b69b5c83818b
https://github.com/LEMS/pylems/blob/4eeb719d2f23650fe16c38626663b69b5c83818b/lems/model/component.py#L979-L1056
train
Converts this object into a LEMS XML object.
LEMS/pylems
lems/model/component.py
Component.add
def add(self, child): """ Adds a typed child object to the component. @param child: Child object to be added. """ if isinstance(child, Component): self.add_child(child) else: raise ModelError('Unsupported child element')
python
def add(self, child): """ Adds a typed child object to the component. @param child: Child object to be added. """ if isinstance(child, Component): self.add_child(child) else: raise ModelError('Unsupported child element')
[ "def", "add", "(", "self", ",", "child", ")", ":", "if", "isinstance", "(", "child", ",", "Component", ")", ":", "self", ".", "add_child", "(", "child", ")", "else", ":", "raise", "ModelError", "(", "'Unsupported child element'", ")" ]
Adds a typed child object to the component. @param child: Child object to be added.
[ "Adds", "a", "typed", "child", "object", "to", "the", "component", "." ]
4eeb719d2f23650fe16c38626663b69b5c83818b
https://github.com/LEMS/pylems/blob/4eeb719d2f23650fe16c38626663b69b5c83818b/lems/model/component.py#L1122-L1132
train
Adds a typed child object to the component.
LEMS/pylems
lems/model/component.py
Component.toxml
def toxml(self): """ Exports this object into a LEMS XML object """ xmlstr = '<Component id="{0}" type="{1}"'.format(self.id, self.type) for (k, v) in self.parameters.items(): xmlstr += ' {0}="{1}"'.format(k, v) if self.children: xmlstr += '>' ...
python
def toxml(self): """ Exports this object into a LEMS XML object """ xmlstr = '<Component id="{0}" type="{1}"'.format(self.id, self.type) for (k, v) in self.parameters.items(): xmlstr += ' {0}="{1}"'.format(k, v) if self.children: xmlstr += '>' ...
[ "def", "toxml", "(", "self", ")", ":", "xmlstr", "=", "'<Component id=\"{0}\" type=\"{1}\"'", ".", "format", "(", "self", ".", "id", ",", "self", ".", "type", ")", "for", "(", "k", ",", "v", ")", "in", "self", ".", "parameters", ".", "items", "(", ")...
Exports this object into a LEMS XML object
[ "Exports", "this", "object", "into", "a", "LEMS", "XML", "object" ]
4eeb719d2f23650fe16c38626663b69b5c83818b
https://github.com/LEMS/pylems/blob/4eeb719d2f23650fe16c38626663b69b5c83818b/lems/model/component.py#L1145-L1163
train
Returns a LEMS XML string representation of the object.
LEMS/pylems
lems/model/component.py
FatComponent.add
def add(self, child): """ Adds a typed child object to the component type. @param child: Child object to be added. """ if isinstance(child, FatComponent): self.add_child_component(child) else: Fat.add(self, child)
python
def add(self, child): """ Adds a typed child object to the component type. @param child: Child object to be added. """ if isinstance(child, FatComponent): self.add_child_component(child) else: Fat.add(self, child)
[ "def", "add", "(", "self", ",", "child", ")", ":", "if", "isinstance", "(", "child", ",", "FatComponent", ")", ":", "self", ".", "add_child_component", "(", "child", ")", "else", ":", "Fat", ".", "add", "(", "self", ",", "child", ")" ]
Adds a typed child object to the component type. @param child: Child object to be added.
[ "Adds", "a", "typed", "child", "object", "to", "the", "component", "type", "." ]
4eeb719d2f23650fe16c38626663b69b5c83818b
https://github.com/LEMS/pylems/blob/4eeb719d2f23650fe16c38626663b69b5c83818b/lems/model/component.py#L1212-L1222
train
Adds a typed child object to the component type.
cprogrammer1994/ModernGL.ext.obj
ModernGL/ext/obj/objects.py
Obj.fromstring
def fromstring(data) -> 'Obj': ''' Args: data (str): The obj file content. Returns: Obj: The object. Examples: .. code-block:: python import ModernGL from ModernGL.ext import obj ...
python
def fromstring(data) -> 'Obj': ''' Args: data (str): The obj file content. Returns: Obj: The object. Examples: .. code-block:: python import ModernGL from ModernGL.ext import obj ...
[ "def", "fromstring", "(", "data", ")", "->", "'Obj'", ":", "vert", "=", "[", "]", "text", "=", "[", "]", "norm", "=", "[", "]", "face", "=", "[", "]", "data", "=", "RE_COMMENT", ".", "sub", "(", "'\\n'", ",", "data", ")", "for", "line", "in", ...
Args: data (str): The obj file content. Returns: Obj: The object. Examples: .. code-block:: python import ModernGL from ModernGL.ext import obj content = open('box.obj').read() ...
[ "Args", ":", "data", "(", "str", ")", ":", "The", "obj", "file", "content", "." ]
84ef626166dc9a2520512158f1746c8bac0d95d2
https://github.com/cprogrammer1994/ModernGL.ext.obj/blob/84ef626166dc9a2520512158f1746c8bac0d95d2/ModernGL/ext/obj/objects.py#L83-L174
train
Parses the content of the object file into a ModernGL object.
cprogrammer1994/ModernGL.ext.obj
ModernGL/ext/obj/objects.py
Obj.pack
def pack(self, packer=default_packer) -> bytes: ''' Args: packer (str or lambda): The vertex attributes to pack. Returns: bytes: The packed vertex data. Examples: .. code-block:: python import ModernGL ...
python
def pack(self, packer=default_packer) -> bytes: ''' Args: packer (str or lambda): The vertex attributes to pack. Returns: bytes: The packed vertex data. Examples: .. code-block:: python import ModernGL ...
[ "def", "pack", "(", "self", ",", "packer", "=", "default_packer", ")", "->", "bytes", ":", "if", "isinstance", "(", "packer", ",", "str", ")", ":", "nodes", "=", "packer", ".", "split", "(", ")", "packer", "=", "eval", "(", "PACKER", "%", "(", "len...
Args: packer (str or lambda): The vertex attributes to pack. Returns: bytes: The packed vertex data. Examples: .. code-block:: python import ModernGL from ModernGL.ext import obj mode...
[ "Args", ":", "packer", "(", "str", "or", "lambda", ")", ":", "The", "vertex", "attributes", "to", "pack", "." ]
84ef626166dc9a2520512158f1746c8bac0d95d2
https://github.com/cprogrammer1994/ModernGL.ext.obj/blob/84ef626166dc9a2520512158f1746c8bac0d95d2/ModernGL/ext/obj/objects.py#L182-L230
train
Packs the current object into a byte string.
quikmile/trellio
trellio/pubsub.py
PubSub.publish
async def publish(self, endpoint: str, payload: str): """ Publish to an endpoint. :param str endpoint: Key by which the endpoint is recognised. Subscribers will use this key to listen to events :param str payload: Payload to publish with the event :return...
python
async def publish(self, endpoint: str, payload: str): """ Publish to an endpoint. :param str endpoint: Key by which the endpoint is recognised. Subscribers will use this key to listen to events :param str payload: Payload to publish with the event :return...
[ "async", "def", "publish", "(", "self", ",", "endpoint", ":", "str", ",", "payload", ":", "str", ")", ":", "if", "self", ".", "_conn", "is", "not", "None", ":", "try", ":", "await", "self", ".", "_conn", ".", "publish", "(", "endpoint", ",", "paylo...
Publish to an endpoint. :param str endpoint: Key by which the endpoint is recognised. Subscribers will use this key to listen to events :param str payload: Payload to publish with the event :return: A boolean indicating if the publish was successful
[ "Publish", "to", "an", "endpoint", ".", ":", "param", "str", "endpoint", ":", "Key", "by", "which", "the", "endpoint", "is", "recognised", ".", "Subscribers", "will", "use", "this", "key", "to", "listen", "to", "events", ":", "param", "str", "payload", "...
e8b050077562acf32805fcbb9c0c162248a23c62
https://github.com/quikmile/trellio/blob/e8b050077562acf32805fcbb9c0c162248a23c62/trellio/pubsub.py#L36-L50
train
Publish to an endpoint.
quikmile/trellio
trellio/pubsub.py
PubSub.subscribe
async def subscribe(self, endpoints: list, handler): """ Subscribe to a list of endpoints :param endpoints: List of endpoints the subscribers is interested to subscribe to :type endpoints: list :param handler: The callback to call when a particular event is published. ...
python
async def subscribe(self, endpoints: list, handler): """ Subscribe to a list of endpoints :param endpoints: List of endpoints the subscribers is interested to subscribe to :type endpoints: list :param handler: The callback to call when a particular event is published. ...
[ "async", "def", "subscribe", "(", "self", ",", "endpoints", ":", "list", ",", "handler", ")", ":", "connection", "=", "await", "self", ".", "_get_conn", "(", ")", "subscriber", "=", "await", "connection", ".", "start_subscribe", "(", ")", "await", "subscri...
Subscribe to a list of endpoints :param endpoints: List of endpoints the subscribers is interested to subscribe to :type endpoints: list :param handler: The callback to call when a particular event is published. Must take two arguments, a channel to which the event was pu...
[ "Subscribe", "to", "a", "list", "of", "endpoints", ":", "param", "endpoints", ":", "List", "of", "endpoints", "the", "subscribers", "is", "interested", "to", "subscribe", "to", ":", "type", "endpoints", ":", "list", ":", "param", "handler", ":", "The", "ca...
e8b050077562acf32805fcbb9c0c162248a23c62
https://github.com/quikmile/trellio/blob/e8b050077562acf32805fcbb9c0c162248a23c62/trellio/pubsub.py#L52-L67
train
Subscribe to a list of endpoints
glormph/msstitch
src/app/lookups/sqlite/searchspace.py
SearchSpaceDB.write_peps
def write_peps(self, peps, reverse_seqs): """Writes peps to db. We can reverse to be able to look up peptides that have some amino acids missing at the N-terminal. This way we can still use the index. """ if reverse_seqs: peps = [(x[0][::-1],) for x in peps] c...
python
def write_peps(self, peps, reverse_seqs): """Writes peps to db. We can reverse to be able to look up peptides that have some amino acids missing at the N-terminal. This way we can still use the index. """ if reverse_seqs: peps = [(x[0][::-1],) for x in peps] c...
[ "def", "write_peps", "(", "self", ",", "peps", ",", "reverse_seqs", ")", ":", "if", "reverse_seqs", ":", "peps", "=", "[", "(", "x", "[", "0", "]", "[", ":", ":", "-", "1", "]", ",", ")", "for", "x", "in", "peps", "]", "cursor", "=", "self", ...
Writes peps to db. We can reverse to be able to look up peptides that have some amino acids missing at the N-terminal. This way we can still use the index.
[ "Writes", "peps", "to", "db", ".", "We", "can", "reverse", "to", "be", "able", "to", "look", "up", "peptides", "that", "have", "some", "amino", "acids", "missing", "at", "the", "N", "-", "terminal", ".", "This", "way", "we", "can", "still", "use", "t...
ded7e5cbd813d7797dc9d42805778266e59ff042
https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/lookups/sqlite/searchspace.py#L9-L19
train
Writes the given list of peptides to the database.
glormph/msstitch
src/app/lookups/sqlite/searchspace.py
SearchSpaceDB.check_seq_exists
def check_seq_exists(self, seq, amount_ntermwildcards): """Look up sequence in sqlite DB. Returns True or False if it exists (or not). When looking up a reversed DB with ntermwildcards: we reverse the sequence of the pep and add a LIKE and %-suffix to the query. """ curso...
python
def check_seq_exists(self, seq, amount_ntermwildcards): """Look up sequence in sqlite DB. Returns True or False if it exists (or not). When looking up a reversed DB with ntermwildcards: we reverse the sequence of the pep and add a LIKE and %-suffix to the query. """ curso...
[ "def", "check_seq_exists", "(", "self", ",", "seq", ",", "amount_ntermwildcards", ")", ":", "cursor", "=", "self", ".", "get_cursor", "(", ")", "if", "amount_ntermwildcards", ">", "0", ":", "seq", "=", "seq", "[", ":", ":", "-", "1", "]", "sqlseq", "="...
Look up sequence in sqlite DB. Returns True or False if it exists (or not). When looking up a reversed DB with ntermwildcards: we reverse the sequence of the pep and add a LIKE and %-suffix to the query.
[ "Look", "up", "sequence", "in", "sqlite", "DB", ".", "Returns", "True", "or", "False", "if", "it", "exists", "(", "or", "not", ")", ".", "When", "looking", "up", "a", "reversed", "DB", "with", "ntermwildcards", ":", "we", "reverse", "the", "sequence", ...
ded7e5cbd813d7797dc9d42805778266e59ff042
https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/lookups/sqlite/searchspace.py#L39-L61
train
Check if a sequence exists in sqlite DB. Returns True or False if it doesn t exist.
Erotemic/utool
utool/util_ipynb.py
make_autogen_str
def make_autogen_str(): r""" Returns: str: CommandLine: python -m utool.util_ipynb --exec-make_autogen_str --show Example: >>> # DISABLE_DOCTEST >>> from utool.util_ipynb import * # NOQA >>> import utool as ut >>> result = make_autogen_str() >>>...
python
def make_autogen_str(): r""" Returns: str: CommandLine: python -m utool.util_ipynb --exec-make_autogen_str --show Example: >>> # DISABLE_DOCTEST >>> from utool.util_ipynb import * # NOQA >>> import utool as ut >>> result = make_autogen_str() >>>...
[ "def", "make_autogen_str", "(", ")", ":", "import", "utool", "as", "ut", "def", "get_regen_cmd", "(", ")", ":", "try", ":", "if", "len", "(", "sys", ".", "argv", ")", ">", "0", "and", "ut", ".", "checkpath", "(", "sys", ".", "argv", "[", "0", "]"...
r""" Returns: str: CommandLine: python -m utool.util_ipynb --exec-make_autogen_str --show Example: >>> # DISABLE_DOCTEST >>> from utool.util_ipynb import * # NOQA >>> import utool as ut >>> result = make_autogen_str() >>> print(result)
[ "r", "Returns", ":", "str", ":" ]
3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_ipynb.py#L23-L64
train
r Creates a string that can be used to generate a new version of the current language.
Erotemic/utool
utool/util_ipynb.py
run_ipython_notebook
def run_ipython_notebook(notebook_str): """ References: https://github.com/paulgb/runipy >>> from utool.util_ipynb import * # NOQA """ from runipy.notebook_runner import NotebookRunner import nbformat import logging log_format = '%(asctime)s %(levelname)s: %(message)s' l...
python
def run_ipython_notebook(notebook_str): """ References: https://github.com/paulgb/runipy >>> from utool.util_ipynb import * # NOQA """ from runipy.notebook_runner import NotebookRunner import nbformat import logging log_format = '%(asctime)s %(levelname)s: %(message)s' l...
[ "def", "run_ipython_notebook", "(", "notebook_str", ")", ":", "from", "runipy", ".", "notebook_runner", "import", "NotebookRunner", "import", "nbformat", "import", "logging", "log_format", "=", "'%(asctime)s %(levelname)s: %(message)s'", "log_datefmt", "=", "'%m/%d/%Y %I:%M...
References: https://github.com/paulgb/runipy >>> from utool.util_ipynb import * # NOQA
[ "References", ":", "https", ":", "//", "github", ".", "com", "/", "paulgb", "/", "runipy", ">>>", "from", "utool", ".", "util_ipynb", "import", "*", "#", "NOQA" ]
3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_ipynb.py#L81-L106
train
Runs an IPython notebook
Erotemic/utool
utool/util_ipynb.py
code_cell
def code_cell(sourcecode): r""" Args: sourcecode (str): Returns: str: json formatted ipython notebook code cell CommandLine: python -m ibeis.templates.generate_notebook --exec-code_cell Example: >>> # DISABLE_DOCTEST >>> from ibeis.templates.generate_notebo...
python
def code_cell(sourcecode): r""" Args: sourcecode (str): Returns: str: json formatted ipython notebook code cell CommandLine: python -m ibeis.templates.generate_notebook --exec-code_cell Example: >>> # DISABLE_DOCTEST >>> from ibeis.templates.generate_notebo...
[ "def", "code_cell", "(", "sourcecode", ")", ":", "import", "utool", "as", "ut", "sourcecode", "=", "ut", ".", "remove_codeblock_syntax_sentinals", "(", "sourcecode", ")", "cell_header", "=", "ut", ".", "codeblock", "(", "'''\n {\n \"cell_type\": \"code\...
r""" Args: sourcecode (str): Returns: str: json formatted ipython notebook code cell CommandLine: python -m ibeis.templates.generate_notebook --exec-code_cell Example: >>> # DISABLE_DOCTEST >>> from ibeis.templates.generate_notebook import * # NOQA >>>...
[ "r", "Args", ":", "sourcecode", "(", "str", ")", ":" ]
3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_ipynb.py#L191-L237
train
r Generate a ipython notebook code cell
Erotemic/utool
utool/util_ipynb.py
markdown_cell
def markdown_cell(markdown): r""" Args: markdown (str): Returns: str: json formatted ipython notebook markdown cell CommandLine: python -m ibeis.templates.generate_notebook --exec-markdown_cell Example: >>> # DISABLE_DOCTEST >>> from ibeis.templates.generat...
python
def markdown_cell(markdown): r""" Args: markdown (str): Returns: str: json formatted ipython notebook markdown cell CommandLine: python -m ibeis.templates.generate_notebook --exec-markdown_cell Example: >>> # DISABLE_DOCTEST >>> from ibeis.templates.generat...
[ "def", "markdown_cell", "(", "markdown", ")", ":", "import", "utool", "as", "ut", "markdown_header", "=", "ut", ".", "codeblock", "(", "'''\n {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [\n '''", ")", "markdown_...
r""" Args: markdown (str): Returns: str: json formatted ipython notebook markdown cell CommandLine: python -m ibeis.templates.generate_notebook --exec-markdown_cell Example: >>> # DISABLE_DOCTEST >>> from ibeis.templates.generate_notebook import * # NOQA ...
[ "r", "Args", ":", "markdown", "(", "str", ")", ":" ]
3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_ipynb.py#L240-L275
train
r Converts markdown cell into json formatted ipython notebook markdown cell
Erotemic/utool
utool/util_ipynb.py
make_notebook
def make_notebook(cell_list): """ References: # Change cell width http://stackoverflow.com/questions/21971449/how-do-i-increase-the-cell-width-of-the-ipython-notebook-in-my-browser/24207353#24207353 """ import utool as ut header = ut.codeblock( ''' { "cells":...
python
def make_notebook(cell_list): """ References: # Change cell width http://stackoverflow.com/questions/21971449/how-do-i-increase-the-cell-width-of-the-ipython-notebook-in-my-browser/24207353#24207353 """ import utool as ut header = ut.codeblock( ''' { "cells":...
[ "def", "make_notebook", "(", "cell_list", ")", ":", "import", "utool", "as", "ut", "header", "=", "ut", ".", "codeblock", "(", "'''\n {\n \"cells\": [\n '''", ")", "footer", "=", "ut", ".", "codeblock", "(", "'''\n ],\n \"metadata...
References: # Change cell width http://stackoverflow.com/questions/21971449/how-do-i-increase-the-cell-width-of-the-ipython-notebook-in-my-browser/24207353#24207353
[ "References", ":", "#", "Change", "cell", "width", "http", ":", "//", "stackoverflow", ".", "com", "/", "questions", "/", "21971449", "/", "how", "-", "do", "-", "i", "-", "increase", "-", "the", "-", "cell", "-", "width", "-", "of", "-", "the", "-...
3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_ipynb.py#L278-L327
train
Creates a notebook from a list of cell names.
Erotemic/utool
utool/util_ipynb.py
repr_single_for_md
def repr_single_for_md(s): r""" Args: s (str): Returns: str: str_repr CommandLine: python -m ibeis.templates.generate_notebook --exec-repr_single_for_md --show Example: >>> # DISABLE_DOCTEST >>> from ibeis.templates.generate_notebook import * # NOQA ...
python
def repr_single_for_md(s): r""" Args: s (str): Returns: str: str_repr CommandLine: python -m ibeis.templates.generate_notebook --exec-repr_single_for_md --show Example: >>> # DISABLE_DOCTEST >>> from ibeis.templates.generate_notebook import * # NOQA ...
[ "def", "repr_single_for_md", "(", "s", ")", ":", "import", "utool", "as", "ut", "if", "True", ":", "str_repr", "=", "ut", ".", "reprfunc", "(", "s", ")", "import", "re", "if", "str_repr", ".", "startswith", "(", "'\\''", ")", ":", "dq", "=", "(", "...
r""" Args: s (str): Returns: str: str_repr CommandLine: python -m ibeis.templates.generate_notebook --exec-repr_single_for_md --show Example: >>> # DISABLE_DOCTEST >>> from ibeis.templates.generate_notebook import * # NOQA >>> s = '#HTML(\'<iframe src=...
[ "r", "Args", ":", "s", "(", "str", ")", ":" ]
3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_ipynb.py#L330-L377
train
r Represents a single entry in the current language for the current language.
quikmile/trellio
trellio/bus.py
HTTPBus.send_http_request
def send_http_request(self, app: str, service: str, version: str, method: str, entity: str, params: dict): """ A convenience method that allows you to send a well formatted http request to another service """ host, port, node_id, service_type = self._registry_client.resolve(service, vers...
python
def send_http_request(self, app: str, service: str, version: str, method: str, entity: str, params: dict): """ A convenience method that allows you to send a well formatted http request to another service """ host, port, node_id, service_type = self._registry_client.resolve(service, vers...
[ "def", "send_http_request", "(", "self", ",", "app", ":", "str", ",", "service", ":", "str", ",", "version", ":", "str", ",", "method", ":", "str", ",", "entity", ":", "str", ",", "params", ":", "dict", ")", ":", "host", ",", "port", ",", "node_id"...
A convenience method that allows you to send a well formatted http request to another service
[ "A", "convenience", "method", "that", "allows", "you", "to", "send", "a", "well", "formatted", "http", "request", "to", "another", "service" ]
e8b050077562acf32805fcbb9c0c162248a23c62
https://github.com/quikmile/trellio/blob/e8b050077562acf32805fcbb9c0c162248a23c62/trellio/bus.py#L31-L51
train
A convenience method that allows you to send a well formatted http request to another service
ColinDuquesnoy/QCrash
qcrash/api.py
install_except_hook
def install_except_hook(except_hook=_hooks.except_hook): """ Install an except hook that will show the crash report dialog when an unhandled exception has occured. :param except_hook: except_hook function that will be called on the main thread whenever an unhandled exception occured. The functi...
python
def install_except_hook(except_hook=_hooks.except_hook): """ Install an except hook that will show the crash report dialog when an unhandled exception has occured. :param except_hook: except_hook function that will be called on the main thread whenever an unhandled exception occured. The functi...
[ "def", "install_except_hook", "(", "except_hook", "=", "_hooks", ".", "except_hook", ")", ":", "if", "not", "_backends", ":", "raise", "ValueError", "(", "'no backends found, you must at least install one '", "'backend before calling this function'", ")", "global", "_except...
Install an except hook that will show the crash report dialog when an unhandled exception has occured. :param except_hook: except_hook function that will be called on the main thread whenever an unhandled exception occured. The function takes two parameters: the exception object and the traceba...
[ "Install", "an", "except", "hook", "that", "will", "show", "the", "crash", "report", "dialog", "when", "an", "unhandled", "exception", "has", "occured", "." ]
775e1b15764e2041a8f9a08bea938e4d6ce817c7
https://github.com/ColinDuquesnoy/QCrash/blob/775e1b15764e2041a8f9a08bea938e4d6ce817c7/qcrash/api.py#L36-L49
train
Installs an except hook that will show the crash report dialog when an unhandled exception has occured.
ColinDuquesnoy/QCrash
qcrash/api.py
show_report_dialog
def show_report_dialog(window_title='Report an issue...', window_icon=None, traceback=None, issue_title='', issue_description='', parent=None, modal=None, include_log=True, include_sys_info=True): """ Show the issue report dialog manually. ...
python
def show_report_dialog(window_title='Report an issue...', window_icon=None, traceback=None, issue_title='', issue_description='', parent=None, modal=None, include_log=True, include_sys_info=True): """ Show the issue report dialog manually. ...
[ "def", "show_report_dialog", "(", "window_title", "=", "'Report an issue...'", ",", "window_icon", "=", "None", ",", "traceback", "=", "None", ",", "issue_title", "=", "''", ",", "issue_description", "=", "''", ",", "parent", "=", "None", ",", "modal", "=", ...
Show the issue report dialog manually. :param window_title: Title of dialog window :param window_icon: the icon to use for the dialog window :param traceback: optional traceback string to include in the report. :param issue_title: optional issue title :param issue_description: optional issue descri...
[ "Show", "the", "issue", "report", "dialog", "manually", "." ]
775e1b15764e2041a8f9a08bea938e4d6ce817c7
https://github.com/ColinDuquesnoy/QCrash/blob/775e1b15764e2041a8f9a08bea938e4d6ce817c7/qcrash/api.py#L64-L93
train
Show the issue report dialog manually.
moluwole/Bast
bast/route.py
Route.middleware
def middleware(self, args): """ Appends a Middleware to the route which is to be executed before the route runs """ if self.url[(len(self.url) - 1)] == (self.url_, self.controller, dict(method=self.method, request_type=self.request_type, middleware=None)): self.url.pop() ...
python
def middleware(self, args): """ Appends a Middleware to the route which is to be executed before the route runs """ if self.url[(len(self.url) - 1)] == (self.url_, self.controller, dict(method=self.method, request_type=self.request_type, middleware=None)): self.url.pop() ...
[ "def", "middleware", "(", "self", ",", "args", ")", ":", "if", "self", ".", "url", "[", "(", "len", "(", "self", ".", "url", ")", "-", "1", ")", "]", "==", "(", "self", ".", "url_", ",", "self", ".", "controller", ",", "dict", "(", "method", ...
Appends a Middleware to the route which is to be executed before the route runs
[ "Appends", "a", "Middleware", "to", "the", "route", "which", "is", "to", "be", "executed", "before", "the", "route", "runs" ]
eecf55ae72e6f24af7c101549be0422cd2c1c95a
https://github.com/moluwole/Bast/blob/eecf55ae72e6f24af7c101549be0422cd2c1c95a/bast/route.py#L27-L34
train
Appends a Middleware to the route which runs before the route runs
moluwole/Bast
bast/route.py
Route.get
def get(self, url, controller): """ Gets the Controller and adds the route, controller and method to the url list for GET request """ self.request_type = 'GET' controller_class, controller_method = self.__return_controller__(controller) self.controller = controller_clas...
python
def get(self, url, controller): """ Gets the Controller and adds the route, controller and method to the url list for GET request """ self.request_type = 'GET' controller_class, controller_method = self.__return_controller__(controller) self.controller = controller_clas...
[ "def", "get", "(", "self", ",", "url", ",", "controller", ")", ":", "self", ".", "request_type", "=", "'GET'", "controller_class", ",", "controller_method", "=", "self", ".", "__return_controller__", "(", "controller", ")", "self", ".", "controller", "=", "c...
Gets the Controller and adds the route, controller and method to the url list for GET request
[ "Gets", "the", "Controller", "and", "adds", "the", "route", "controller", "and", "method", "to", "the", "url", "list", "for", "GET", "request" ]
eecf55ae72e6f24af7c101549be0422cd2c1c95a
https://github.com/moluwole/Bast/blob/eecf55ae72e6f24af7c101549be0422cd2c1c95a/bast/route.py#L62-L75
train
Gets the Controller and adds the route controller and method to the url list for GET request
chriso/gauged
gauged/utilities.py
to_bytes
def to_bytes(value): """Get a byte array representing the value""" if isinstance(value, unicode): return value.encode('utf8') elif not isinstance(value, str): return str(value) return value
python
def to_bytes(value): """Get a byte array representing the value""" if isinstance(value, unicode): return value.encode('utf8') elif not isinstance(value, str): return str(value) return value
[ "def", "to_bytes", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "unicode", ")", ":", "return", "value", ".", "encode", "(", "'utf8'", ")", "elif", "not", "isinstance", "(", "value", ",", "str", ")", ":", "return", "str", "(", "value...
Get a byte array representing the value
[ "Get", "a", "byte", "array", "representing", "the", "value" ]
cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976
https://github.com/chriso/gauged/blob/cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976/gauged/utilities.py#L14-L20
train
Get a byte array representing the value
chriso/gauged
gauged/utilities.py
table_repr
def table_repr(columns, rows, data, padding=2): """Generate a table for cli output""" padding = ' ' * padding column_lengths = [len(column) for column in columns] for row in rows: for i, column in enumerate(columns): item = str(data[row][column]) column_lengths[i] = max(l...
python
def table_repr(columns, rows, data, padding=2): """Generate a table for cli output""" padding = ' ' * padding column_lengths = [len(column) for column in columns] for row in rows: for i, column in enumerate(columns): item = str(data[row][column]) column_lengths[i] = max(l...
[ "def", "table_repr", "(", "columns", ",", "rows", ",", "data", ",", "padding", "=", "2", ")", ":", "padding", "=", "' '", "*", "padding", "column_lengths", "=", "[", "len", "(", "column", ")", "for", "column", "in", "columns", "]", "for", "row", "in"...
Generate a table for cli output
[ "Generate", "a", "table", "for", "cli", "output" ]
cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976
https://github.com/chriso/gauged/blob/cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976/gauged/utilities.py#L36-L55
train
Generate a table for cli output
glormph/msstitch
src/app/readers/fasta.py
get_proteins_for_db
def get_proteins_for_db(fastafn): """Runs through fasta file and returns proteins accession nrs, sequences and evidence levels for storage in lookup DB. Duplicate accessions in fasta are accepted and removed by keeping only the last one. """ objects = {} for record in parse_fasta(fastafn): ...
python
def get_proteins_for_db(fastafn): """Runs through fasta file and returns proteins accession nrs, sequences and evidence levels for storage in lookup DB. Duplicate accessions in fasta are accepted and removed by keeping only the last one. """ objects = {} for record in parse_fasta(fastafn): ...
[ "def", "get_proteins_for_db", "(", "fastafn", ")", ":", "objects", "=", "{", "}", "for", "record", "in", "parse_fasta", "(", "fastafn", ")", ":", "objects", "[", "parse_protein_identifier", "(", "record", ")", "]", "=", "record", "return", "(", "(", "(", ...
Runs through fasta file and returns proteins accession nrs, sequences and evidence levels for storage in lookup DB. Duplicate accessions in fasta are accepted and removed by keeping only the last one.
[ "Runs", "through", "fasta", "file", "and", "returns", "proteins", "accession", "nrs", "sequences", "and", "evidence", "levels", "for", "storage", "in", "lookup", "DB", ".", "Duplicate", "accessions", "in", "fasta", "are", "accepted", "and", "removed", "by", "k...
ded7e5cbd813d7797dc9d42805778266e59ff042
https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/readers/fasta.py#L4-L15
train
Runs through a FASTA file and returns proteins accession nrs sequences and evidence levels for storage in lookup DB.
glormph/msstitch
src/app/readers/fasta.py
get_proteins_genes
def get_proteins_genes(fastafn, fastadelim=None, genefield=None): """This returns a tuple of (protein, gene, HGNC symbol, description) from a passed file. If the file is FASTA from ENSEMBL or UniProt, only genes and descriptions are given and symbol will be None. If the file is a ENSEMBL Biomart mapping...
python
def get_proteins_genes(fastafn, fastadelim=None, genefield=None): """This returns a tuple of (protein, gene, HGNC symbol, description) from a passed file. If the file is FASTA from ENSEMBL or UniProt, only genes and descriptions are given and symbol will be None. If the file is a ENSEMBL Biomart mapping...
[ "def", "get_proteins_genes", "(", "fastafn", ",", "fastadelim", "=", "None", ",", "genefield", "=", "None", ")", ":", "with", "open", "(", "fastafn", ")", "as", "fp", ":", "firstline", "=", "next", "(", "fp", ")", ".", "strip", "(", ")", "if", "first...
This returns a tuple of (protein, gene, HGNC symbol, description) from a passed file. If the file is FASTA from ENSEMBL or UniProt, only genes and descriptions are given and symbol will be None. If the file is a ENSEMBL Biomart mapping file it tries to parse that and also return the rest
[ "This", "returns", "a", "tuple", "of", "(", "protein", "gene", "HGNC", "symbol", "description", ")", "from", "a", "passed", "file", ".", "If", "the", "file", "is", "FASTA", "from", "ENSEMBL", "or", "UniProt", "only", "genes", "and", "descriptions", "are", ...
ded7e5cbd813d7797dc9d42805778266e59ff042
https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/readers/fasta.py#L38-L60
train
This function returns a tuple of protein gene HGNC symbol and description from a Biomart mapping file.
glormph/msstitch
src/app/readers/fasta.py
get_uniprot_evidence_level
def get_uniprot_evidence_level(header): """Returns uniprot protein existence evidence level for a fasta header. Evidence levels are 1-5, but we return 5 - x since sorting still demands that higher is better.""" header = header.split() for item in header: item = item.split('=') try: ...
python
def get_uniprot_evidence_level(header): """Returns uniprot protein existence evidence level for a fasta header. Evidence levels are 1-5, but we return 5 - x since sorting still demands that higher is better.""" header = header.split() for item in header: item = item.split('=') try: ...
[ "def", "get_uniprot_evidence_level", "(", "header", ")", ":", "header", "=", "header", ".", "split", "(", ")", "for", "item", "in", "header", ":", "item", "=", "item", ".", "split", "(", "'='", ")", "try", ":", "if", "item", "[", "0", "]", "==", "'...
Returns uniprot protein existence evidence level for a fasta header. Evidence levels are 1-5, but we return 5 - x since sorting still demands that higher is better.
[ "Returns", "uniprot", "protein", "existence", "evidence", "level", "for", "a", "fasta", "header", ".", "Evidence", "levels", "are", "1", "-", "5", "but", "we", "return", "5", "-", "x", "since", "sorting", "still", "demands", "that", "higher", "is", "better...
ded7e5cbd813d7797dc9d42805778266e59ff042
https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/readers/fasta.py#L119-L131
train
Returns the uniprot protein existence evidence level for a fasta header.
timedata-org/loady
loady/raw.py
raw
def raw(url): """Return a raw version of the URL if there is one. Otherwise returns the original URL. Many repos have "raw" and "user-friendly" versions of each URL. Usually when you want to download something programmatically, you want the raw version, but users will enter the user-friendly versi...
python
def raw(url): """Return a raw version of the URL if there is one. Otherwise returns the original URL. Many repos have "raw" and "user-friendly" versions of each URL. Usually when you want to download something programmatically, you want the raw version, but users will enter the user-friendly versi...
[ "def", "raw", "(", "url", ")", ":", "try", ":", "# If it's a user-friendly gist URL, get the real data by parsing", "# the file.", "parts", "=", "url", ".", "split", "(", "'/'", ")", "if", "parts", "[", "2", "]", "==", "'gist.github.com'", "and", "'.'", "not", ...
Return a raw version of the URL if there is one. Otherwise returns the original URL. Many repos have "raw" and "user-friendly" versions of each URL. Usually when you want to download something programmatically, you want the raw version, but users will enter the user-friendly version as it is the one ...
[ "Return", "a", "raw", "version", "of", "the", "URL", "if", "there", "is", "one", ".", "Otherwise", "returns", "the", "original", "URL", "." ]
94ffcdb92f15a28f3c85f77bd293a9cb59de4cad
https://github.com/timedata-org/loady/blob/94ffcdb92f15a28f3c85f77bd293a9cb59de4cad/loady/raw.py#L17-L59
train
Return a raw version of the URL if there is one.
jdodds/feather
feather/plugin.py
Plugin.run
def run(self): """Run our loop, and any defined hooks... """ self.pre_run() first = True while self.runnable: self.pre_call_message() if first: self.pre_first_call_message() message, payload = self.listener.get() ...
python
def run(self): """Run our loop, and any defined hooks... """ self.pre_run() first = True while self.runnable: self.pre_call_message() if first: self.pre_first_call_message() message, payload = self.listener.get() ...
[ "def", "run", "(", "self", ")", ":", "self", ".", "pre_run", "(", ")", "first", "=", "True", "while", "self", ".", "runnable", ":", "self", ".", "pre_call_message", "(", ")", "if", "first", ":", "self", ".", "pre_first_call_message", "(", ")", "message...
Run our loop, and any defined hooks...
[ "Run", "our", "loop", "and", "any", "defined", "hooks", "..." ]
92a9426e692b33c7fddf758df8dbc99a9a1ba8ef
https://github.com/jdodds/feather/blob/92a9426e692b33c7fddf758df8dbc99a9a1ba8ef/feather/plugin.py#L70-L90
train
Run our loop and any defined hooks...
tamasgal/km3pipe
km3modules/hits.py
count_multiplicities
def count_multiplicities(times, tmax=20): """Calculate an array of multiplicities and corresponding coincidence IDs Note that this algorithm does not take care about DOM IDs, so it has to be fed with DOM hits. Parameters ---------- times: array[float], shape=(n,) Hit times for n hits ...
python
def count_multiplicities(times, tmax=20): """Calculate an array of multiplicities and corresponding coincidence IDs Note that this algorithm does not take care about DOM IDs, so it has to be fed with DOM hits. Parameters ---------- times: array[float], shape=(n,) Hit times for n hits ...
[ "def", "count_multiplicities", "(", "times", ",", "tmax", "=", "20", ")", ":", "n", "=", "times", ".", "shape", "[", "0", "]", "mtp", "=", "np", ".", "ones", "(", "n", ",", "dtype", "=", "'<i4'", ")", "# multiplicities", "cid", "=", "np", ".", "z...
Calculate an array of multiplicities and corresponding coincidence IDs Note that this algorithm does not take care about DOM IDs, so it has to be fed with DOM hits. Parameters ---------- times: array[float], shape=(n,) Hit times for n hits dt: int [default: 20] Time window of a...
[ "Calculate", "an", "array", "of", "multiplicities", "and", "corresponding", "coincidence", "IDs" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3modules/hits.py#L28-L68
train
Calculate an array of multiplicities and corresponding coincidence IDs for a single node.
IRC-SPHERE/HyperStream
hyperstream/utils/serialization.py
func_load
def func_load(code, defaults=None, closure=None, globs=None): """ Reload a function :param code: The code object :param defaults: Default values :param closure: The closure :param globs: globals :return: """ if isinstance(code, (tuple, list)): # unpack previous dump code, de...
python
def func_load(code, defaults=None, closure=None, globs=None): """ Reload a function :param code: The code object :param defaults: Default values :param closure: The closure :param globs: globals :return: """ if isinstance(code, (tuple, list)): # unpack previous dump code, de...
[ "def", "func_load", "(", "code", ",", "defaults", "=", "None", ",", "closure", "=", "None", ",", "globs", "=", "None", ")", ":", "if", "isinstance", "(", "code", ",", "(", "tuple", ",", "list", ")", ")", ":", "# unpack previous dump", "code", ",", "d...
Reload a function :param code: The code object :param defaults: Default values :param closure: The closure :param globs: globals :return:
[ "Reload", "a", "function", ":", "param", "code", ":", "The", "code", "object", ":", "param", "defaults", ":", "Default", "values", ":", "param", "closure", ":", "The", "closure", ":", "param", "globs", ":", "globals", ":", "return", ":" ]
98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780
https://github.com/IRC-SPHERE/HyperStream/blob/98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780/hyperstream/utils/serialization.py#L41-L57
train
Load a function from a code object.
IRC-SPHERE/HyperStream
hyperstream/utils/serialization.py
func_reconstruct_closure
def func_reconstruct_closure(values): """ Deserialization helper that reconstructs a closure :param values: The closure values :return: The closure """ nums = range(len(values)) src = ["def func(arg):"] src += [" _%d = arg[%d]" % (n, n) for n in nums] src += [" return lambda:(%s)" ...
python
def func_reconstruct_closure(values): """ Deserialization helper that reconstructs a closure :param values: The closure values :return: The closure """ nums = range(len(values)) src = ["def func(arg):"] src += [" _%d = arg[%d]" % (n, n) for n in nums] src += [" return lambda:(%s)" ...
[ "def", "func_reconstruct_closure", "(", "values", ")", ":", "nums", "=", "range", "(", "len", "(", "values", ")", ")", "src", "=", "[", "\"def func(arg):\"", "]", "src", "+=", "[", "\" _%d = arg[%d]\"", "%", "(", "n", ",", "n", ")", "for", "n", "in", ...
Deserialization helper that reconstructs a closure :param values: The closure values :return: The closure
[ "Deserialization", "helper", "that", "reconstructs", "a", "closure", ":", "param", "values", ":", "The", "closure", "values", ":", "return", ":", "The", "closure" ]
98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780
https://github.com/IRC-SPHERE/HyperStream/blob/98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780/hyperstream/utils/serialization.py#L60-L75
train
Deserialization helper that reconstructs a closure .
vslutov/turingmarkov
turingmarkov/turing.py
build_machine
def build_machine(lines): """Build machine from list of lines.""" if lines == []: raise SyntaxError('Empty file') else: machine = Machine(lines[0].split()) for line in lines[1:]: if line.strip() != '': machine.add_state(line) machine.check() return...
python
def build_machine(lines): """Build machine from list of lines.""" if lines == []: raise SyntaxError('Empty file') else: machine = Machine(lines[0].split()) for line in lines[1:]: if line.strip() != '': machine.add_state(line) machine.check() return...
[ "def", "build_machine", "(", "lines", ")", ":", "if", "lines", "==", "[", "]", ":", "raise", "SyntaxError", "(", "'Empty file'", ")", "else", ":", "machine", "=", "Machine", "(", "lines", "[", "0", "]", ".", "split", "(", ")", ")", "for", "line", "...
Build machine from list of lines.
[ "Build", "machine", "from", "list", "of", "lines", "." ]
63e2ba255d7d0d868cbc4bf3e568b1c1bbcf38ce
https://github.com/vslutov/turingmarkov/blob/63e2ba255d7d0d868cbc4bf3e568b1c1bbcf38ce/turingmarkov/turing.py#L175-L185
train
Build a machine from a list of lines.
vslutov/turingmarkov
turingmarkov/turing.py
Machine._add_rule
def _add_rule(self, state, rule): """Parse rule and add it to machine (for internal use).""" if rule.strip() == "-": parsed_rule = None else: parsed_rule = rule.split(',') if (len(parsed_rule) != 3 or parsed_rule[1] not in ['L', 'N', 'R'] or...
python
def _add_rule(self, state, rule): """Parse rule and add it to machine (for internal use).""" if rule.strip() == "-": parsed_rule = None else: parsed_rule = rule.split(',') if (len(parsed_rule) != 3 or parsed_rule[1] not in ['L', 'N', 'R'] or...
[ "def", "_add_rule", "(", "self", ",", "state", ",", "rule", ")", ":", "if", "rule", ".", "strip", "(", ")", "==", "\"-\"", ":", "parsed_rule", "=", "None", "else", ":", "parsed_rule", "=", "rule", ".", "split", "(", "','", ")", "if", "(", "len", ...
Parse rule and add it to machine (for internal use).
[ "Parse", "rule", "and", "add", "it", "to", "machine", "(", "for", "internal", "use", ")", "." ]
63e2ba255d7d0d868cbc4bf3e568b1c1bbcf38ce
https://github.com/vslutov/turingmarkov/blob/63e2ba255d7d0d868cbc4bf3e568b1c1bbcf38ce/turingmarkov/turing.py#L41-L58
train
Parse rule and add it to machine.
vslutov/turingmarkov
turingmarkov/turing.py
Machine.add_state
def add_state(self, string): """Add state and rules to machine.""" parsed_string = string.split() if len(parsed_string) > 0: state, rules = parsed_string[0], parsed_string[1:] if len(rules) != len(self.alphabet): raise SyntaxError('Wrong count of rules ({...
python
def add_state(self, string): """Add state and rules to machine.""" parsed_string = string.split() if len(parsed_string) > 0: state, rules = parsed_string[0], parsed_string[1:] if len(rules) != len(self.alphabet): raise SyntaxError('Wrong count of rules ({...
[ "def", "add_state", "(", "self", ",", "string", ")", ":", "parsed_string", "=", "string", ".", "split", "(", ")", "if", "len", "(", "parsed_string", ")", ">", "0", ":", "state", ",", "rules", "=", "parsed_string", "[", "0", "]", ",", "parsed_string", ...
Add state and rules to machine.
[ "Add", "state", "and", "rules", "to", "machine", "." ]
63e2ba255d7d0d868cbc4bf3e568b1c1bbcf38ce
https://github.com/vslutov/turingmarkov/blob/63e2ba255d7d0d868cbc4bf3e568b1c1bbcf38ce/turingmarkov/turing.py#L60-L81
train
Add state and rules to machine.
vslutov/turingmarkov
turingmarkov/turing.py
Machine.check
def check(self): """Check semantic rules.""" has_term = False if self.START_STATE not in self.states: raise SyntaxError('Undefined start rule') for state in self.states: for rule in self.states[state]: if rule is not None: if ...
python
def check(self): """Check semantic rules.""" has_term = False if self.START_STATE not in self.states: raise SyntaxError('Undefined start rule') for state in self.states: for rule in self.states[state]: if rule is not None: if ...
[ "def", "check", "(", "self", ")", ":", "has_term", "=", "False", "if", "self", ".", "START_STATE", "not", "in", "self", ".", "states", ":", "raise", "SyntaxError", "(", "'Undefined start rule'", ")", "for", "state", "in", "self", ".", "states", ":", "for...
Check semantic rules.
[ "Check", "semantic", "rules", "." ]
63e2ba255d7d0d868cbc4bf3e568b1c1bbcf38ce
https://github.com/vslutov/turingmarkov/blob/63e2ba255d7d0d868cbc4bf3e568b1c1bbcf38ce/turingmarkov/turing.py#L83-L99
train
Check semantic rules.
vslutov/turingmarkov
turingmarkov/turing.py
Machine.init_tape
def init_tape(self, string): """Init system values.""" for char in string: if char not in self.alphabet and not char.isspace() and char != self.EMPTY_SYMBOL: raise RuntimeError('Invalid symbol: "' + char + '"') self.check() self.state = self.START_STATE ...
python
def init_tape(self, string): """Init system values.""" for char in string: if char not in self.alphabet and not char.isspace() and char != self.EMPTY_SYMBOL: raise RuntimeError('Invalid symbol: "' + char + '"') self.check() self.state = self.START_STATE ...
[ "def", "init_tape", "(", "self", ",", "string", ")", ":", "for", "char", "in", "string", ":", "if", "char", "not", "in", "self", ".", "alphabet", "and", "not", "char", ".", "isspace", "(", ")", "and", "char", "!=", "self", ".", "EMPTY_SYMBOL", ":", ...
Init system values.
[ "Init", "system", "values", "." ]
63e2ba255d7d0d868cbc4bf3e568b1c1bbcf38ce
https://github.com/vslutov/turingmarkov/blob/63e2ba255d7d0d868cbc4bf3e568b1c1bbcf38ce/turingmarkov/turing.py#L101-L114
train
Initialize the system values.
vslutov/turingmarkov
turingmarkov/turing.py
Machine.get_tape
def get_tape(self): """Get content of tape.""" result = '' for i in range(min(self.tape), max(self.tape) + 1): symbol = self.tape[i] if self.tape[i] != self.EMPTY_SYMBOL else ' ' result += symbol # Remove unnecessary empty symbols on tape return result.str...
python
def get_tape(self): """Get content of tape.""" result = '' for i in range(min(self.tape), max(self.tape) + 1): symbol = self.tape[i] if self.tape[i] != self.EMPTY_SYMBOL else ' ' result += symbol # Remove unnecessary empty symbols on tape return result.str...
[ "def", "get_tape", "(", "self", ")", ":", "result", "=", "''", "for", "i", "in", "range", "(", "min", "(", "self", ".", "tape", ")", ",", "max", "(", "self", ".", "tape", ")", "+", "1", ")", ":", "symbol", "=", "self", ".", "tape", "[", "i", ...
Get content of tape.
[ "Get", "content", "of", "tape", "." ]
63e2ba255d7d0d868cbc4bf3e568b1c1bbcf38ce
https://github.com/vslutov/turingmarkov/blob/63e2ba255d7d0d868cbc4bf3e568b1c1bbcf38ce/turingmarkov/turing.py#L116-L123
train
Get content of tape.
vslutov/turingmarkov
turingmarkov/turing.py
Machine.execute_once
def execute_once(self): """One step of execution.""" symbol = self.tape.get(self.head, self.EMPTY_SYMBOL) index = self.alphabet.index(symbol) rule = self.states[self.state][index] if rule is None: raise RuntimeError('Unexpected symbol: ' + symbol) self.tape...
python
def execute_once(self): """One step of execution.""" symbol = self.tape.get(self.head, self.EMPTY_SYMBOL) index = self.alphabet.index(symbol) rule = self.states[self.state][index] if rule is None: raise RuntimeError('Unexpected symbol: ' + symbol) self.tape...
[ "def", "execute_once", "(", "self", ")", ":", "symbol", "=", "self", ".", "tape", ".", "get", "(", "self", ".", "head", ",", "self", ".", "EMPTY_SYMBOL", ")", "index", "=", "self", ".", "alphabet", ".", "index", "(", "symbol", ")", "rule", "=", "se...
One step of execution.
[ "One", "step", "of", "execution", "." ]
63e2ba255d7d0d868cbc4bf3e568b1c1bbcf38ce
https://github.com/vslutov/turingmarkov/blob/63e2ba255d7d0d868cbc4bf3e568b1c1bbcf38ce/turingmarkov/turing.py#L125-L142
train
Execute one step of execution.
vslutov/turingmarkov
turingmarkov/turing.py
Machine.execute
def execute(self, string, max_tacts=None): """Execute algorithm (if max_times = None, there can be forever loop).""" self.init_tape(string) counter = 0 while True: self.execute_once() if self.state == self.TERM_STATE: break counter += ...
python
def execute(self, string, max_tacts=None): """Execute algorithm (if max_times = None, there can be forever loop).""" self.init_tape(string) counter = 0 while True: self.execute_once() if self.state == self.TERM_STATE: break counter += ...
[ "def", "execute", "(", "self", ",", "string", ",", "max_tacts", "=", "None", ")", ":", "self", ".", "init_tape", "(", "string", ")", "counter", "=", "0", "while", "True", ":", "self", ".", "execute_once", "(", ")", "if", "self", ".", "state", "==", ...
Execute algorithm (if max_times = None, there can be forever loop).
[ "Execute", "algorithm", "(", "if", "max_times", "=", "None", "there", "can", "be", "forever", "loop", ")", "." ]
63e2ba255d7d0d868cbc4bf3e568b1c1bbcf38ce
https://github.com/vslutov/turingmarkov/blob/63e2ba255d7d0d868cbc4bf3e568b1c1bbcf38ce/turingmarkov/turing.py#L144-L157
train
Execute algorithm.
vslutov/turingmarkov
turingmarkov/turing.py
Machine.compile
def compile(self): """Return python code for create and execute machine.""" result = TEMPLATE result += 'machine = Machine(' + repr(self.alphabet) + ')\n' for state in self.states: repr_state = state[0] for rule in self.states[state]: repr_state +...
python
def compile(self): """Return python code for create and execute machine.""" result = TEMPLATE result += 'machine = Machine(' + repr(self.alphabet) + ')\n' for state in self.states: repr_state = state[0] for rule in self.states[state]: repr_state +...
[ "def", "compile", "(", "self", ")", ":", "result", "=", "TEMPLATE", "result", "+=", "'machine = Machine('", "+", "repr", "(", "self", ".", "alphabet", ")", "+", "')\\n'", "for", "state", "in", "self", ".", "states", ":", "repr_state", "=", "state", "[", ...
Return python code for create and execute machine.
[ "Return", "python", "code", "for", "create", "and", "execute", "machine", "." ]
63e2ba255d7d0d868cbc4bf3e568b1c1bbcf38ce
https://github.com/vslutov/turingmarkov/blob/63e2ba255d7d0d868cbc4bf3e568b1c1bbcf38ce/turingmarkov/turing.py#L159-L173
train
Return python code for create and execute machine.
tamasgal/km3pipe
km3pipe/core.py
ServiceManager.get_missing_services
def get_missing_services(self, services): """ Check if all required services are provided Args: services: List with the service names which are required Returns: List with missing services """ required_services = set(services) provided_ser...
python
def get_missing_services(self, services): """ Check if all required services are provided Args: services: List with the service names which are required Returns: List with missing services """ required_services = set(services) provided_ser...
[ "def", "get_missing_services", "(", "self", ",", "services", ")", ":", "required_services", "=", "set", "(", "services", ")", "provided_services", "=", "set", "(", "self", ".", "_services", ".", "keys", "(", ")", ")", "missing_services", "=", "required_service...
Check if all required services are provided Args: services: List with the service names which are required Returns: List with missing services
[ "Check", "if", "all", "required", "services", "are", "provided" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/core.py#L72-L85
train
Check if all required services are provided
tamasgal/km3pipe
km3pipe/core.py
Pipeline.attach
def attach(self, module_factory, name=None, **kwargs): """Attach a module to the pipeline system""" if self.anybar: self.anybar.change("yellow") fac = module_factory if name is None: name = fac.__name__ log.info("Attaching module '{0}'".format(name)) if (i...
python
def attach(self, module_factory, name=None, **kwargs): """Attach a module to the pipeline system""" if self.anybar: self.anybar.change("yellow") fac = module_factory if name is None: name = fac.__name__ log.info("Attaching module '{0}'".format(name)) if (i...
[ "def", "attach", "(", "self", ",", "module_factory", ",", "name", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "anybar", ":", "self", ".", "anybar", ".", "change", "(", "\"yellow\"", ")", "fac", "=", "module_factory", "if", "nam...
Attach a module to the pipeline system
[ "Attach", "a", "module", "to", "the", "pipeline", "system" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/core.py#L158-L252
train
Attach a module to the pipeline system.
tamasgal/km3pipe
km3pipe/core.py
Pipeline._drain
def _drain(self, cycles=None): """Activate the pump and let the flow go. This will call the process() method on each attached module until a StopIteration is raised, usually by a pump when it reached the EOF. A StopIteration is also raised when self.cycles was set and the numbe...
python
def _drain(self, cycles=None): """Activate the pump and let the flow go. This will call the process() method on each attached module until a StopIteration is raised, usually by a pump when it reached the EOF. A StopIteration is also raised when self.cycles was set and the numbe...
[ "def", "_drain", "(", "self", ",", "cycles", "=", "None", ")", ":", "log", ".", "info", "(", "\"Now draining...\"", ")", "if", "not", "cycles", ":", "log", ".", "info", "(", "\"No cycle count, the pipeline may be drained forever.\"", ")", "if", "self", ".", ...
Activate the pump and let the flow go. This will call the process() method on each attached module until a StopIteration is raised, usually by a pump when it reached the EOF. A StopIteration is also raised when self.cycles was set and the number of cycles has reached that limit.
[ "Activate", "the", "pump", "and", "let", "the", "flow", "go", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/core.py#L258-L344
train
This method is called by the pump when the pipeline is empty.
tamasgal/km3pipe
km3pipe/core.py
Pipeline._check_service_requirements
def _check_service_requirements(self): """Final comparison of provided and required modules""" missing = self.services.get_missing_services( self.required_services.keys() ) if missing: self.log.critical( "Following services are required and missing...
python
def _check_service_requirements(self): """Final comparison of provided and required modules""" missing = self.services.get_missing_services( self.required_services.keys() ) if missing: self.log.critical( "Following services are required and missing...
[ "def", "_check_service_requirements", "(", "self", ")", ":", "missing", "=", "self", ".", "services", ".", "get_missing_services", "(", "self", ".", "required_services", ".", "keys", "(", ")", ")", "if", "missing", ":", "self", ".", "log", ".", "critical", ...
Final comparison of provided and required modules
[ "Final", "comparison", "of", "provided", "and", "required", "modules" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/core.py#L346-L358
train
Final comparison of provided and required modules
tamasgal/km3pipe
km3pipe/core.py
Pipeline.drain
def drain(self, cycles=None): """Execute _drain while trapping KeyboardInterrupt""" if not self._check_service_requirements(): self.init_timer.stop() return self.finish() if self.anybar: self.anybar.change("orange") self.init_timer.stop() log.info("Trappi...
python
def drain(self, cycles=None): """Execute _drain while trapping KeyboardInterrupt""" if not self._check_service_requirements(): self.init_timer.stop() return self.finish() if self.anybar: self.anybar.change("orange") self.init_timer.stop() log.info("Trappi...
[ "def", "drain", "(", "self", ",", "cycles", "=", "None", ")", ":", "if", "not", "self", ".", "_check_service_requirements", "(", ")", ":", "self", ".", "init_timer", ".", "stop", "(", ")", "return", "self", ".", "finish", "(", ")", "if", "self", ".",...
Execute _drain while trapping KeyboardInterrupt
[ "Execute", "_drain", "while", "trapping", "KeyboardInterrupt" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/core.py#L360-L371
train
Execute _drain while trapping KeyboardInterrupt
tamasgal/km3pipe
km3pipe/core.py
Pipeline.finish
def finish(self): """Call finish() on each attached module""" if self.anybar: self.anybar.change("purple") finish_blob = Blob() for module in self.modules: if hasattr(module, 'pre_finish'): log.info("Finishing {0}".format(module.name)) start_t...
python
def finish(self): """Call finish() on each attached module""" if self.anybar: self.anybar.change("purple") finish_blob = Blob() for module in self.modules: if hasattr(module, 'pre_finish'): log.info("Finishing {0}".format(module.name)) start_t...
[ "def", "finish", "(", "self", ")", ":", "if", "self", ".", "anybar", ":", "self", ".", "anybar", ".", "change", "(", "\"purple\"", ")", "finish_blob", "=", "Blob", "(", ")", "for", "module", "in", "self", ".", "modules", ":", "if", "hasattr", "(", ...
Call finish() on each attached module
[ "Call", "finish", "()", "on", "each", "attached", "module" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/core.py#L373-L395
train
Call finish on each attached module
tamasgal/km3pipe
km3pipe/core.py
Pipeline._handle_ctrl_c
def _handle_ctrl_c(self, *args): """Handle the keyboard interrupts.""" if self.anybar: self.anybar.change("exclamation") if self._stop: print("\nForced shutdown...") raise SystemExit if not self._stop: hline = 42 * '=' print( ...
python
def _handle_ctrl_c(self, *args): """Handle the keyboard interrupts.""" if self.anybar: self.anybar.change("exclamation") if self._stop: print("\nForced shutdown...") raise SystemExit if not self._stop: hline = 42 * '=' print( ...
[ "def", "_handle_ctrl_c", "(", "self", ",", "*", "args", ")", ":", "if", "self", ".", "anybar", ":", "self", ".", "anybar", ".", "change", "(", "\"exclamation\"", ")", "if", "self", ".", "_stop", ":", "print", "(", "\"\\nForced shutdown...\"", ")", "raise...
Handle the keyboard interrupts.
[ "Handle", "the", "keyboard", "interrupts", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/core.py#L397-L410
train
Handle the keyboard interrupts.
tamasgal/km3pipe
km3pipe/core.py
Module.get
def get(self, name, default=None): """Return the value of the requested parameter or `default` if None.""" value = self.parameters.get(name) self._processed_parameters.append(name) if value is None: return default return value
python
def get(self, name, default=None): """Return the value of the requested parameter or `default` if None.""" value = self.parameters.get(name) self._processed_parameters.append(name) if value is None: return default return value
[ "def", "get", "(", "self", ",", "name", ",", "default", "=", "None", ")", ":", "value", "=", "self", ".", "parameters", ".", "get", "(", "name", ")", "self", ".", "_processed_parameters", ".", "append", "(", "name", ")", "if", "value", "is", "None", ...
Return the value of the requested parameter or `default` if None.
[ "Return", "the", "value", "of", "the", "requested", "parameter", "or", "default", "if", "None", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/core.py#L531-L537
train
Return the value of the requested parameter or default.
tamasgal/km3pipe
km3pipe/core.py
Module.require
def require(self, name): """Return the value of the requested parameter or raise an error.""" value = self.get(name) if value is None: raise TypeError( "{0} requires the parameter '{1}'.".format( self.__class__, name ) )...
python
def require(self, name): """Return the value of the requested parameter or raise an error.""" value = self.get(name) if value is None: raise TypeError( "{0} requires the parameter '{1}'.".format( self.__class__, name ) )...
[ "def", "require", "(", "self", ",", "name", ")", ":", "value", "=", "self", ".", "get", "(", "name", ")", "if", "value", "is", "None", ":", "raise", "TypeError", "(", "\"{0} requires the parameter '{1}'.\"", ".", "format", "(", "self", ".", "__class__", ...
Return the value of the requested parameter or raise an error.
[ "Return", "the", "value", "of", "the", "requested", "parameter", "or", "raise", "an", "error", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/core.py#L539-L548
train
Return the value of the requested parameter. Raise an error if the requested parameter is not present.
tamasgal/km3pipe
km3pipe/core.py
Module._check_unused_parameters
def _check_unused_parameters(self): """Check if any of the parameters passed in are ignored""" all_params = set(self.parameters.keys()) processed_params = set(self._processed_parameters) unused_params = all_params - processed_params - RESERVED_ARGS if unused_params: ...
python
def _check_unused_parameters(self): """Check if any of the parameters passed in are ignored""" all_params = set(self.parameters.keys()) processed_params = set(self._processed_parameters) unused_params = all_params - processed_params - RESERVED_ARGS if unused_params: ...
[ "def", "_check_unused_parameters", "(", "self", ")", ":", "all_params", "=", "set", "(", "self", ".", "parameters", ".", "keys", "(", ")", ")", "processed_params", "=", "set", "(", "self", ".", "_processed_parameters", ")", "unused_params", "=", "all_params", ...
Check if any of the parameters passed in are ignored
[ "Check", "if", "any", "of", "the", "parameters", "passed", "in", "are", "ignored" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/core.py#L565-L576
train
Check if any of the parameters passed in are ignored
tamasgal/km3pipe
km3pipe/core.py
Pump.open_file
def open_file(self, filename): """Open the file with filename""" try: if filename.endswith('.gz'): self.blob_file = gzip.open(filename, 'rb') else: self.blob_file = open(filename, 'rb') except TypeError: log.error("Please specif...
python
def open_file(self, filename): """Open the file with filename""" try: if filename.endswith('.gz'): self.blob_file = gzip.open(filename, 'rb') else: self.blob_file = open(filename, 'rb') except TypeError: log.error("Please specif...
[ "def", "open_file", "(", "self", ",", "filename", ")", ":", "try", ":", "if", "filename", ".", "endswith", "(", "'.gz'", ")", ":", "self", ".", "blob_file", "=", "gzip", ".", "open", "(", "filename", ",", "'rb'", ")", "else", ":", "self", ".", "blo...
Open the file with filename
[ "Open", "the", "file", "with", "filename" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/core.py#L599-L611
train
Open the file with filename
ioos/pyoos
pyoos/parsers/hads.py
HadsParser._parse_data
def _parse_data(self, raw_data, var_filter, time_extents): """ Transforms raw HADS observations into a dict: station code -> [(variable, time, value), ...] Takes into account the var filter (if set). """ retval = defaultdict(list) p = parser() begin...
python
def _parse_data(self, raw_data, var_filter, time_extents): """ Transforms raw HADS observations into a dict: station code -> [(variable, time, value), ...] Takes into account the var filter (if set). """ retval = defaultdict(list) p = parser() begin...
[ "def", "_parse_data", "(", "self", ",", "raw_data", ",", "var_filter", ",", "time_extents", ")", ":", "retval", "=", "defaultdict", "(", "list", ")", "p", "=", "parser", "(", ")", "begin_time", ",", "end_time", "=", "time_extents", "for", "line", "in", "...
Transforms raw HADS observations into a dict: station code -> [(variable, time, value), ...] Takes into account the var filter (if set).
[ "Transforms", "raw", "HADS", "observations", "into", "a", "dict", ":", "station", "code", "-", ">", "[", "(", "variable", "time", "value", ")", "...", "]" ]
908660385029ecd8eccda8ab3a6b20b47b915c77
https://github.com/ioos/pyoos/blob/908660385029ecd8eccda8ab3a6b20b47b915c77/pyoos/parsers/hads.py#L127-L158
train
Parses the HADS data into a dictionary of station code - > list of variable - > value pairs.
ioos/pyoos
pyoos/parsers/hads.py
HadsParser._parse_metadata
def _parse_metadata(self, metadata): """ Transforms raw HADS metadata into a dictionary (station code -> props) """ retval = {} # these are the first keys, afterwards follows a var-len list of variables/props # first key always blank so skip it field_keys = [ ...
python
def _parse_metadata(self, metadata): """ Transforms raw HADS metadata into a dictionary (station code -> props) """ retval = {} # these are the first keys, afterwards follows a var-len list of variables/props # first key always blank so skip it field_keys = [ ...
[ "def", "_parse_metadata", "(", "self", ",", "metadata", ")", ":", "retval", "=", "{", "}", "# these are the first keys, afterwards follows a var-len list of variables/props", "# first key always blank so skip it", "field_keys", "=", "[", "\"nesdis_id\"", ",", "\"nwsli\"", ","...
Transforms raw HADS metadata into a dictionary (station code -> props)
[ "Transforms", "raw", "HADS", "metadata", "into", "a", "dictionary", "(", "station", "code", "-", ">", "props", ")" ]
908660385029ecd8eccda8ab3a6b20b47b915c77
https://github.com/ioos/pyoos/blob/908660385029ecd8eccda8ab3a6b20b47b915c77/pyoos/parsers/hads.py#L160-L246
train
Parses the HADS metadata into a dictionary.
ioos/pyoos
pyoos/parsers/hads.py
HadsParser.get_variable_info
def get_variable_info(cls, hads_var_name): """ Returns a tuple of (mmi name, units, english name, english description) or None. """ if hads_var_name == "UR": return ( "wind_gust_from_direction", "degrees from N", "Wind Gust from...
python
def get_variable_info(cls, hads_var_name): """ Returns a tuple of (mmi name, units, english name, english description) or None. """ if hads_var_name == "UR": return ( "wind_gust_from_direction", "degrees from N", "Wind Gust from...
[ "def", "get_variable_info", "(", "cls", ",", "hads_var_name", ")", ":", "if", "hads_var_name", "==", "\"UR\"", ":", "return", "(", "\"wind_gust_from_direction\"", ",", "\"degrees from N\"", ",", "\"Wind Gust from Direction\"", ",", "\"Direction from which wind gust is blowi...
Returns a tuple of (mmi name, units, english name, english description) or None.
[ "Returns", "a", "tuple", "of", "(", "mmi", "name", "units", "english", "name", "english", "description", ")", "or", "None", "." ]
908660385029ecd8eccda8ab3a6b20b47b915c77
https://github.com/ioos/pyoos/blob/908660385029ecd8eccda8ab3a6b20b47b915c77/pyoos/parsers/hads.py#L249-L404
train
Returns a tuple of the variable name units english name and english description of the variable.
ioos/pyoos
pyoos/utils/asatime.py
AsaTime.parse
def parse(cls, date_string): """ Parse any time string. Use a custom timezone matching if the original matching does not pull one out. """ try: date = dateparser.parse(date_string) if date.tzinfo is None: date = dateparser.parse(da...
python
def parse(cls, date_string): """ Parse any time string. Use a custom timezone matching if the original matching does not pull one out. """ try: date = dateparser.parse(date_string) if date.tzinfo is None: date = dateparser.parse(da...
[ "def", "parse", "(", "cls", ",", "date_string", ")", ":", "try", ":", "date", "=", "dateparser", ".", "parse", "(", "date_string", ")", "if", "date", ".", "tzinfo", "is", "None", ":", "date", "=", "dateparser", ".", "parse", "(", "date_string", ",", ...
Parse any time string. Use a custom timezone matching if the original matching does not pull one out.
[ "Parse", "any", "time", "string", ".", "Use", "a", "custom", "timezone", "matching", "if", "the", "original", "matching", "does", "not", "pull", "one", "out", "." ]
908660385029ecd8eccda8ab3a6b20b47b915c77
https://github.com/ioos/pyoos/blob/908660385029ecd8eccda8ab3a6b20b47b915c77/pyoos/utils/asatime.py#L54-L65
train
Parse any time string.
developmentseed/sentinel-s3
sentinel_s3/converter.py
epsg_code
def epsg_code(geojson): """ get the espg code from the crs system """ if isinstance(geojson, dict): if 'crs' in geojson: urn = geojson['crs']['properties']['name'].split(':') if 'EPSG' in urn: try: return int(urn[-1]) except (T...
python
def epsg_code(geojson): """ get the espg code from the crs system """ if isinstance(geojson, dict): if 'crs' in geojson: urn = geojson['crs']['properties']['name'].split(':') if 'EPSG' in urn: try: return int(urn[-1]) except (T...
[ "def", "epsg_code", "(", "geojson", ")", ":", "if", "isinstance", "(", "geojson", ",", "dict", ")", ":", "if", "'crs'", "in", "geojson", ":", "urn", "=", "geojson", "[", "'crs'", "]", "[", "'properties'", "]", "[", "'name'", "]", ".", "split", "(", ...
get the espg code from the crs system
[ "get", "the", "espg", "code", "from", "the", "crs", "system" ]
02bf2f9cb6aff527e492b39518a54f0b4613ddda
https://github.com/developmentseed/sentinel-s3/blob/02bf2f9cb6aff527e492b39518a54f0b4613ddda/sentinel_s3/converter.py#L24-L36
train
get the espg code from the crs system
developmentseed/sentinel-s3
sentinel_s3/converter.py
convert_coordinates
def convert_coordinates(coords, origin, wgs84, wrapped): """ Convert coordinates from one crs to another """ if isinstance(coords, list) or isinstance(coords, tuple): try: if isinstance(coords[0], list) or isinstance(coords[0], tuple): return [convert_coordinates(list(c), ori...
python
def convert_coordinates(coords, origin, wgs84, wrapped): """ Convert coordinates from one crs to another """ if isinstance(coords, list) or isinstance(coords, tuple): try: if isinstance(coords[0], list) or isinstance(coords[0], tuple): return [convert_coordinates(list(c), ori...
[ "def", "convert_coordinates", "(", "coords", ",", "origin", ",", "wgs84", ",", "wrapped", ")", ":", "if", "isinstance", "(", "coords", ",", "list", ")", "or", "isinstance", "(", "coords", ",", "tuple", ")", ":", "try", ":", "if", "isinstance", "(", "co...
Convert coordinates from one crs to another
[ "Convert", "coordinates", "from", "one", "crs", "to", "another" ]
02bf2f9cb6aff527e492b39518a54f0b4613ddda
https://github.com/developmentseed/sentinel-s3/blob/02bf2f9cb6aff527e492b39518a54f0b4613ddda/sentinel_s3/converter.py#L56-L71
train
Convert coordinates from one crs to another
developmentseed/sentinel-s3
sentinel_s3/converter.py
to_latlon
def to_latlon(geojson, origin_espg=None): """ Convert a given geojson to wgs84. The original epsg must be included insde the crs tag of geojson """ if isinstance(geojson, dict): # get epsg code: if origin_espg: code = origin_espg else: code = epsg_co...
python
def to_latlon(geojson, origin_espg=None): """ Convert a given geojson to wgs84. The original epsg must be included insde the crs tag of geojson """ if isinstance(geojson, dict): # get epsg code: if origin_espg: code = origin_espg else: code = epsg_co...
[ "def", "to_latlon", "(", "geojson", ",", "origin_espg", "=", "None", ")", ":", "if", "isinstance", "(", "geojson", ",", "dict", ")", ":", "# get epsg code:", "if", "origin_espg", ":", "code", "=", "origin_espg", "else", ":", "code", "=", "epsg_code", "(", ...
Convert a given geojson to wgs84. The original epsg must be included insde the crs tag of geojson
[ "Convert", "a", "given", "geojson", "to", "wgs84", ".", "The", "original", "epsg", "must", "be", "included", "insde", "the", "crs", "tag", "of", "geojson" ]
02bf2f9cb6aff527e492b39518a54f0b4613ddda
https://github.com/developmentseed/sentinel-s3/blob/02bf2f9cb6aff527e492b39518a54f0b4613ddda/sentinel_s3/converter.py#L74-L99
train
Convert a given geojson to wgs84.
developmentseed/sentinel-s3
sentinel_s3/converter.py
camelcase_underscore
def camelcase_underscore(name): """ Convert camelcase names to underscore """ s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
python
def camelcase_underscore(name): """ Convert camelcase names to underscore """ s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
[ "def", "camelcase_underscore", "(", "name", ")", ":", "s1", "=", "re", ".", "sub", "(", "'(.)([A-Z][a-z]+)'", ",", "r'\\1_\\2'", ",", "name", ")", "return", "re", ".", "sub", "(", "'([a-z0-9])([A-Z])'", ",", "r'\\1_\\2'", ",", "s1", ")", ".", "lower", "(...
Convert camelcase names to underscore
[ "Convert", "camelcase", "names", "to", "underscore" ]
02bf2f9cb6aff527e492b39518a54f0b4613ddda
https://github.com/developmentseed/sentinel-s3/blob/02bf2f9cb6aff527e492b39518a54f0b4613ddda/sentinel_s3/converter.py#L102-L105
train
Convert camelcase names to underscore
developmentseed/sentinel-s3
sentinel_s3/converter.py
get_tiles_list
def get_tiles_list(element): """ Returns the list of all tile names from Product_Organisation element in metadata.xml """ tiles = {} for el in element: g = (el.findall('.//Granules') or el.findall('.//Granule'))[0] name = g.attrib['granuleIdentifier'] name_parts = name...
python
def get_tiles_list(element): """ Returns the list of all tile names from Product_Organisation element in metadata.xml """ tiles = {} for el in element: g = (el.findall('.//Granules') or el.findall('.//Granule'))[0] name = g.attrib['granuleIdentifier'] name_parts = name...
[ "def", "get_tiles_list", "(", "element", ")", ":", "tiles", "=", "{", "}", "for", "el", "in", "element", ":", "g", "=", "(", "el", ".", "findall", "(", "'.//Granules'", ")", "or", "el", ".", "findall", "(", "'.//Granule'", ")", ")", "[", "0", "]", ...
Returns the list of all tile names from Product_Organisation element in metadata.xml
[ "Returns", "the", "list", "of", "all", "tile", "names", "from", "Product_Organisation", "element", "in", "metadata", ".", "xml" ]
02bf2f9cb6aff527e492b39518a54f0b4613ddda
https://github.com/developmentseed/sentinel-s3/blob/02bf2f9cb6aff527e492b39518a54f0b4613ddda/sentinel_s3/converter.py#L108-L124
train
Returns the list of all tile names from Product_Organisation element in metadata. xml
developmentseed/sentinel-s3
sentinel_s3/converter.py
metadata_to_dict
def metadata_to_dict(metadata): """ Looks at metadata.xml file of sentinel product and extract useful keys Returns a python dict """ tree = etree.parse(metadata) root = tree.getroot() meta = OrderedDict() keys = [ 'SPACECRAFT_NAME', 'PRODUCT_STOP_TIME', 'Cloud_Coverage...
python
def metadata_to_dict(metadata): """ Looks at metadata.xml file of sentinel product and extract useful keys Returns a python dict """ tree = etree.parse(metadata) root = tree.getroot() meta = OrderedDict() keys = [ 'SPACECRAFT_NAME', 'PRODUCT_STOP_TIME', 'Cloud_Coverage...
[ "def", "metadata_to_dict", "(", "metadata", ")", ":", "tree", "=", "etree", ".", "parse", "(", "metadata", ")", "root", "=", "tree", ".", "getroot", "(", ")", "meta", "=", "OrderedDict", "(", ")", "keys", "=", "[", "'SPACECRAFT_NAME'", ",", "'PRODUCT_STO...
Looks at metadata.xml file of sentinel product and extract useful keys Returns a python dict
[ "Looks", "at", "metadata", ".", "xml", "file", "of", "sentinel", "product", "and", "extract", "useful", "keys", "Returns", "a", "python", "dict" ]
02bf2f9cb6aff527e492b39518a54f0b4613ddda
https://github.com/developmentseed/sentinel-s3/blob/02bf2f9cb6aff527e492b39518a54f0b4613ddda/sentinel_s3/converter.py#L127-L184
train
Takes the metadata. xml file of sentinel product and extracts useful keys Returns a python dict
developmentseed/sentinel-s3
sentinel_s3/converter.py
get_tile_geometry
def get_tile_geometry(path, origin_espg, tolerance=500): """ Calculate the data and tile geometry for sentinel-2 tiles """ with rasterio.open(path) as src: # Get tile geometry b = src.bounds tile_shape = Polygon([(b[0], b[1]), (b[2], b[1]), (b[2], b[3]), (b[0], b[3]), (b[0], b[1])]) ...
python
def get_tile_geometry(path, origin_espg, tolerance=500): """ Calculate the data and tile geometry for sentinel-2 tiles """ with rasterio.open(path) as src: # Get tile geometry b = src.bounds tile_shape = Polygon([(b[0], b[1]), (b[2], b[1]), (b[2], b[3]), (b[0], b[3]), (b[0], b[1])]) ...
[ "def", "get_tile_geometry", "(", "path", ",", "origin_espg", ",", "tolerance", "=", "500", ")", ":", "with", "rasterio", ".", "open", "(", "path", ")", "as", "src", ":", "# Get tile geometry", "b", "=", "src", ".", "bounds", "tile_shape", "=", "Polygon", ...
Calculate the data and tile geometry for sentinel-2 tiles
[ "Calculate", "the", "data", "and", "tile", "geometry", "for", "sentinel", "-", "2", "tiles" ]
02bf2f9cb6aff527e492b39518a54f0b4613ddda
https://github.com/developmentseed/sentinel-s3/blob/02bf2f9cb6aff527e492b39518a54f0b4613ddda/sentinel_s3/converter.py#L187-L235
train
Calculate the data and tile geometry for sentinel - 2 tiles
developmentseed/sentinel-s3
sentinel_s3/converter.py
tile_metadata
def tile_metadata(tile, product, geometry_check=None): """ Generate metadata for a given tile - geometry_check is a function the determines whether to calculate the geometry by downloading B01 and override provided geometry in tilejson. The meta object is passed to this function. The function return a ...
python
def tile_metadata(tile, product, geometry_check=None): """ Generate metadata for a given tile - geometry_check is a function the determines whether to calculate the geometry by downloading B01 and override provided geometry in tilejson. The meta object is passed to this function. The function return a ...
[ "def", "tile_metadata", "(", "tile", ",", "product", ",", "geometry_check", "=", "None", ")", ":", "grid", "=", "'T{0}{1}{2}'", ".", "format", "(", "pad", "(", "tile", "[", "'utmZone'", "]", ",", "2", ")", ",", "tile", "[", "'latitudeBand'", "]", ",", ...
Generate metadata for a given tile - geometry_check is a function the determines whether to calculate the geometry by downloading B01 and override provided geometry in tilejson. The meta object is passed to this function. The function return a True or False response.
[ "Generate", "metadata", "for", "a", "given", "tile" ]
02bf2f9cb6aff527e492b39518a54f0b4613ddda
https://github.com/developmentseed/sentinel-s3/blob/02bf2f9cb6aff527e492b39518a54f0b4613ddda/sentinel_s3/converter.py#L266-L324
train
Generate metadata for a given tile
vslutov/turingmarkov
turingmarkov/__main__.py
load_markov
def load_markov(argv, stdin): """Load and return markov algorithm.""" if len(argv) > 3: with open(argv[3]) as input_file: return Algorithm(input_file.readlines()) else: return Algorithm(stdin.readlines())
python
def load_markov(argv, stdin): """Load and return markov algorithm.""" if len(argv) > 3: with open(argv[3]) as input_file: return Algorithm(input_file.readlines()) else: return Algorithm(stdin.readlines())
[ "def", "load_markov", "(", "argv", ",", "stdin", ")", ":", "if", "len", "(", "argv", ")", ">", "3", ":", "with", "open", "(", "argv", "[", "3", "]", ")", "as", "input_file", ":", "return", "Algorithm", "(", "input_file", ".", "readlines", "(", ")",...
Load and return markov algorithm.
[ "Load", "and", "return", "markov", "algorithm", "." ]
63e2ba255d7d0d868cbc4bf3e568b1c1bbcf38ce
https://github.com/vslutov/turingmarkov/blob/63e2ba255d7d0d868cbc4bf3e568b1c1bbcf38ce/turingmarkov/__main__.py#L21-L27
train
Load and return markov algorithm.
vslutov/turingmarkov
turingmarkov/__main__.py
load_turing
def load_turing(argv, stdin): """Load and return turing machine.""" if len(argv) > 3: with open(argv[3]) as input_file: return build_machine(input_file.readlines()) else: return build_machine(stdin.readlines())
python
def load_turing(argv, stdin): """Load and return turing machine.""" if len(argv) > 3: with open(argv[3]) as input_file: return build_machine(input_file.readlines()) else: return build_machine(stdin.readlines())
[ "def", "load_turing", "(", "argv", ",", "stdin", ")", ":", "if", "len", "(", "argv", ")", ">", "3", ":", "with", "open", "(", "argv", "[", "3", "]", ")", "as", "input_file", ":", "return", "build_machine", "(", "input_file", ".", "readlines", "(", ...
Load and return turing machine.
[ "Load", "and", "return", "turing", "machine", "." ]
63e2ba255d7d0d868cbc4bf3e568b1c1bbcf38ce
https://github.com/vslutov/turingmarkov/blob/63e2ba255d7d0d868cbc4bf3e568b1c1bbcf38ce/turingmarkov/__main__.py#L29-L35
train
Load and return turing machine.
vslutov/turingmarkov
turingmarkov/__main__.py
main
def main(argv, stdin, stdout): """Execute, when user call turingmarkov.""" if len(argv) > 1 and argv[1:3] == ["compile", "markov"]: algo = load_markov(argv, stdin) print(algo.compile(), file=stdout) elif len(argv) == 4 and argv[1:3] == ["run", "markov"]: algo = load_markov(argv, stdi...
python
def main(argv, stdin, stdout): """Execute, when user call turingmarkov.""" if len(argv) > 1 and argv[1:3] == ["compile", "markov"]: algo = load_markov(argv, stdin) print(algo.compile(), file=stdout) elif len(argv) == 4 and argv[1:3] == ["run", "markov"]: algo = load_markov(argv, stdi...
[ "def", "main", "(", "argv", ",", "stdin", ",", "stdout", ")", ":", "if", "len", "(", "argv", ")", ">", "1", "and", "argv", "[", "1", ":", "3", "]", "==", "[", "\"compile\"", ",", "\"markov\"", "]", ":", "algo", "=", "load_markov", "(", "argv", ...
Execute, when user call turingmarkov.
[ "Execute", "when", "user", "call", "turingmarkov", "." ]
63e2ba255d7d0d868cbc4bf3e568b1c1bbcf38ce
https://github.com/vslutov/turingmarkov/blob/63e2ba255d7d0d868cbc4bf3e568b1c1bbcf38ce/turingmarkov/__main__.py#L37-L65
train
Execute when user call turingmarkov.
tamasgal/km3pipe
km3pipe/cmd.py
retrieve
def retrieve(run_id, det_id, outfile=None): """Retrieve run from iRODS for a given detector (O)ID""" try: det_id = int(det_id) except ValueError: pass path = irods_filepath(det_id, run_id) suffix = '' if outfile is None else outfile os.system("iget -Pv {0} {1}".format(path, suffi...
python
def retrieve(run_id, det_id, outfile=None): """Retrieve run from iRODS for a given detector (O)ID""" try: det_id = int(det_id) except ValueError: pass path = irods_filepath(det_id, run_id) suffix = '' if outfile is None else outfile os.system("iget -Pv {0} {1}".format(path, suffi...
[ "def", "retrieve", "(", "run_id", ",", "det_id", ",", "outfile", "=", "None", ")", ":", "try", ":", "det_id", "=", "int", "(", "det_id", ")", "except", "ValueError", ":", "pass", "path", "=", "irods_filepath", "(", "det_id", ",", "run_id", ")", "suffix...
Retrieve run from iRODS for a given detector (O)ID
[ "Retrieve", "run", "from", "iRODS", "for", "a", "given", "detector", "(", "O", ")", "ID" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/cmd.py#L86-L94
train
Retrieve a run from iRODS for a given detector ID
tamasgal/km3pipe
km3pipe/cmd.py
detectors
def detectors(regex=None, sep='\t', temporary=False): """Print the detectors table""" db = DBManager(temporary=temporary) dt = db.detectors if regex is not None: try: re.compile(regex) except re.error: log.error("Invalid regex!") return dt = dt...
python
def detectors(regex=None, sep='\t', temporary=False): """Print the detectors table""" db = DBManager(temporary=temporary) dt = db.detectors if regex is not None: try: re.compile(regex) except re.error: log.error("Invalid regex!") return dt = dt...
[ "def", "detectors", "(", "regex", "=", "None", ",", "sep", "=", "'\\t'", ",", "temporary", "=", "False", ")", ":", "db", "=", "DBManager", "(", "temporary", "=", "temporary", ")", "dt", "=", "db", ".", "detectors", "if", "regex", "is", "not", "None",...
Print the detectors table
[ "Print", "the", "detectors", "table" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/cmd.py#L112-L123
train
Print the detectors table
tamasgal/km3pipe
km3pipe/cmd.py
rundetsn
def rundetsn(run_id, detector="ARCA", temporary=False): """Print the detector serial number for a given run of ARCA/ORCA""" db = DBManager(temporary=temporary) dts = db.detectors for det_id in dts[dts.OID.str.contains(detector)].SERIALNUMBER: if run_id in db.run_table(det_id).RUN.values: ...
python
def rundetsn(run_id, detector="ARCA", temporary=False): """Print the detector serial number for a given run of ARCA/ORCA""" db = DBManager(temporary=temporary) dts = db.detectors for det_id in dts[dts.OID.str.contains(detector)].SERIALNUMBER: if run_id in db.run_table(det_id).RUN.values: ...
[ "def", "rundetsn", "(", "run_id", ",", "detector", "=", "\"ARCA\"", ",", "temporary", "=", "False", ")", ":", "db", "=", "DBManager", "(", "temporary", "=", "temporary", ")", "dts", "=", "db", ".", "detectors", "for", "det_id", "in", "dts", "[", "dts",...
Print the detector serial number for a given run of ARCA/ORCA
[ "Print", "the", "detector", "serial", "number", "for", "a", "given", "run", "of", "ARCA", "/", "ORCA" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/cmd.py#L126-L133
train
Print the detector serial number for a given run of ARCA or ORCA
PrefPy/prefpy
prefpy/stats.py
mse
def mse(mean, estimator): """ Description: Calculates the Mean Squared Error (MSE) of an estimation on flat numpy ndarrays. Parameters: mean: actual value (numpy ndarray) estimator: estimated value of the mean (numpy ndarray) """ return np.mean((np.asarr...
python
def mse(mean, estimator): """ Description: Calculates the Mean Squared Error (MSE) of an estimation on flat numpy ndarrays. Parameters: mean: actual value (numpy ndarray) estimator: estimated value of the mean (numpy ndarray) """ return np.mean((np.asarr...
[ "def", "mse", "(", "mean", ",", "estimator", ")", ":", "return", "np", ".", "mean", "(", "(", "np", ".", "asarray", "(", "estimator", ")", "-", "np", ".", "asarray", "(", "mean", ")", ")", "**", "2", ",", "axis", "=", "0", ")" ]
Description: Calculates the Mean Squared Error (MSE) of an estimation on flat numpy ndarrays. Parameters: mean: actual value (numpy ndarray) estimator: estimated value of the mean (numpy ndarray)
[ "Description", ":", "Calculates", "the", "Mean", "Squared", "Error", "(", "MSE", ")", "of", "an", "estimation", "on", "flat", "numpy", "ndarrays", ".", "Parameters", ":", "mean", ":", "actual", "value", "(", "numpy", "ndarray", ")", "estimator", ":", "esti...
f395ba3782f05684fa5de0cece387a6da9391d02
https://github.com/PrefPy/prefpy/blob/f395ba3782f05684fa5de0cece387a6da9391d02/prefpy/stats.py#L22-L31
train
Returns the Mean Squared Error of a single record in a flat numpy ndarrays.
PrefPy/prefpy
prefpy/stats.py
sse
def sse(mean, estimator): """ Description: Calculates the Sum of Squared Errors (SSE) of an estimation on flat numpy ndarrays. Parameters: mean: actual value (numpy ndarray) estimator: estimated value of the mean (numpy ndarray) """ return np.sum((np.asa...
python
def sse(mean, estimator): """ Description: Calculates the Sum of Squared Errors (SSE) of an estimation on flat numpy ndarrays. Parameters: mean: actual value (numpy ndarray) estimator: estimated value of the mean (numpy ndarray) """ return np.sum((np.asa...
[ "def", "sse", "(", "mean", ",", "estimator", ")", ":", "return", "np", ".", "sum", "(", "(", "np", ".", "asarray", "(", "estimator", ")", "-", "np", ".", "asarray", "(", "mean", ")", ")", "**", "2", ",", "axis", "=", "0", ")" ]
Description: Calculates the Sum of Squared Errors (SSE) of an estimation on flat numpy ndarrays. Parameters: mean: actual value (numpy ndarray) estimator: estimated value of the mean (numpy ndarray)
[ "Description", ":", "Calculates", "the", "Sum", "of", "Squared", "Errors", "(", "SSE", ")", "of", "an", "estimation", "on", "flat", "numpy", "ndarrays", ".", "Parameters", ":", "mean", ":", "actual", "value", "(", "numpy", "ndarray", ")", "estimator", ":",...
f395ba3782f05684fa5de0cece387a6da9391d02
https://github.com/PrefPy/prefpy/blob/f395ba3782f05684fa5de0cece387a6da9391d02/prefpy/stats.py#L33-L42
train
Returns the sum of squared errors of a given time series
PrefPy/prefpy
prefpy/stats.py
mix2PL_mse
def mix2PL_mse(mean, estimator, m): """ Description: Calculates the Mean Squared Error (MSE) of an estimator of a mixture of 2 Plackett-Luce models, on flat numpy ndarrays, where the first element is the mixing proportion of the first model defined as the minimum M...
python
def mix2PL_mse(mean, estimator, m): """ Description: Calculates the Mean Squared Error (MSE) of an estimator of a mixture of 2 Plackett-Luce models, on flat numpy ndarrays, where the first element is the mixing proportion of the first model defined as the minimum M...
[ "def", "mix2PL_mse", "(", "mean", ",", "estimator", ",", "m", ")", ":", "mse1", "=", "mse", "(", "mean", ",", "estimator", ")", "estimator", "=", "np", ".", "hstack", "(", "(", "1", "-", "estimator", "[", "0", "]", ",", "estimator", "[", "m", "+"...
Description: Calculates the Mean Squared Error (MSE) of an estimator of a mixture of 2 Plackett-Luce models, on flat numpy ndarrays, where the first element is the mixing proportion of the first model defined as the minimum MSE over the inverse permutations of the e...
[ "Description", ":", "Calculates", "the", "Mean", "Squared", "Error", "(", "MSE", ")", "of", "an", "estimator", "of", "a", "mixture", "of", "2", "Plackett", "-", "Luce", "models", "on", "flat", "numpy", "ndarrays", "where", "the", "first", "element", "is", ...
f395ba3782f05684fa5de0cece387a6da9391d02
https://github.com/PrefPy/prefpy/blob/f395ba3782f05684fa5de0cece387a6da9391d02/prefpy/stats.py#L45-L62
train
Returns the mean squared error of an estimator over the inverse permutations of the first model in the model - 2 Plackett - Luce models.
PrefPy/prefpy
prefpy/stats.py
mix2PL_sse
def mix2PL_sse(mean, estimator, m): """ Description: Calculates the Sum of Squared Errors (SSE) of an estimator of a mixture of 2 Plackett-Luce models, on flat numpy ndarrays, where the first element is the mixing proportion of the first model defined as the minimu...
python
def mix2PL_sse(mean, estimator, m): """ Description: Calculates the Sum of Squared Errors (SSE) of an estimator of a mixture of 2 Plackett-Luce models, on flat numpy ndarrays, where the first element is the mixing proportion of the first model defined as the minimu...
[ "def", "mix2PL_sse", "(", "mean", ",", "estimator", ",", "m", ")", ":", "sse1", "=", "sse", "(", "mean", ",", "estimator", ")", "estimator", "=", "np", ".", "hstack", "(", "(", "1", "-", "estimator", "[", "0", "]", ",", "estimator", "[", "m", "+"...
Description: Calculates the Sum of Squared Errors (SSE) of an estimator of a mixture of 2 Plackett-Luce models, on flat numpy ndarrays, where the first element is the mixing proportion of the first model defined as the minimum SSE over the inverse permutations of th...
[ "Description", ":", "Calculates", "the", "Sum", "of", "Squared", "Errors", "(", "SSE", ")", "of", "an", "estimator", "of", "a", "mixture", "of", "2", "Plackett", "-", "Luce", "models", "on", "flat", "numpy", "ndarrays", "where", "the", "first", "element", ...
f395ba3782f05684fa5de0cece387a6da9391d02
https://github.com/PrefPy/prefpy/blob/f395ba3782f05684fa5de0cece387a6da9391d02/prefpy/stats.py#L65-L82
train
Returns the sum of squared errors of an estimator over the inverse permutations of the first model in the estimator.
PrefPy/prefpy
prefpy/stats.py
mix2PL_wsse
def mix2PL_wsse(mean, estimator, m): """ Description: Calculates the weighted Sum of Squared Errors (WSSE) of an estimator of a mixture of 2 Plackett-Luce models, on flat numpy ndarrays, where the first element is the mixing proportion of the first model defined as...
python
def mix2PL_wsse(mean, estimator, m): """ Description: Calculates the weighted Sum of Squared Errors (WSSE) of an estimator of a mixture of 2 Plackett-Luce models, on flat numpy ndarrays, where the first element is the mixing proportion of the first model defined as...
[ "def", "mix2PL_wsse", "(", "mean", ",", "estimator", ",", "m", ")", ":", "def", "wsse", "(", "mean1", ",", "est1", ",", "m1", ")", ":", "return", "(", "(", "(", "est1", "[", "0", "]", "-", "mean1", "[", "0", "]", ")", "**", "2", ")", "+", "...
Description: Calculates the weighted Sum of Squared Errors (WSSE) of an estimator of a mixture of 2 Plackett-Luce models, on flat numpy ndarrays, where the first element is the mixing proportion of the first model defined as the minimum WSSE over the inverse permutations of ...
[ "Description", ":", "Calculates", "the", "weighted", "Sum", "of", "Squared", "Errors", "(", "WSSE", ")", "of", "an", "estimator", "of", "a", "mixture", "of", "2", "Plackett", "-", "Luce", "models", "on", "flat", "numpy", "ndarrays", "where", "the", "first"...
f395ba3782f05684fa5de0cece387a6da9391d02
https://github.com/PrefPy/prefpy/blob/f395ba3782f05684fa5de0cece387a6da9391d02/prefpy/stats.py#L85-L107
train
Returns the minimum WSSE over the inverse permutations of the estimator of the 2 Plackett - Luce models.