id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
18,500 | python-beaver/python-beaver | beaver/ssh_tunnel.py | BeaverSubprocess.poll | def poll(self):
"""Poll attached subprocess until it is available"""
if self._subprocess is not None:
self._subprocess.poll()
time.sleep(self._beaver_config.get('subprocess_poll_sleep')) | python | def poll(self):
if self._subprocess is not None:
self._subprocess.poll()
time.sleep(self._beaver_config.get('subprocess_poll_sleep')) | [
"def",
"poll",
"(",
"self",
")",
":",
"if",
"self",
".",
"_subprocess",
"is",
"not",
"None",
":",
"self",
".",
"_subprocess",
".",
"poll",
"(",
")",
"time",
".",
"sleep",
"(",
"self",
".",
"_beaver_config",
".",
"get",
"(",
"'subprocess_poll_sleep'",
"... | Poll attached subprocess until it is available | [
"Poll",
"attached",
"subprocess",
"until",
"it",
"is",
"available"
] | 93941e968016c5a962dffed9e7a9f6dc1d23236c | https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/ssh_tunnel.py#L43-L48 |
18,501 | python-beaver/python-beaver | beaver/ssh_tunnel.py | BeaverSubprocess.close | def close(self):
"""Close child subprocess"""
if self._subprocess is not None:
os.killpg(self._subprocess.pid, signal.SIGTERM)
self._subprocess = None | python | def close(self):
if self._subprocess is not None:
os.killpg(self._subprocess.pid, signal.SIGTERM)
self._subprocess = None | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"_subprocess",
"is",
"not",
"None",
":",
"os",
".",
"killpg",
"(",
"self",
".",
"_subprocess",
".",
"pid",
",",
"signal",
".",
"SIGTERM",
")",
"self",
".",
"_subprocess",
"=",
"None"
] | Close child subprocess | [
"Close",
"child",
"subprocess"
] | 93941e968016c5a962dffed9e7a9f6dc1d23236c | https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/ssh_tunnel.py#L50-L54 |
18,502 | python-beaver/python-beaver | beaver/unicode_dammit.py | _to_unicode | def _to_unicode(self, data, encoding, errors='strict'):
'''Given a string and its encoding, decodes the string into Unicode.
%encoding is a string recognized by encodings.aliases'''
# strip Byte Order Mark (if present)
if (len(data) >= 4) and (data[:2] == '\xfe\xff') and (data[2:4] != '\x00\x00'):
encoding = 'utf-16be'
data = data[2:]
elif (len(data) >= 4) and (data[:2] == '\xff\xfe') and (data[2:4] != '\x00\x00'):
encoding = 'utf-16le'
data = data[2:]
elif data[:3] == '\xef\xbb\xbf':
encoding = 'utf-8'
data = data[3:]
elif data[:4] == '\x00\x00\xfe\xff':
encoding = 'utf-32be'
data = data[4:]
elif data[:4] == '\xff\xfe\x00\x00':
encoding = 'utf-32le'
data = data[4:]
newdata = unicode(data, encoding, errors)
return newdata | python | def _to_unicode(self, data, encoding, errors='strict'):
'''Given a string and its encoding, decodes the string into Unicode.
%encoding is a string recognized by encodings.aliases'''
# strip Byte Order Mark (if present)
if (len(data) >= 4) and (data[:2] == '\xfe\xff') and (data[2:4] != '\x00\x00'):
encoding = 'utf-16be'
data = data[2:]
elif (len(data) >= 4) and (data[:2] == '\xff\xfe') and (data[2:4] != '\x00\x00'):
encoding = 'utf-16le'
data = data[2:]
elif data[:3] == '\xef\xbb\xbf':
encoding = 'utf-8'
data = data[3:]
elif data[:4] == '\x00\x00\xfe\xff':
encoding = 'utf-32be'
data = data[4:]
elif data[:4] == '\xff\xfe\x00\x00':
encoding = 'utf-32le'
data = data[4:]
newdata = unicode(data, encoding, errors)
return newdata | [
"def",
"_to_unicode",
"(",
"self",
",",
"data",
",",
"encoding",
",",
"errors",
"=",
"'strict'",
")",
":",
"# strip Byte Order Mark (if present)",
"if",
"(",
"len",
"(",
"data",
")",
">=",
"4",
")",
"and",
"(",
"data",
"[",
":",
"2",
"]",
"==",
"'\\xfe... | Given a string and its encoding, decodes the string into Unicode.
%encoding is a string recognized by encodings.aliases | [
"Given",
"a",
"string",
"and",
"its",
"encoding",
"decodes",
"the",
"string",
"into",
"Unicode",
".",
"%encoding",
"is",
"a",
"string",
"recognized",
"by",
"encodings",
".",
"aliases"
] | 93941e968016c5a962dffed9e7a9f6dc1d23236c | https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/unicode_dammit.py#L38-L59 |
18,503 | python-beaver/python-beaver | beaver/transports/stomp_transport.py | StompTransport.reconnect | def reconnect(self):
"""Allows reconnection from when a handled
TransportException is thrown"""
try:
self.conn.close()
except Exception,e:
self.logger.warn(e)
self.createConnection()
return True | python | def reconnect(self):
try:
self.conn.close()
except Exception,e:
self.logger.warn(e)
self.createConnection()
return True | [
"def",
"reconnect",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"conn",
".",
"close",
"(",
")",
"except",
"Exception",
",",
"e",
":",
"self",
".",
"logger",
".",
"warn",
"(",
"e",
")",
"self",
".",
"createConnection",
"(",
")",
"return",
"True"... | Allows reconnection from when a handled
TransportException is thrown | [
"Allows",
"reconnection",
"from",
"when",
"a",
"handled",
"TransportException",
"is",
"thrown"
] | 93941e968016c5a962dffed9e7a9f6dc1d23236c | https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/transports/stomp_transport.py#L64-L74 |
18,504 | python-beaver/python-beaver | beaver/transports/redis_transport.py | RedisTransport._check_connections | def _check_connections(self):
"""Checks if all configured redis servers are reachable"""
for server in self._servers:
if self._is_reachable(server):
server['down_until'] = 0
else:
server['down_until'] = time.time() + 5 | python | def _check_connections(self):
for server in self._servers:
if self._is_reachable(server):
server['down_until'] = 0
else:
server['down_until'] = time.time() + 5 | [
"def",
"_check_connections",
"(",
"self",
")",
":",
"for",
"server",
"in",
"self",
".",
"_servers",
":",
"if",
"self",
".",
"_is_reachable",
"(",
"server",
")",
":",
"server",
"[",
"'down_until'",
"]",
"=",
"0",
"else",
":",
"server",
"[",
"'down_until'"... | Checks if all configured redis servers are reachable | [
"Checks",
"if",
"all",
"configured",
"redis",
"servers",
"are",
"reachable"
] | 93941e968016c5a962dffed9e7a9f6dc1d23236c | https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/transports/redis_transport.py#L38-L45 |
18,505 | python-beaver/python-beaver | beaver/transports/redis_transport.py | RedisTransport._is_reachable | def _is_reachable(self, server):
"""Checks if the given redis server is reachable"""
try:
server['redis'].ping()
return True
except UserWarning:
self._logger.warn('Cannot reach redis server: ' + server['url'])
except Exception:
self._logger.warn('Cannot reach redis server: ' + server['url'])
return False | python | def _is_reachable(self, server):
try:
server['redis'].ping()
return True
except UserWarning:
self._logger.warn('Cannot reach redis server: ' + server['url'])
except Exception:
self._logger.warn('Cannot reach redis server: ' + server['url'])
return False | [
"def",
"_is_reachable",
"(",
"self",
",",
"server",
")",
":",
"try",
":",
"server",
"[",
"'redis'",
"]",
".",
"ping",
"(",
")",
"return",
"True",
"except",
"UserWarning",
":",
"self",
".",
"_logger",
".",
"warn",
"(",
"'Cannot reach redis server: '",
"+",
... | Checks if the given redis server is reachable | [
"Checks",
"if",
"the",
"given",
"redis",
"server",
"is",
"reachable"
] | 93941e968016c5a962dffed9e7a9f6dc1d23236c | https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/transports/redis_transport.py#L47-L58 |
18,506 | python-beaver/python-beaver | beaver/transports/redis_transport.py | RedisTransport.invalidate | def invalidate(self):
"""Invalidates the current transport and disconnects all redis connections"""
super(RedisTransport, self).invalidate()
for server in self._servers:
server['redis'].connection_pool.disconnect()
return False | python | def invalidate(self):
super(RedisTransport, self).invalidate()
for server in self._servers:
server['redis'].connection_pool.disconnect()
return False | [
"def",
"invalidate",
"(",
"self",
")",
":",
"super",
"(",
"RedisTransport",
",",
"self",
")",
".",
"invalidate",
"(",
")",
"for",
"server",
"in",
"self",
".",
"_servers",
":",
"server",
"[",
"'redis'",
"]",
".",
"connection_pool",
".",
"disconnect",
"(",... | Invalidates the current transport and disconnects all redis connections | [
"Invalidates",
"the",
"current",
"transport",
"and",
"disconnects",
"all",
"redis",
"connections"
] | 93941e968016c5a962dffed9e7a9f6dc1d23236c | https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/transports/redis_transport.py#L63-L69 |
18,507 | python-beaver/python-beaver | beaver/transports/redis_transport.py | RedisTransport.callback | def callback(self, filename, lines, **kwargs):
"""Sends log lines to redis servers"""
self._logger.debug('Redis transport called')
timestamp = self.get_timestamp(**kwargs)
if kwargs.get('timestamp', False):
del kwargs['timestamp']
namespaces = self._beaver_config.get_field('redis_namespace', filename)
if not namespaces:
namespaces = self._namespace
namespaces = namespaces.split(",")
self._logger.debug('Got namespaces: '.join(namespaces))
data_type = self._data_type
self._logger.debug('Got data type: ' + data_type)
server = self._get_next_server()
self._logger.debug('Got redis server: ' + server['url'])
pipeline = server['redis'].pipeline(transaction=False)
callback_map = {
self.LIST_DATA_TYPE: pipeline.rpush,
self.CHANNEL_DATA_TYPE: pipeline.publish,
}
callback_method = callback_map[data_type]
for line in lines:
for namespace in namespaces:
callback_method(
namespace.strip(),
self.format(filename, line, timestamp, **kwargs)
)
try:
pipeline.execute()
except redis.exceptions.RedisError, exception:
self._logger.warn('Cannot push lines to redis server: ' + server['url'])
raise TransportException(exception) | python | def callback(self, filename, lines, **kwargs):
self._logger.debug('Redis transport called')
timestamp = self.get_timestamp(**kwargs)
if kwargs.get('timestamp', False):
del kwargs['timestamp']
namespaces = self._beaver_config.get_field('redis_namespace', filename)
if not namespaces:
namespaces = self._namespace
namespaces = namespaces.split(",")
self._logger.debug('Got namespaces: '.join(namespaces))
data_type = self._data_type
self._logger.debug('Got data type: ' + data_type)
server = self._get_next_server()
self._logger.debug('Got redis server: ' + server['url'])
pipeline = server['redis'].pipeline(transaction=False)
callback_map = {
self.LIST_DATA_TYPE: pipeline.rpush,
self.CHANNEL_DATA_TYPE: pipeline.publish,
}
callback_method = callback_map[data_type]
for line in lines:
for namespace in namespaces:
callback_method(
namespace.strip(),
self.format(filename, line, timestamp, **kwargs)
)
try:
pipeline.execute()
except redis.exceptions.RedisError, exception:
self._logger.warn('Cannot push lines to redis server: ' + server['url'])
raise TransportException(exception) | [
"def",
"callback",
"(",
"self",
",",
"filename",
",",
"lines",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_logger",
".",
"debug",
"(",
"'Redis transport called'",
")",
"timestamp",
"=",
"self",
".",
"get_timestamp",
"(",
"*",
"*",
"kwargs",
")",
... | Sends log lines to redis servers | [
"Sends",
"log",
"lines",
"to",
"redis",
"servers"
] | 93941e968016c5a962dffed9e7a9f6dc1d23236c | https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/transports/redis_transport.py#L71-L112 |
18,508 | python-beaver/python-beaver | beaver/transports/redis_transport.py | RedisTransport._get_next_server | def _get_next_server(self):
"""Returns a valid redis server or raises a TransportException"""
current_try = 0
max_tries = len(self._servers)
while current_try < max_tries:
server_index = self._raise_server_index()
server = self._servers[server_index]
down_until = server['down_until']
self._logger.debug('Checking server ' + str(current_try + 1) + '/' + str(max_tries) + ': ' + server['url'])
if down_until == 0:
self._logger.debug('Elected server: ' + server['url'])
return server
if down_until < time.time():
if self._is_reachable(server):
server['down_until'] = 0
self._logger.debug('Elected server: ' + server['url'])
return server
else:
self._logger.debug('Server still unavailable: ' + server['url'])
server['down_until'] = time.time() + 5
current_try += 1
raise TransportException('Cannot reach any redis server') | python | def _get_next_server(self):
current_try = 0
max_tries = len(self._servers)
while current_try < max_tries:
server_index = self._raise_server_index()
server = self._servers[server_index]
down_until = server['down_until']
self._logger.debug('Checking server ' + str(current_try + 1) + '/' + str(max_tries) + ': ' + server['url'])
if down_until == 0:
self._logger.debug('Elected server: ' + server['url'])
return server
if down_until < time.time():
if self._is_reachable(server):
server['down_until'] = 0
self._logger.debug('Elected server: ' + server['url'])
return server
else:
self._logger.debug('Server still unavailable: ' + server['url'])
server['down_until'] = time.time() + 5
current_try += 1
raise TransportException('Cannot reach any redis server') | [
"def",
"_get_next_server",
"(",
"self",
")",
":",
"current_try",
"=",
"0",
"max_tries",
"=",
"len",
"(",
"self",
".",
"_servers",
")",
"while",
"current_try",
"<",
"max_tries",
":",
"server_index",
"=",
"self",
".",
"_raise_server_index",
"(",
")",
"server",... | Returns a valid redis server or raises a TransportException | [
"Returns",
"a",
"valid",
"redis",
"server",
"or",
"raises",
"a",
"TransportException"
] | 93941e968016c5a962dffed9e7a9f6dc1d23236c | https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/transports/redis_transport.py#L114-L144 |
18,509 | python-beaver/python-beaver | beaver/transports/redis_transport.py | RedisTransport.valid | def valid(self):
"""Returns whether or not the transport can send data to any redis server"""
valid_servers = 0
for server in self._servers:
if server['down_until'] <= time.time():
valid_servers += 1
return valid_servers > 0 | python | def valid(self):
valid_servers = 0
for server in self._servers:
if server['down_until'] <= time.time():
valid_servers += 1
return valid_servers > 0 | [
"def",
"valid",
"(",
"self",
")",
":",
"valid_servers",
"=",
"0",
"for",
"server",
"in",
"self",
".",
"_servers",
":",
"if",
"server",
"[",
"'down_until'",
"]",
"<=",
"time",
".",
"time",
"(",
")",
":",
"valid_servers",
"+=",
"1",
"return",
"valid_serv... | Returns whether or not the transport can send data to any redis server | [
"Returns",
"whether",
"or",
"not",
"the",
"transport",
"can",
"send",
"data",
"to",
"any",
"redis",
"server"
] | 93941e968016c5a962dffed9e7a9f6dc1d23236c | https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/transports/redis_transport.py#L154-L162 |
18,510 | python-beaver/python-beaver | beaver/transports/base_transport.py | BaseTransport.format | def format(self, filename, line, timestamp, **kwargs):
"""Returns a formatted log line"""
line = unicode(line.encode("utf-8"), "utf-8", errors="ignore")
formatter = self._beaver_config.get_field('format', filename)
if formatter not in self._formatters:
formatter = self._default_formatter
data = {
self._fields.get('type'): kwargs.get('type'),
self._fields.get('tags'): kwargs.get('tags'),
'@timestamp': timestamp,
self._fields.get('host'): self._current_host,
self._fields.get('file'): filename,
self._fields.get('message'): line
}
if self._logstash_version == 0:
data['@source'] = 'file://{0}'.format(filename)
data['@fields'] = kwargs.get('fields')
else:
data['@version'] = self._logstash_version
fields = kwargs.get('fields')
for key in fields:
data[key] = fields.get(key)
return self._formatters[formatter](data) | python | def format(self, filename, line, timestamp, **kwargs):
line = unicode(line.encode("utf-8"), "utf-8", errors="ignore")
formatter = self._beaver_config.get_field('format', filename)
if formatter not in self._formatters:
formatter = self._default_formatter
data = {
self._fields.get('type'): kwargs.get('type'),
self._fields.get('tags'): kwargs.get('tags'),
'@timestamp': timestamp,
self._fields.get('host'): self._current_host,
self._fields.get('file'): filename,
self._fields.get('message'): line
}
if self._logstash_version == 0:
data['@source'] = 'file://{0}'.format(filename)
data['@fields'] = kwargs.get('fields')
else:
data['@version'] = self._logstash_version
fields = kwargs.get('fields')
for key in fields:
data[key] = fields.get(key)
return self._formatters[formatter](data) | [
"def",
"format",
"(",
"self",
",",
"filename",
",",
"line",
",",
"timestamp",
",",
"*",
"*",
"kwargs",
")",
":",
"line",
"=",
"unicode",
"(",
"line",
".",
"encode",
"(",
"\"utf-8\"",
")",
",",
"\"utf-8\"",
",",
"errors",
"=",
"\"ignore\"",
")",
"form... | Returns a formatted log line | [
"Returns",
"a",
"formatted",
"log",
"line"
] | 93941e968016c5a962dffed9e7a9f6dc1d23236c | https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/transports/base_transport.py#L117-L142 |
18,511 | python-beaver/python-beaver | beaver/transports/base_transport.py | BaseTransport.get_timestamp | def get_timestamp(self, **kwargs):
"""Retrieves the timestamp for a given set of data"""
timestamp = kwargs.get('timestamp')
if not timestamp:
now = datetime.datetime.utcnow()
timestamp = now.strftime("%Y-%m-%dT%H:%M:%S") + ".%03d" % (now.microsecond / 1000) + "Z"
return timestamp | python | def get_timestamp(self, **kwargs):
timestamp = kwargs.get('timestamp')
if not timestamp:
now = datetime.datetime.utcnow()
timestamp = now.strftime("%Y-%m-%dT%H:%M:%S") + ".%03d" % (now.microsecond / 1000) + "Z"
return timestamp | [
"def",
"get_timestamp",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"timestamp",
"=",
"kwargs",
".",
"get",
"(",
"'timestamp'",
")",
"if",
"not",
"timestamp",
":",
"now",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"timestamp",
"=",
... | Retrieves the timestamp for a given set of data | [
"Retrieves",
"the",
"timestamp",
"for",
"a",
"given",
"set",
"of",
"data"
] | 93941e968016c5a962dffed9e7a9f6dc1d23236c | https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/transports/base_transport.py#L144-L151 |
18,512 | gqmelo/exec-wrappers | exec_wrappers/create_wrappers.py | _make_executable | def _make_executable(path):
"""Make the file at path executable."""
os.chmod(path, os.stat(path).st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH) | python | def _make_executable(path):
os.chmod(path, os.stat(path).st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH) | [
"def",
"_make_executable",
"(",
"path",
")",
":",
"os",
".",
"chmod",
"(",
"path",
",",
"os",
".",
"stat",
"(",
"path",
")",
".",
"st_mode",
"|",
"stat",
".",
"S_IXUSR",
"|",
"stat",
".",
"S_IXGRP",
"|",
"stat",
".",
"S_IXOTH",
")"
] | Make the file at path executable. | [
"Make",
"the",
"file",
"at",
"path",
"executable",
"."
] | 0faf892a103cf03d005f1dbdc71ca52d279b4e3b | https://github.com/gqmelo/exec-wrappers/blob/0faf892a103cf03d005f1dbdc71ca52d279b4e3b/exec_wrappers/create_wrappers.py#L300-L302 |
18,513 | cmap/cmapPy | cmapPy/pandasGEXpress/subset.py | build_parser | def build_parser():
"""Build argument parser."""
parser = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
# Required args
parser.add_argument("--in_path", "-i", required=True,
help="file path to input GCT(x) file")
parser.add_argument("--rid", nargs="+", help="filepath to grp file or string array for including rows")
parser.add_argument("--cid", nargs="+", help="filepath to grp file or string array for including cols")
parser.add_argument("--exclude_rid", "-er", nargs="+", help="filepath to grp file or string array for excluding rows")
parser.add_argument("--exclude_cid", "-ec", nargs="+", help="filepath to grp file or string array for excluding cols")
parser.add_argument("--out_name", "-o", default="ds_subsetted.gct",
help="what to name the output file")
parser.add_argument("--out_type", default="gct", choices=["gct", "gctx"],
help="whether to write output as GCT or GCTx")
parser.add_argument("--verbose", "-v", action="store_true", default=False,
help="whether to increase the # of messages reported")
return parser | python | def build_parser():
parser = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
# Required args
parser.add_argument("--in_path", "-i", required=True,
help="file path to input GCT(x) file")
parser.add_argument("--rid", nargs="+", help="filepath to grp file or string array for including rows")
parser.add_argument("--cid", nargs="+", help="filepath to grp file or string array for including cols")
parser.add_argument("--exclude_rid", "-er", nargs="+", help="filepath to grp file or string array for excluding rows")
parser.add_argument("--exclude_cid", "-ec", nargs="+", help="filepath to grp file or string array for excluding cols")
parser.add_argument("--out_name", "-o", default="ds_subsetted.gct",
help="what to name the output file")
parser.add_argument("--out_type", default="gct", choices=["gct", "gctx"],
help="whether to write output as GCT or GCTx")
parser.add_argument("--verbose", "-v", action="store_true", default=False,
help="whether to increase the # of messages reported")
return parser | [
"def",
"build_parser",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"__doc__",
",",
"formatter_class",
"=",
"argparse",
".",
"ArgumentDefaultsHelpFormatter",
")",
"# Required args",
"parser",
".",
"add_argument",
"(",
"... | Build argument parser. | [
"Build",
"argument",
"parser",
"."
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/subset.py#L28-L49 |
18,514 | cmap/cmapPy | cmapPy/pandasGEXpress/subset.py | _read_arg | def _read_arg(arg):
"""
If arg is a list with 1 element that corresponds to a valid file path, use
set_io.grp to read the grp file. Otherwise, check that arg is a list of strings.
Args:
arg (list or None)
Returns:
arg_out (list or None)
"""
# If arg is None, just return it back
if arg is None:
arg_out = arg
else:
# If len(arg) == 1 and arg[0] is a valid filepath, read it as a grp file
if len(arg) == 1 and os.path.exists(arg[0]):
arg_out = grp.read(arg[0])
else:
arg_out = arg
# Make sure that arg_out is a list of strings
assert isinstance(arg_out, list), "arg_out must be a list."
assert type(arg_out[0]) == str, "arg_out must be a list of strings."
return arg_out | python | def _read_arg(arg):
# If arg is None, just return it back
if arg is None:
arg_out = arg
else:
# If len(arg) == 1 and arg[0] is a valid filepath, read it as a grp file
if len(arg) == 1 and os.path.exists(arg[0]):
arg_out = grp.read(arg[0])
else:
arg_out = arg
# Make sure that arg_out is a list of strings
assert isinstance(arg_out, list), "arg_out must be a list."
assert type(arg_out[0]) == str, "arg_out must be a list of strings."
return arg_out | [
"def",
"_read_arg",
"(",
"arg",
")",
":",
"# If arg is None, just return it back",
"if",
"arg",
"is",
"None",
":",
"arg_out",
"=",
"arg",
"else",
":",
"# If len(arg) == 1 and arg[0] is a valid filepath, read it as a grp file",
"if",
"len",
"(",
"arg",
")",
"==",
"1",
... | If arg is a list with 1 element that corresponds to a valid file path, use
set_io.grp to read the grp file. Otherwise, check that arg is a list of strings.
Args:
arg (list or None)
Returns:
arg_out (list or None) | [
"If",
"arg",
"is",
"a",
"list",
"with",
"1",
"element",
"that",
"corresponds",
"to",
"a",
"valid",
"file",
"path",
"use",
"set_io",
".",
"grp",
"to",
"read",
"the",
"grp",
"file",
".",
"Otherwise",
"check",
"that",
"arg",
"is",
"a",
"list",
"of",
"st... | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/subset.py#L94-L121 |
18,515 | cmap/cmapPy | cmapPy/set_io/gmt.py | read | def read(file_path):
""" Read a gmt file at the path specified by file_path.
Args:
file_path (string): path to gmt file
Returns:
gmt (GMT object): list of dicts, where each dict corresponds to one
line of the GMT file
"""
# Read in file
actual_file_path = os.path.expanduser(file_path)
with open(actual_file_path, 'r') as f:
lines = f.readlines()
# Create GMT object
gmt = []
# Iterate over each line
for line_num, line in enumerate(lines):
# Separate along tabs
fields = line.split('\t')
assert len(fields) > 2, (
"Each line must have at least 3 tab-delimited items. " +
"line_num: {}, fields: {}").format(line_num, fields)
# Get rid of trailing whitespace
fields[-1] = fields[-1].rstrip()
# Collect entries
entries = fields[2:]
# Remove empty entries
entries = [x for x in entries if x]
assert len(set(entries)) == len(entries), (
"There should not be duplicate entries for the same set. " +
"line_num: {}, entries: {}").format(line_num, entries)
# Store this line as a dictionary
line_dict = {SET_IDENTIFIER_FIELD: fields[0],
SET_DESC_FIELD: fields[1],
SET_MEMBERS_FIELD: entries}
gmt.append(line_dict)
verify_gmt_integrity(gmt)
return gmt | python | def read(file_path):
# Read in file
actual_file_path = os.path.expanduser(file_path)
with open(actual_file_path, 'r') as f:
lines = f.readlines()
# Create GMT object
gmt = []
# Iterate over each line
for line_num, line in enumerate(lines):
# Separate along tabs
fields = line.split('\t')
assert len(fields) > 2, (
"Each line must have at least 3 tab-delimited items. " +
"line_num: {}, fields: {}").format(line_num, fields)
# Get rid of trailing whitespace
fields[-1] = fields[-1].rstrip()
# Collect entries
entries = fields[2:]
# Remove empty entries
entries = [x for x in entries if x]
assert len(set(entries)) == len(entries), (
"There should not be duplicate entries for the same set. " +
"line_num: {}, entries: {}").format(line_num, entries)
# Store this line as a dictionary
line_dict = {SET_IDENTIFIER_FIELD: fields[0],
SET_DESC_FIELD: fields[1],
SET_MEMBERS_FIELD: entries}
gmt.append(line_dict)
verify_gmt_integrity(gmt)
return gmt | [
"def",
"read",
"(",
"file_path",
")",
":",
"# Read in file",
"actual_file_path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"file_path",
")",
"with",
"open",
"(",
"actual_file_path",
",",
"'r'",
")",
"as",
"f",
":",
"lines",
"=",
"f",
".",
"readline... | Read a gmt file at the path specified by file_path.
Args:
file_path (string): path to gmt file
Returns:
gmt (GMT object): list of dicts, where each dict corresponds to one
line of the GMT file | [
"Read",
"a",
"gmt",
"file",
"at",
"the",
"path",
"specified",
"by",
"file_path",
"."
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/set_io/gmt.py#L24-L73 |
18,516 | cmap/cmapPy | cmapPy/set_io/gmt.py | verify_gmt_integrity | def verify_gmt_integrity(gmt):
""" Make sure that set ids are unique.
Args:
gmt (GMT object): list of dicts
Returns:
None
"""
# Verify that set ids are unique
set_ids = [d[SET_IDENTIFIER_FIELD] for d in gmt]
assert len(set(set_ids)) == len(set_ids), (
"Set identifiers should be unique. set_ids: {}".format(set_ids)) | python | def verify_gmt_integrity(gmt):
# Verify that set ids are unique
set_ids = [d[SET_IDENTIFIER_FIELD] for d in gmt]
assert len(set(set_ids)) == len(set_ids), (
"Set identifiers should be unique. set_ids: {}".format(set_ids)) | [
"def",
"verify_gmt_integrity",
"(",
"gmt",
")",
":",
"# Verify that set ids are unique",
"set_ids",
"=",
"[",
"d",
"[",
"SET_IDENTIFIER_FIELD",
"]",
"for",
"d",
"in",
"gmt",
"]",
"assert",
"len",
"(",
"set",
"(",
"set_ids",
")",
")",
"==",
"len",
"(",
"set... | Make sure that set ids are unique.
Args:
gmt (GMT object): list of dicts
Returns:
None | [
"Make",
"sure",
"that",
"set",
"ids",
"are",
"unique",
"."
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/set_io/gmt.py#L76-L90 |
18,517 | cmap/cmapPy | cmapPy/set_io/gmt.py | write | def write(gmt, out_path):
""" Write a GMT to a text file.
Args:
gmt (GMT object): list of dicts
out_path (string): output path
Returns:
None
"""
with open(out_path, 'w') as f:
for _, each_dict in enumerate(gmt):
f.write(each_dict[SET_IDENTIFIER_FIELD] + '\t')
f.write(each_dict[SET_DESC_FIELD] + '\t')
f.write('\t'.join([str(entry) for entry in each_dict[SET_MEMBERS_FIELD]]))
f.write('\n') | python | def write(gmt, out_path):
with open(out_path, 'w') as f:
for _, each_dict in enumerate(gmt):
f.write(each_dict[SET_IDENTIFIER_FIELD] + '\t')
f.write(each_dict[SET_DESC_FIELD] + '\t')
f.write('\t'.join([str(entry) for entry in each_dict[SET_MEMBERS_FIELD]]))
f.write('\n') | [
"def",
"write",
"(",
"gmt",
",",
"out_path",
")",
":",
"with",
"open",
"(",
"out_path",
",",
"'w'",
")",
"as",
"f",
":",
"for",
"_",
",",
"each_dict",
"in",
"enumerate",
"(",
"gmt",
")",
":",
"f",
".",
"write",
"(",
"each_dict",
"[",
"SET_IDENTIFIE... | Write a GMT to a text file.
Args:
gmt (GMT object): list of dicts
out_path (string): output path
Returns:
None | [
"Write",
"a",
"GMT",
"to",
"a",
"text",
"file",
"."
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/set_io/gmt.py#L93-L109 |
18,518 | cmap/cmapPy | cmapPy/pandasGEXpress/parse_gctx.py | parse | def parse(gctx_file_path, convert_neg_666=True, rid=None, cid=None,
ridx=None, cidx=None, row_meta_only=False, col_meta_only=False, make_multiindex=False):
"""
Primary method of script. Reads in path to a gctx file and parses into GCToo object.
Input:
Mandatory:
- gctx_file_path (str): full path to gctx file you want to parse.
Optional:
- convert_neg_666 (bool): whether to convert -666 values to numpy.nan or not
(see Note below for more details on this). Default = False.
- rid (list of strings): list of row ids to specifically keep from gctx. Default=None.
- cid (list of strings): list of col ids to specifically keep from gctx. Default=None.
- ridx (list of integers): only read the rows corresponding to this
list of integer ids. Default=None.
- cidx (list of integers): only read the columns corresponding to this
list of integer ids. Default=None.
- row_meta_only (bool): Whether to load data + metadata (if False), or just row metadata (if True)
as pandas DataFrame
- col_meta_only (bool): Whether to load data + metadata (if False), or just col metadata (if True)
as pandas DataFrame
- make_multiindex (bool): whether to create a multi-index df combining
the 3 component dfs
Output:
- myGCToo (GCToo): A GCToo instance containing content of parsed gctx file. Note: if meta_only = True,
this will be a GCToo instance where the data_df is empty, i.e. data_df = pd.DataFrame(index=rids,
columns = cids)
Note: why does convert_neg_666 exist?
- In CMap--for somewhat obscure historical reasons--we use "-666" as our null value
for metadata. However (so that users can take full advantage of pandas' methods,
including those for filtering nan's etc) we provide the option of converting these
into numpy.NaN values, the pandas default.
"""
full_path = os.path.expanduser(gctx_file_path)
# Verify that the path exists
if not os.path.exists(full_path):
err_msg = "The given path to the gctx file cannot be found. full_path: {}"
logger.error(err_msg.format(full_path))
raise Exception(err_msg.format(full_path))
logger.info("Reading GCTX: {}".format(full_path))
# open file
gctx_file = h5py.File(full_path, "r")
if row_meta_only:
# read in row metadata
row_dset = gctx_file[row_meta_group_node]
row_meta = parse_metadata_df("row", row_dset, convert_neg_666)
# validate optional input ids & get indexes to subset by
(sorted_ridx, sorted_cidx) = check_and_order_id_inputs(rid, ridx, cid, cidx, row_meta, None)
gctx_file.close()
# subset if specified, then return
row_meta = row_meta.iloc[sorted_ridx]
return row_meta
elif col_meta_only:
# read in col metadata
col_dset = gctx_file[col_meta_group_node]
col_meta = parse_metadata_df("col", col_dset, convert_neg_666)
# validate optional input ids & get indexes to subset by
(sorted_ridx, sorted_cidx) = check_and_order_id_inputs(rid, ridx, cid, cidx, None, col_meta)
gctx_file.close()
# subset if specified, then return
col_meta = col_meta.iloc[sorted_cidx]
return col_meta
else:
# read in row metadata
row_dset = gctx_file[row_meta_group_node]
row_meta = parse_metadata_df("row", row_dset, convert_neg_666)
# read in col metadata
col_dset = gctx_file[col_meta_group_node]
col_meta = parse_metadata_df("col", col_dset, convert_neg_666)
# validate optional input ids & get indexes to subset by
(sorted_ridx, sorted_cidx) = check_and_order_id_inputs(rid, ridx, cid, cidx, row_meta, col_meta)
data_dset = gctx_file[data_node]
data_df = parse_data_df(data_dset, sorted_ridx, sorted_cidx, row_meta, col_meta)
# (if subsetting) subset metadata
row_meta = row_meta.iloc[sorted_ridx]
col_meta = col_meta.iloc[sorted_cidx]
# get version
my_version = gctx_file.attrs[version_node]
if type(my_version) == np.ndarray:
my_version = my_version[0]
gctx_file.close()
# make GCToo instance
my_gctoo = GCToo.GCToo(data_df=data_df, row_metadata_df=row_meta, col_metadata_df=col_meta,
src=full_path, version=my_version, make_multiindex=make_multiindex)
return my_gctoo | python | def parse(gctx_file_path, convert_neg_666=True, rid=None, cid=None,
ridx=None, cidx=None, row_meta_only=False, col_meta_only=False, make_multiindex=False):
full_path = os.path.expanduser(gctx_file_path)
# Verify that the path exists
if not os.path.exists(full_path):
err_msg = "The given path to the gctx file cannot be found. full_path: {}"
logger.error(err_msg.format(full_path))
raise Exception(err_msg.format(full_path))
logger.info("Reading GCTX: {}".format(full_path))
# open file
gctx_file = h5py.File(full_path, "r")
if row_meta_only:
# read in row metadata
row_dset = gctx_file[row_meta_group_node]
row_meta = parse_metadata_df("row", row_dset, convert_neg_666)
# validate optional input ids & get indexes to subset by
(sorted_ridx, sorted_cidx) = check_and_order_id_inputs(rid, ridx, cid, cidx, row_meta, None)
gctx_file.close()
# subset if specified, then return
row_meta = row_meta.iloc[sorted_ridx]
return row_meta
elif col_meta_only:
# read in col metadata
col_dset = gctx_file[col_meta_group_node]
col_meta = parse_metadata_df("col", col_dset, convert_neg_666)
# validate optional input ids & get indexes to subset by
(sorted_ridx, sorted_cidx) = check_and_order_id_inputs(rid, ridx, cid, cidx, None, col_meta)
gctx_file.close()
# subset if specified, then return
col_meta = col_meta.iloc[sorted_cidx]
return col_meta
else:
# read in row metadata
row_dset = gctx_file[row_meta_group_node]
row_meta = parse_metadata_df("row", row_dset, convert_neg_666)
# read in col metadata
col_dset = gctx_file[col_meta_group_node]
col_meta = parse_metadata_df("col", col_dset, convert_neg_666)
# validate optional input ids & get indexes to subset by
(sorted_ridx, sorted_cidx) = check_and_order_id_inputs(rid, ridx, cid, cidx, row_meta, col_meta)
data_dset = gctx_file[data_node]
data_df = parse_data_df(data_dset, sorted_ridx, sorted_cidx, row_meta, col_meta)
# (if subsetting) subset metadata
row_meta = row_meta.iloc[sorted_ridx]
col_meta = col_meta.iloc[sorted_cidx]
# get version
my_version = gctx_file.attrs[version_node]
if type(my_version) == np.ndarray:
my_version = my_version[0]
gctx_file.close()
# make GCToo instance
my_gctoo = GCToo.GCToo(data_df=data_df, row_metadata_df=row_meta, col_metadata_df=col_meta,
src=full_path, version=my_version, make_multiindex=make_multiindex)
return my_gctoo | [
"def",
"parse",
"(",
"gctx_file_path",
",",
"convert_neg_666",
"=",
"True",
",",
"rid",
"=",
"None",
",",
"cid",
"=",
"None",
",",
"ridx",
"=",
"None",
",",
"cidx",
"=",
"None",
",",
"row_meta_only",
"=",
"False",
",",
"col_meta_only",
"=",
"False",
",... | Primary method of script. Reads in path to a gctx file and parses into GCToo object.
Input:
Mandatory:
- gctx_file_path (str): full path to gctx file you want to parse.
Optional:
- convert_neg_666 (bool): whether to convert -666 values to numpy.nan or not
(see Note below for more details on this). Default = False.
- rid (list of strings): list of row ids to specifically keep from gctx. Default=None.
- cid (list of strings): list of col ids to specifically keep from gctx. Default=None.
- ridx (list of integers): only read the rows corresponding to this
list of integer ids. Default=None.
- cidx (list of integers): only read the columns corresponding to this
list of integer ids. Default=None.
- row_meta_only (bool): Whether to load data + metadata (if False), or just row metadata (if True)
as pandas DataFrame
- col_meta_only (bool): Whether to load data + metadata (if False), or just col metadata (if True)
as pandas DataFrame
- make_multiindex (bool): whether to create a multi-index df combining
the 3 component dfs
Output:
- myGCToo (GCToo): A GCToo instance containing content of parsed gctx file. Note: if meta_only = True,
this will be a GCToo instance where the data_df is empty, i.e. data_df = pd.DataFrame(index=rids,
columns = cids)
Note: why does convert_neg_666 exist?
- In CMap--for somewhat obscure historical reasons--we use "-666" as our null value
for metadata. However (so that users can take full advantage of pandas' methods,
including those for filtering nan's etc) we provide the option of converting these
into numpy.NaN values, the pandas default. | [
"Primary",
"method",
"of",
"script",
".",
"Reads",
"in",
"path",
"to",
"a",
"gctx",
"file",
"and",
"parses",
"into",
"GCToo",
"object",
"."
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/parse_gctx.py#L23-L126 |
18,519 | cmap/cmapPy | cmapPy/pandasGEXpress/parse_gctx.py | check_id_idx_exclusivity | def check_id_idx_exclusivity(id, idx):
"""
Makes sure user didn't provide both ids and idx values to subset by.
Input:
- id (list or None): if not None, a list of string id names
- idx (list or None): if not None, a list of integer id indexes
Output:
- a tuple: first element is subset type, second is subset content
"""
if (id is not None and idx is not None):
msg = ("'id' and 'idx' fields can't both not be None," +
" please specify subset in only one of these fields")
logger.error(msg)
raise Exception("parse_gctx.check_id_idx_exclusivity: " + msg)
elif id is not None:
return ("id", id)
elif idx is not None:
return ("idx", idx)
else:
return (None, []) | python | def check_id_idx_exclusivity(id, idx):
if (id is not None and idx is not None):
msg = ("'id' and 'idx' fields can't both not be None," +
" please specify subset in only one of these fields")
logger.error(msg)
raise Exception("parse_gctx.check_id_idx_exclusivity: " + msg)
elif id is not None:
return ("id", id)
elif idx is not None:
return ("idx", idx)
else:
return (None, []) | [
"def",
"check_id_idx_exclusivity",
"(",
"id",
",",
"idx",
")",
":",
"if",
"(",
"id",
"is",
"not",
"None",
"and",
"idx",
"is",
"not",
"None",
")",
":",
"msg",
"=",
"(",
"\"'id' and 'idx' fields can't both not be None,\"",
"+",
"\" please specify subset in only one ... | Makes sure user didn't provide both ids and idx values to subset by.
Input:
- id (list or None): if not None, a list of string id names
- idx (list or None): if not None, a list of integer id indexes
Output:
- a tuple: first element is subset type, second is subset content | [
"Makes",
"sure",
"user",
"didn",
"t",
"provide",
"both",
"ids",
"and",
"idx",
"values",
"to",
"subset",
"by",
"."
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/parse_gctx.py#L151-L172 |
18,520 | cmap/cmapPy | cmapPy/pandasGEXpress/parse_gctx.py | parse_data_df | def parse_data_df(data_dset, ridx, cidx, row_meta, col_meta):
"""
Parses in data_df from hdf5, subsetting if specified.
Input:
-data_dset (h5py dset): HDF5 dataset from which to read data_df
-ridx (list): list of indexes to subset from data_df
(may be all of them if no subsetting)
-cidx (list): list of indexes to subset from data_df
(may be all of them if no subsetting)
-row_meta (pandas DataFrame): the parsed in row metadata
-col_meta (pandas DataFrame): the parsed in col metadata
"""
if len(ridx) == len(row_meta.index) and len(cidx) == len(col_meta.index): # no subset
data_array = np.empty(data_dset.shape, dtype=np.float32)
data_dset.read_direct(data_array)
data_array = data_array.transpose()
elif len(ridx) <= len(cidx):
first_subset = data_dset[:, ridx].astype(np.float32)
data_array = first_subset[cidx, :].transpose()
elif len(cidx) < len(ridx):
first_subset = data_dset[cidx, :].astype(np.float32)
data_array = first_subset[:, ridx].transpose()
# make DataFrame instance
data_df = pd.DataFrame(data_array, index=row_meta.index[ridx], columns=col_meta.index[cidx])
return data_df | python | def parse_data_df(data_dset, ridx, cidx, row_meta, col_meta):
if len(ridx) == len(row_meta.index) and len(cidx) == len(col_meta.index): # no subset
data_array = np.empty(data_dset.shape, dtype=np.float32)
data_dset.read_direct(data_array)
data_array = data_array.transpose()
elif len(ridx) <= len(cidx):
first_subset = data_dset[:, ridx].astype(np.float32)
data_array = first_subset[cidx, :].transpose()
elif len(cidx) < len(ridx):
first_subset = data_dset[cidx, :].astype(np.float32)
data_array = first_subset[:, ridx].transpose()
# make DataFrame instance
data_df = pd.DataFrame(data_array, index=row_meta.index[ridx], columns=col_meta.index[cidx])
return data_df | [
"def",
"parse_data_df",
"(",
"data_dset",
",",
"ridx",
",",
"cidx",
",",
"row_meta",
",",
"col_meta",
")",
":",
"if",
"len",
"(",
"ridx",
")",
"==",
"len",
"(",
"row_meta",
".",
"index",
")",
"and",
"len",
"(",
"cidx",
")",
"==",
"len",
"(",
"col_m... | Parses in data_df from hdf5, subsetting if specified.
Input:
-data_dset (h5py dset): HDF5 dataset from which to read data_df
-ridx (list): list of indexes to subset from data_df
(may be all of them if no subsetting)
-cidx (list): list of indexes to subset from data_df
(may be all of them if no subsetting)
-row_meta (pandas DataFrame): the parsed in row metadata
-col_meta (pandas DataFrame): the parsed in col metadata | [
"Parses",
"in",
"data_df",
"from",
"hdf5",
"subsetting",
"if",
"specified",
"."
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/parse_gctx.py#L320-L345 |
18,521 | cmap/cmapPy | cmapPy/pandasGEXpress/parse_gctx.py | get_column_metadata | def get_column_metadata(gctx_file_path, convert_neg_666=True):
"""
Opens .gctx file and returns only column metadata
Input:
Mandatory:
- gctx_file_path (str): full path to gctx file you want to parse.
Optional:
- convert_neg_666 (bool): whether to convert -666 values to num
Output:
- col_meta (pandas DataFrame): a DataFrame of all column metadata values.
"""
full_path = os.path.expanduser(gctx_file_path)
# open file
gctx_file = h5py.File(full_path, "r")
col_dset = gctx_file[col_meta_group_node]
col_meta = parse_metadata_df("col", col_dset, convert_neg_666)
gctx_file.close()
return col_meta | python | def get_column_metadata(gctx_file_path, convert_neg_666=True):
full_path = os.path.expanduser(gctx_file_path)
# open file
gctx_file = h5py.File(full_path, "r")
col_dset = gctx_file[col_meta_group_node]
col_meta = parse_metadata_df("col", col_dset, convert_neg_666)
gctx_file.close()
return col_meta | [
"def",
"get_column_metadata",
"(",
"gctx_file_path",
",",
"convert_neg_666",
"=",
"True",
")",
":",
"full_path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"gctx_file_path",
")",
"# open file",
"gctx_file",
"=",
"h5py",
".",
"File",
"(",
"full_path",
",",... | Opens .gctx file and returns only column metadata
Input:
Mandatory:
- gctx_file_path (str): full path to gctx file you want to parse.
Optional:
- convert_neg_666 (bool): whether to convert -666 values to num
Output:
- col_meta (pandas DataFrame): a DataFrame of all column metadata values. | [
"Opens",
".",
"gctx",
"file",
"and",
"returns",
"only",
"column",
"metadata"
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/parse_gctx.py#L348-L368 |
18,522 | cmap/cmapPy | cmapPy/pandasGEXpress/parse_gctx.py | get_row_metadata | def get_row_metadata(gctx_file_path, convert_neg_666=True):
"""
Opens .gctx file and returns only row metadata
Input:
Mandatory:
- gctx_file_path (str): full path to gctx file you want to parse.
Optional:
- convert_neg_666 (bool): whether to convert -666 values to num
Output:
- row_meta (pandas DataFrame): a DataFrame of all row metadata values.
"""
full_path = os.path.expanduser(gctx_file_path)
# open file
gctx_file = h5py.File(full_path, "r")
row_dset = gctx_file[row_meta_group_node]
row_meta = parse_metadata_df("row", row_dset, convert_neg_666)
gctx_file.close()
return row_meta | python | def get_row_metadata(gctx_file_path, convert_neg_666=True):
full_path = os.path.expanduser(gctx_file_path)
# open file
gctx_file = h5py.File(full_path, "r")
row_dset = gctx_file[row_meta_group_node]
row_meta = parse_metadata_df("row", row_dset, convert_neg_666)
gctx_file.close()
return row_meta | [
"def",
"get_row_metadata",
"(",
"gctx_file_path",
",",
"convert_neg_666",
"=",
"True",
")",
":",
"full_path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"gctx_file_path",
")",
"# open file",
"gctx_file",
"=",
"h5py",
".",
"File",
"(",
"full_path",
",",
... | Opens .gctx file and returns only row metadata
Input:
Mandatory:
- gctx_file_path (str): full path to gctx file you want to parse.
Optional:
- convert_neg_666 (bool): whether to convert -666 values to num
Output:
- row_meta (pandas DataFrame): a DataFrame of all row metadata values. | [
"Opens",
".",
"gctx",
"file",
"and",
"returns",
"only",
"row",
"metadata"
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/parse_gctx.py#L371-L391 |
18,523 | cmap/cmapPy | cmapPy/pandasGEXpress/GCToo.py | multi_index_df_to_component_dfs | def multi_index_df_to_component_dfs(multi_index_df, rid="rid", cid="cid"):
""" Convert a multi-index df into 3 component dfs. """
# Id level of the multiindex will become the index
rids = list(multi_index_df.index.get_level_values(rid))
cids = list(multi_index_df.columns.get_level_values(cid))
# It's possible that the index and/or columns of multi_index_df are not
# actually multi-index; need to check for this and there are more than one level in index(python3)
if isinstance(multi_index_df.index, pd.MultiIndex):
# check if there are more than one levels in index (python3)
if len(multi_index_df.index.names) > 1:
# If so, drop rid because it won't go into the body of the metadata
mi_df_index = multi_index_df.index.droplevel(rid)
# Names of the multiindex levels become the headers
rhds = list(mi_df_index.names)
# Assemble metadata values
row_metadata = np.array([mi_df_index.get_level_values(level).values for level in list(rhds)]).T
# if there is one level in index (python3), then rhds and row metadata should be empty
else:
rhds = []
row_metadata = []
# If the index is not multi-index, then rhds and row metadata should be empty
else:
rhds = []
row_metadata = []
# Check if columns of multi_index_df are in fact multi-index
if isinstance(multi_index_df.columns, pd.MultiIndex):
# Check if there are more than one levels in columns(python3)
if len(multi_index_df.columns.names) > 1:
# If so, drop cid because it won't go into the body of the metadata
mi_df_columns = multi_index_df.columns.droplevel(cid)
# Names of the multiindex levels become the headers
chds = list(mi_df_columns.names)
# Assemble metadata values
col_metadata = np.array([mi_df_columns.get_level_values(level).values for level in list(chds)]).T
# If there is one level in columns (python3), then rhds and row metadata should be empty
else:
chds = []
col_metadata = []
# If the columns are not multi-index, then rhds and row metadata should be empty
else:
chds = []
col_metadata = []
# Create component dfs
row_metadata_df = pd.DataFrame.from_records(row_metadata, index=pd.Index(rids, name="rid"), columns=pd.Index(rhds, name="rhd"))
col_metadata_df = pd.DataFrame.from_records(col_metadata, index=pd.Index(cids, name="cid"), columns=pd.Index(chds, name="chd"))
data_df = pd.DataFrame(multi_index_df.values, index=pd.Index(rids, name="rid"), columns=pd.Index(cids, name="cid"))
return data_df, row_metadata_df, col_metadata_df | python | def multi_index_df_to_component_dfs(multi_index_df, rid="rid", cid="cid"):
# Id level of the multiindex will become the index
rids = list(multi_index_df.index.get_level_values(rid))
cids = list(multi_index_df.columns.get_level_values(cid))
# It's possible that the index and/or columns of multi_index_df are not
# actually multi-index; need to check for this and there are more than one level in index(python3)
if isinstance(multi_index_df.index, pd.MultiIndex):
# check if there are more than one levels in index (python3)
if len(multi_index_df.index.names) > 1:
# If so, drop rid because it won't go into the body of the metadata
mi_df_index = multi_index_df.index.droplevel(rid)
# Names of the multiindex levels become the headers
rhds = list(mi_df_index.names)
# Assemble metadata values
row_metadata = np.array([mi_df_index.get_level_values(level).values for level in list(rhds)]).T
# if there is one level in index (python3), then rhds and row metadata should be empty
else:
rhds = []
row_metadata = []
# If the index is not multi-index, then rhds and row metadata should be empty
else:
rhds = []
row_metadata = []
# Check if columns of multi_index_df are in fact multi-index
if isinstance(multi_index_df.columns, pd.MultiIndex):
# Check if there are more than one levels in columns(python3)
if len(multi_index_df.columns.names) > 1:
# If so, drop cid because it won't go into the body of the metadata
mi_df_columns = multi_index_df.columns.droplevel(cid)
# Names of the multiindex levels become the headers
chds = list(mi_df_columns.names)
# Assemble metadata values
col_metadata = np.array([mi_df_columns.get_level_values(level).values for level in list(chds)]).T
# If there is one level in columns (python3), then rhds and row metadata should be empty
else:
chds = []
col_metadata = []
# If the columns are not multi-index, then rhds and row metadata should be empty
else:
chds = []
col_metadata = []
# Create component dfs
row_metadata_df = pd.DataFrame.from_records(row_metadata, index=pd.Index(rids, name="rid"), columns=pd.Index(rhds, name="rhd"))
col_metadata_df = pd.DataFrame.from_records(col_metadata, index=pd.Index(cids, name="cid"), columns=pd.Index(chds, name="chd"))
data_df = pd.DataFrame(multi_index_df.values, index=pd.Index(rids, name="rid"), columns=pd.Index(cids, name="cid"))
return data_df, row_metadata_df, col_metadata_df | [
"def",
"multi_index_df_to_component_dfs",
"(",
"multi_index_df",
",",
"rid",
"=",
"\"rid\"",
",",
"cid",
"=",
"\"cid\"",
")",
":",
"# Id level of the multiindex will become the index",
"rids",
"=",
"list",
"(",
"multi_index_df",
".",
"index",
".",
"get_level_values",
... | Convert a multi-index df into 3 component dfs. | [
"Convert",
"a",
"multi",
"-",
"index",
"df",
"into",
"3",
"component",
"dfs",
"."
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/GCToo.py#L222-L284 |
18,524 | cmap/cmapPy | cmapPy/pandasGEXpress/GCToo.py | GCToo.check_df | def check_df(self, df):
"""
Verifies that df is a pandas DataFrame instance and
that its index and column values are unique.
"""
if isinstance(df, pd.DataFrame):
if not df.index.is_unique:
repeats = df.index[df.index.duplicated()].values
msg = "Index values must be unique but aren't. The following entries appear more than once: {}".format(repeats)
self.logger.error(msg)
raise Exception("GCToo GCToo.check_df " + msg)
if not df.columns.is_unique:
repeats = df.columns[df.columns.duplicated()].values
msg = "Columns values must be unique but aren't. The following entries appear more than once: {}".format(repeats)
raise Exception("GCToo GCToo.check_df " + msg)
else:
return True
else:
msg = "expected Pandas DataFrame, got something else: {} of type: {}".format(df, type(df))
self.logger.error(msg)
raise Exception("GCToo GCToo.check_df " + msg) | python | def check_df(self, df):
if isinstance(df, pd.DataFrame):
if not df.index.is_unique:
repeats = df.index[df.index.duplicated()].values
msg = "Index values must be unique but aren't. The following entries appear more than once: {}".format(repeats)
self.logger.error(msg)
raise Exception("GCToo GCToo.check_df " + msg)
if not df.columns.is_unique:
repeats = df.columns[df.columns.duplicated()].values
msg = "Columns values must be unique but aren't. The following entries appear more than once: {}".format(repeats)
raise Exception("GCToo GCToo.check_df " + msg)
else:
return True
else:
msg = "expected Pandas DataFrame, got something else: {} of type: {}".format(df, type(df))
self.logger.error(msg)
raise Exception("GCToo GCToo.check_df " + msg) | [
"def",
"check_df",
"(",
"self",
",",
"df",
")",
":",
"if",
"isinstance",
"(",
"df",
",",
"pd",
".",
"DataFrame",
")",
":",
"if",
"not",
"df",
".",
"index",
".",
"is_unique",
":",
"repeats",
"=",
"df",
".",
"index",
"[",
"df",
".",
"index",
".",
... | Verifies that df is a pandas DataFrame instance and
that its index and column values are unique. | [
"Verifies",
"that",
"df",
"is",
"a",
"pandas",
"DataFrame",
"instance",
"and",
"that",
"its",
"index",
"and",
"column",
"values",
"are",
"unique",
"."
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/GCToo.py#L125-L145 |
18,525 | cmap/cmapPy | cmapPy/clue_api_client/gene_queries.py | are_genes_in_api | def are_genes_in_api(my_clue_api_client, gene_symbols):
"""determine if genes are present in the API
Args:
my_clue_api_client:
gene_symbols: collection of gene symbols to query the API with
Returns: set of the found gene symbols
"""
if len(gene_symbols) > 0:
query_gene_symbols = gene_symbols if type(gene_symbols) is list else list(gene_symbols)
query_result = my_clue_api_client.run_filter_query(resource_name,
{"where":{"gene_symbol":{"inq":query_gene_symbols}}, "fields":{"gene_symbol":True}})
logger.debug("query_result: {}".format(query_result))
r = set([x["gene_symbol"] for x in query_result])
return r
else:
logger.warning("provided gene_symbols was empty, cannot run query")
return set() | python | def are_genes_in_api(my_clue_api_client, gene_symbols):
if len(gene_symbols) > 0:
query_gene_symbols = gene_symbols if type(gene_symbols) is list else list(gene_symbols)
query_result = my_clue_api_client.run_filter_query(resource_name,
{"where":{"gene_symbol":{"inq":query_gene_symbols}}, "fields":{"gene_symbol":True}})
logger.debug("query_result: {}".format(query_result))
r = set([x["gene_symbol"] for x in query_result])
return r
else:
logger.warning("provided gene_symbols was empty, cannot run query")
return set() | [
"def",
"are_genes_in_api",
"(",
"my_clue_api_client",
",",
"gene_symbols",
")",
":",
"if",
"len",
"(",
"gene_symbols",
")",
">",
"0",
":",
"query_gene_symbols",
"=",
"gene_symbols",
"if",
"type",
"(",
"gene_symbols",
")",
"is",
"list",
"else",
"list",
"(",
"... | determine if genes are present in the API
Args:
my_clue_api_client:
gene_symbols: collection of gene symbols to query the API with
Returns: set of the found gene symbols | [
"determine",
"if",
"genes",
"are",
"present",
"in",
"the",
"API"
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/clue_api_client/gene_queries.py#L13-L34 |
18,526 | cmap/cmapPy | cmapPy/pandasGEXpress/write_gct.py | write | def write(gctoo, out_fname, data_null="NaN", metadata_null="-666", filler_null="-666", data_float_format="%.4f"):
"""Write a gctoo object to a gct file.
Args:
gctoo (gctoo object)
out_fname (string): filename for output gct file
data_null (string): how to represent missing values in the data (default = "NaN")
metadata_null (string): how to represent missing values in the metadata (default = "-666")
filler_null (string): what value to fill the top-left filler block with (default = "-666")
data_float_format (string): how many decimal points to keep in representing data
(default = 4 digits; None will keep all digits)
Returns:
None
"""
# Create handle for output file
if not out_fname.endswith(".gct"):
out_fname += ".gct"
f = open(out_fname, "w")
# Write first two lines
dims = [str(gctoo.data_df.shape[0]), str(gctoo.data_df.shape[1]),
str(gctoo.row_metadata_df.shape[1]), str(gctoo.col_metadata_df.shape[1])]
write_version_and_dims(VERSION, dims, f)
# Write top half of the gct
write_top_half(f, gctoo.row_metadata_df, gctoo.col_metadata_df,
metadata_null, filler_null)
# Write bottom half of the gct
write_bottom_half(f, gctoo.row_metadata_df, gctoo.data_df,
data_null, data_float_format, metadata_null)
f.close()
logger.info("GCT has been written to {}".format(out_fname)) | python | def write(gctoo, out_fname, data_null="NaN", metadata_null="-666", filler_null="-666", data_float_format="%.4f"):
# Create handle for output file
if not out_fname.endswith(".gct"):
out_fname += ".gct"
f = open(out_fname, "w")
# Write first two lines
dims = [str(gctoo.data_df.shape[0]), str(gctoo.data_df.shape[1]),
str(gctoo.row_metadata_df.shape[1]), str(gctoo.col_metadata_df.shape[1])]
write_version_and_dims(VERSION, dims, f)
# Write top half of the gct
write_top_half(f, gctoo.row_metadata_df, gctoo.col_metadata_df,
metadata_null, filler_null)
# Write bottom half of the gct
write_bottom_half(f, gctoo.row_metadata_df, gctoo.data_df,
data_null, data_float_format, metadata_null)
f.close()
logger.info("GCT has been written to {}".format(out_fname)) | [
"def",
"write",
"(",
"gctoo",
",",
"out_fname",
",",
"data_null",
"=",
"\"NaN\"",
",",
"metadata_null",
"=",
"\"-666\"",
",",
"filler_null",
"=",
"\"-666\"",
",",
"data_float_format",
"=",
"\"%.4f\"",
")",
":",
"# Create handle for output file",
"if",
"not",
"ou... | Write a gctoo object to a gct file.
Args:
gctoo (gctoo object)
out_fname (string): filename for output gct file
data_null (string): how to represent missing values in the data (default = "NaN")
metadata_null (string): how to represent missing values in the metadata (default = "-666")
filler_null (string): what value to fill the top-left filler block with (default = "-666")
data_float_format (string): how many decimal points to keep in representing data
(default = 4 digits; None will keep all digits)
Returns:
None | [
"Write",
"a",
"gctoo",
"object",
"to",
"a",
"gct",
"file",
"."
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/write_gct.py#L16-L51 |
18,527 | cmap/cmapPy | cmapPy/pandasGEXpress/write_gct.py | write_version_and_dims | def write_version_and_dims(version, dims, f):
"""Write first two lines of gct file.
Args:
version (string): 1.3 by default
dims (list of strings): length = 4
f (file handle): handle of output file
Returns:
nothing
"""
f.write(("#" + version + "\n"))
f.write((dims[0] + "\t" + dims[1] + "\t" + dims[2] + "\t" + dims[3] + "\n")) | python | def write_version_and_dims(version, dims, f):
f.write(("#" + version + "\n"))
f.write((dims[0] + "\t" + dims[1] + "\t" + dims[2] + "\t" + dims[3] + "\n")) | [
"def",
"write_version_and_dims",
"(",
"version",
",",
"dims",
",",
"f",
")",
":",
"f",
".",
"write",
"(",
"(",
"\"#\"",
"+",
"version",
"+",
"\"\\n\"",
")",
")",
"f",
".",
"write",
"(",
"(",
"dims",
"[",
"0",
"]",
"+",
"\"\\t\"",
"+",
"dims",
"["... | Write first two lines of gct file.
Args:
version (string): 1.3 by default
dims (list of strings): length = 4
f (file handle): handle of output file
Returns:
nothing | [
"Write",
"first",
"two",
"lines",
"of",
"gct",
"file",
"."
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/write_gct.py#L54-L65 |
18,528 | cmap/cmapPy | cmapPy/pandasGEXpress/write_gct.py | append_dims_and_file_extension | def append_dims_and_file_extension(fname, data_df):
"""Append dimensions and file extension to output filename.
N.B. Dimensions are cols x rows.
Args:
fname (string): output filename
data_df (pandas df)
Returns:
out_fname (string): output filename with matrix dims and .gct appended
"""
# If there's no .gct at the end of output file name, add the dims and .gct
if not fname.endswith(".gct"):
out_fname = '{0}_n{1}x{2}.gct'.format(fname, data_df.shape[1], data_df.shape[0])
return out_fname
# Otherwise, only add the dims
else:
basename = os.path.splitext(fname)[0]
out_fname = '{0}_n{1}x{2}.gct'.format(basename, data_df.shape[1], data_df.shape[0])
return out_fname | python | def append_dims_and_file_extension(fname, data_df):
# If there's no .gct at the end of output file name, add the dims and .gct
if not fname.endswith(".gct"):
out_fname = '{0}_n{1}x{2}.gct'.format(fname, data_df.shape[1], data_df.shape[0])
return out_fname
# Otherwise, only add the dims
else:
basename = os.path.splitext(fname)[0]
out_fname = '{0}_n{1}x{2}.gct'.format(basename, data_df.shape[1], data_df.shape[0])
return out_fname | [
"def",
"append_dims_and_file_extension",
"(",
"fname",
",",
"data_df",
")",
":",
"# If there's no .gct at the end of output file name, add the dims and .gct",
"if",
"not",
"fname",
".",
"endswith",
"(",
"\".gct\"",
")",
":",
"out_fname",
"=",
"'{0}_n{1}x{2}.gct'",
".",
"f... | Append dimensions and file extension to output filename.
N.B. Dimensions are cols x rows.
Args:
fname (string): output filename
data_df (pandas df)
Returns:
out_fname (string): output filename with matrix dims and .gct appended | [
"Append",
"dimensions",
"and",
"file",
"extension",
"to",
"output",
"filename",
".",
"N",
".",
"B",
".",
"Dimensions",
"are",
"cols",
"x",
"rows",
"."
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/write_gct.py#L142-L161 |
18,529 | cmap/cmapPy | cmapPy/math/robust_zscore.py | robust_zscore | def robust_zscore(mat, ctrl_mat=None, min_mad=0.1):
''' Robustly z-score a pandas df along the rows.
Args:
mat (pandas df): Matrix of data that z-scoring will be applied to
ctrl_mat (pandas df): Optional matrix from which to compute medians and MADs
(e.g. vehicle control)
min_mad (float): Minimum MAD to threshold to; tiny MAD values will cause
z-scores to blow up
Returns:
zscore_df (pandas_df): z-scored data
'''
# If optional df exists, calc medians and mads from it
if ctrl_mat is not None:
medians = ctrl_mat.median(axis=1)
median_devs = abs(ctrl_mat.subtract(medians, axis=0))
# Else just use plate medians
else:
medians = mat.median(axis=1)
median_devs = abs(mat.subtract(medians, axis=0))
sub = mat.subtract(medians, axis='index')
mads = median_devs.median(axis=1)
# Threshold mads
mads = mads.clip(lower=min_mad)
# Must multiply values by 1.4826 to make MAD comparable to SD
# (https://en.wikipedia.org/wiki/Median_absolute_deviation)
zscore_df = sub.divide(mads * 1.4826, axis='index')
return zscore_df.round(rounding_precision) | python | def robust_zscore(mat, ctrl_mat=None, min_mad=0.1):
''' Robustly z-score a pandas df along the rows.
Args:
mat (pandas df): Matrix of data that z-scoring will be applied to
ctrl_mat (pandas df): Optional matrix from which to compute medians and MADs
(e.g. vehicle control)
min_mad (float): Minimum MAD to threshold to; tiny MAD values will cause
z-scores to blow up
Returns:
zscore_df (pandas_df): z-scored data
'''
# If optional df exists, calc medians and mads from it
if ctrl_mat is not None:
medians = ctrl_mat.median(axis=1)
median_devs = abs(ctrl_mat.subtract(medians, axis=0))
# Else just use plate medians
else:
medians = mat.median(axis=1)
median_devs = abs(mat.subtract(medians, axis=0))
sub = mat.subtract(medians, axis='index')
mads = median_devs.median(axis=1)
# Threshold mads
mads = mads.clip(lower=min_mad)
# Must multiply values by 1.4826 to make MAD comparable to SD
# (https://en.wikipedia.org/wiki/Median_absolute_deviation)
zscore_df = sub.divide(mads * 1.4826, axis='index')
return zscore_df.round(rounding_precision) | [
"def",
"robust_zscore",
"(",
"mat",
",",
"ctrl_mat",
"=",
"None",
",",
"min_mad",
"=",
"0.1",
")",
":",
"# If optional df exists, calc medians and mads from it",
"if",
"ctrl_mat",
"is",
"not",
"None",
":",
"medians",
"=",
"ctrl_mat",
".",
"median",
"(",
"axis",
... | Robustly z-score a pandas df along the rows.
Args:
mat (pandas df): Matrix of data that z-scoring will be applied to
ctrl_mat (pandas df): Optional matrix from which to compute medians and MADs
(e.g. vehicle control)
min_mad (float): Minimum MAD to threshold to; tiny MAD values will cause
z-scores to blow up
Returns:
zscore_df (pandas_df): z-scored data | [
"Robustly",
"z",
"-",
"score",
"a",
"pandas",
"df",
"along",
"the",
"rows",
"."
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/math/robust_zscore.py#L24-L58 |
18,530 | cmap/cmapPy | cmapPy/pandasGEXpress/parse.py | parse | def parse(file_path, convert_neg_666=True, rid=None, cid=None, ridx=None, cidx=None,
row_meta_only=False, col_meta_only=False, make_multiindex=False):
"""
Identifies whether file_path corresponds to a .gct or .gctx file and calls the
correct corresponding parse method.
Input:
Mandatory:
- gct(x)_file_path (str): full path to gct(x) file you want to parse.
Optional:
- convert_neg_666 (bool): whether to convert -666 values to numpy.nan or not
(see Note below for more details on this). Default = False.
- rid (list of strings): list of row ids to specifically keep from gctx. Default=None.
- cid (list of strings): list of col ids to specifically keep from gctx. Default=None.
- ridx (list of integers): only read the rows corresponding to this
list of integer ids. Default=None.
- cidx (list of integers): only read the columns corresponding to this
list of integer ids. Default=None.
- row_meta_only (bool): Whether to load data + metadata (if False), or just row metadata (if True)
as pandas DataFrame
- col_meta_only (bool): Whether to load data + metadata (if False), or just col metadata (if True)
as pandas DataFrame
- make_multiindex (bool): whether to create a multi-index df combining
the 3 component dfs
Output:
- out (GCToo object or pandas df): if row_meta_only or col_meta_only, then
out is a metadata df; otherwise, it's a GCToo instance containing
content of parsed gct(x) file
Note: why does convert_neg_666 exist?
- In CMap--for somewhat obscure historical reasons--we use "-666" as our null value
for metadata. However (so that users can take full advantage of pandas' methods,
including those for filtering nan's etc) we provide the option of converting these
into numpy.NaN values, the pandas default.
"""
if file_path.endswith(".gct"):
out = parse_gct.parse(file_path, convert_neg_666=convert_neg_666,
rid=rid, cid=cid, ridx=ridx, cidx=cidx,
row_meta_only=row_meta_only, col_meta_only=col_meta_only,
make_multiindex=make_multiindex)
elif file_path.endswith(".gctx"):
out = parse_gctx.parse(file_path, convert_neg_666=convert_neg_666,
rid=rid, cid=cid, ridx=ridx, cidx=cidx,
row_meta_only=row_meta_only, col_meta_only=col_meta_only,
make_multiindex=make_multiindex)
else:
err_msg = "File to parse must be .gct or .gctx!"
logger.error(err_msg)
raise Exception(err_msg)
return out | python | def parse(file_path, convert_neg_666=True, rid=None, cid=None, ridx=None, cidx=None,
row_meta_only=False, col_meta_only=False, make_multiindex=False):
if file_path.endswith(".gct"):
out = parse_gct.parse(file_path, convert_neg_666=convert_neg_666,
rid=rid, cid=cid, ridx=ridx, cidx=cidx,
row_meta_only=row_meta_only, col_meta_only=col_meta_only,
make_multiindex=make_multiindex)
elif file_path.endswith(".gctx"):
out = parse_gctx.parse(file_path, convert_neg_666=convert_neg_666,
rid=rid, cid=cid, ridx=ridx, cidx=cidx,
row_meta_only=row_meta_only, col_meta_only=col_meta_only,
make_multiindex=make_multiindex)
else:
err_msg = "File to parse must be .gct or .gctx!"
logger.error(err_msg)
raise Exception(err_msg)
return out | [
"def",
"parse",
"(",
"file_path",
",",
"convert_neg_666",
"=",
"True",
",",
"rid",
"=",
"None",
",",
"cid",
"=",
"None",
",",
"ridx",
"=",
"None",
",",
"cidx",
"=",
"None",
",",
"row_meta_only",
"=",
"False",
",",
"col_meta_only",
"=",
"False",
",",
... | Identifies whether file_path corresponds to a .gct or .gctx file and calls the
correct corresponding parse method.
Input:
Mandatory:
- gct(x)_file_path (str): full path to gct(x) file you want to parse.
Optional:
- convert_neg_666 (bool): whether to convert -666 values to numpy.nan or not
(see Note below for more details on this). Default = False.
- rid (list of strings): list of row ids to specifically keep from gctx. Default=None.
- cid (list of strings): list of col ids to specifically keep from gctx. Default=None.
- ridx (list of integers): only read the rows corresponding to this
list of integer ids. Default=None.
- cidx (list of integers): only read the columns corresponding to this
list of integer ids. Default=None.
- row_meta_only (bool): Whether to load data + metadata (if False), or just row metadata (if True)
as pandas DataFrame
- col_meta_only (bool): Whether to load data + metadata (if False), or just col metadata (if True)
as pandas DataFrame
- make_multiindex (bool): whether to create a multi-index df combining
the 3 component dfs
Output:
- out (GCToo object or pandas df): if row_meta_only or col_meta_only, then
out is a metadata df; otherwise, it's a GCToo instance containing
content of parsed gct(x) file
Note: why does convert_neg_666 exist?
- In CMap--for somewhat obscure historical reasons--we use "-666" as our null value
for metadata. However (so that users can take full advantage of pandas' methods,
including those for filtering nan's etc) we provide the option of converting these
into numpy.NaN values, the pandas default. | [
"Identifies",
"whether",
"file_path",
"corresponds",
"to",
"a",
".",
"gct",
"or",
".",
"gctx",
"file",
"and",
"calls",
"the",
"correct",
"corresponding",
"parse",
"method",
"."
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/parse.py#L21-L75 |
18,531 | cmap/cmapPy | cmapPy/math/agg_wt_avg.py | get_upper_triangle | def get_upper_triangle(correlation_matrix):
''' Extract upper triangle from a square matrix. Negative values are
set to 0.
Args:
correlation_matrix (pandas df): Correlations between all replicates
Returns:
upper_tri_df (pandas df): Upper triangle extracted from
correlation_matrix; rid is the row index, cid is the column index,
corr is the extracted correlation value
'''
upper_triangle = correlation_matrix.where(np.triu(np.ones(correlation_matrix.shape), k=1).astype(np.bool))
# convert matrix into long form description
upper_tri_df = upper_triangle.stack().reset_index(level=1)
upper_tri_df.columns = ['rid', 'corr']
# Index at this point is cid, it now becomes a column
upper_tri_df.reset_index(level=0, inplace=True)
# Get rid of negative values
upper_tri_df['corr'] = upper_tri_df['corr'].clip(lower=0)
return upper_tri_df.round(rounding_precision) | python | def get_upper_triangle(correlation_matrix):
''' Extract upper triangle from a square matrix. Negative values are
set to 0.
Args:
correlation_matrix (pandas df): Correlations between all replicates
Returns:
upper_tri_df (pandas df): Upper triangle extracted from
correlation_matrix; rid is the row index, cid is the column index,
corr is the extracted correlation value
'''
upper_triangle = correlation_matrix.where(np.triu(np.ones(correlation_matrix.shape), k=1).astype(np.bool))
# convert matrix into long form description
upper_tri_df = upper_triangle.stack().reset_index(level=1)
upper_tri_df.columns = ['rid', 'corr']
# Index at this point is cid, it now becomes a column
upper_tri_df.reset_index(level=0, inplace=True)
# Get rid of negative values
upper_tri_df['corr'] = upper_tri_df['corr'].clip(lower=0)
return upper_tri_df.round(rounding_precision) | [
"def",
"get_upper_triangle",
"(",
"correlation_matrix",
")",
":",
"upper_triangle",
"=",
"correlation_matrix",
".",
"where",
"(",
"np",
".",
"triu",
"(",
"np",
".",
"ones",
"(",
"correlation_matrix",
".",
"shape",
")",
",",
"k",
"=",
"1",
")",
".",
"astype... | Extract upper triangle from a square matrix. Negative values are
set to 0.
Args:
correlation_matrix (pandas df): Correlations between all replicates
Returns:
upper_tri_df (pandas df): Upper triangle extracted from
correlation_matrix; rid is the row index, cid is the column index,
corr is the extracted correlation value | [
"Extract",
"upper",
"triangle",
"from",
"a",
"square",
"matrix",
".",
"Negative",
"values",
"are",
"set",
"to",
"0",
"."
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/math/agg_wt_avg.py#L17-L41 |
18,532 | cmap/cmapPy | cmapPy/math/agg_wt_avg.py | calculate_weights | def calculate_weights(correlation_matrix, min_wt):
''' Calculate a weight for each profile based on its correlation to other
replicates. Negative correlations are clipped to 0, and weights are clipped
to be min_wt at the least.
Args:
correlation_matrix (pandas df): Correlations between all replicates
min_wt (float): Minimum raw weight when calculating weighted average
Returns:
raw weights (pandas series): Mean correlation to other replicates
weights (pandas series): raw_weights normalized such that they add to 1
'''
# fill diagonal of correlation_matrix with np.nan
np.fill_diagonal(correlation_matrix.values, np.nan)
# remove negative values
correlation_matrix = correlation_matrix.clip(lower=0)
# get average correlation for each profile (will ignore NaN)
raw_weights = correlation_matrix.mean(axis=1)
# threshold weights
raw_weights = raw_weights.clip(lower=min_wt)
# normalize raw_weights so that they add to 1
weights = raw_weights / sum(raw_weights)
return raw_weights.round(rounding_precision), weights.round(rounding_precision) | python | def calculate_weights(correlation_matrix, min_wt):
''' Calculate a weight for each profile based on its correlation to other
replicates. Negative correlations are clipped to 0, and weights are clipped
to be min_wt at the least.
Args:
correlation_matrix (pandas df): Correlations between all replicates
min_wt (float): Minimum raw weight when calculating weighted average
Returns:
raw weights (pandas series): Mean correlation to other replicates
weights (pandas series): raw_weights normalized such that they add to 1
'''
# fill diagonal of correlation_matrix with np.nan
np.fill_diagonal(correlation_matrix.values, np.nan)
# remove negative values
correlation_matrix = correlation_matrix.clip(lower=0)
# get average correlation for each profile (will ignore NaN)
raw_weights = correlation_matrix.mean(axis=1)
# threshold weights
raw_weights = raw_weights.clip(lower=min_wt)
# normalize raw_weights so that they add to 1
weights = raw_weights / sum(raw_weights)
return raw_weights.round(rounding_precision), weights.round(rounding_precision) | [
"def",
"calculate_weights",
"(",
"correlation_matrix",
",",
"min_wt",
")",
":",
"# fill diagonal of correlation_matrix with np.nan",
"np",
".",
"fill_diagonal",
"(",
"correlation_matrix",
".",
"values",
",",
"np",
".",
"nan",
")",
"# remove negative values",
"correlation_... | Calculate a weight for each profile based on its correlation to other
replicates. Negative correlations are clipped to 0, and weights are clipped
to be min_wt at the least.
Args:
correlation_matrix (pandas df): Correlations between all replicates
min_wt (float): Minimum raw weight when calculating weighted average
Returns:
raw weights (pandas series): Mean correlation to other replicates
weights (pandas series): raw_weights normalized such that they add to 1 | [
"Calculate",
"a",
"weight",
"for",
"each",
"profile",
"based",
"on",
"its",
"correlation",
"to",
"other",
"replicates",
".",
"Negative",
"correlations",
"are",
"clipped",
"to",
"0",
"and",
"weights",
"are",
"clipped",
"to",
"be",
"min_wt",
"at",
"the",
"leas... | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/math/agg_wt_avg.py#L44-L72 |
18,533 | cmap/cmapPy | cmapPy/math/agg_wt_avg.py | agg_wt_avg | def agg_wt_avg(mat, min_wt = 0.01, corr_metric='spearman'):
''' Aggregate a set of replicate profiles into a single signature using
a weighted average.
Args:
mat (pandas df): a matrix of replicate profiles, where the columns are
samples and the rows are features; columns correspond to the
replicates of a single perturbagen
min_wt (float): Minimum raw weight when calculating weighted average
corr_metric (string): Spearman or Pearson; the correlation method
Returns:
out_sig (pandas series): weighted average values
upper_tri_df (pandas df): the correlations between each profile that went into the signature
raw weights (pandas series): weights before normalization
weights (pandas series): weights after normalization
'''
assert mat.shape[1] > 0, "mat is empty! mat: {}".format(mat)
if mat.shape[1] == 1:
out_sig = mat
upper_tri_df = None
raw_weights = None
weights = None
else:
assert corr_metric in ["spearman", "pearson"]
# Make correlation matrix column wise
corr_mat = mat.corr(method=corr_metric)
# Save the values in the upper triangle
upper_tri_df = get_upper_triangle(corr_mat)
# Calculate weight per replicate
raw_weights, weights = calculate_weights(corr_mat, min_wt)
# Apply weights to values
weighted_values = mat * weights
out_sig = weighted_values.sum(axis=1)
return out_sig, upper_tri_df, raw_weights, weights | python | def agg_wt_avg(mat, min_wt = 0.01, corr_metric='spearman'):
''' Aggregate a set of replicate profiles into a single signature using
a weighted average.
Args:
mat (pandas df): a matrix of replicate profiles, where the columns are
samples and the rows are features; columns correspond to the
replicates of a single perturbagen
min_wt (float): Minimum raw weight when calculating weighted average
corr_metric (string): Spearman or Pearson; the correlation method
Returns:
out_sig (pandas series): weighted average values
upper_tri_df (pandas df): the correlations between each profile that went into the signature
raw weights (pandas series): weights before normalization
weights (pandas series): weights after normalization
'''
assert mat.shape[1] > 0, "mat is empty! mat: {}".format(mat)
if mat.shape[1] == 1:
out_sig = mat
upper_tri_df = None
raw_weights = None
weights = None
else:
assert corr_metric in ["spearman", "pearson"]
# Make correlation matrix column wise
corr_mat = mat.corr(method=corr_metric)
# Save the values in the upper triangle
upper_tri_df = get_upper_triangle(corr_mat)
# Calculate weight per replicate
raw_weights, weights = calculate_weights(corr_mat, min_wt)
# Apply weights to values
weighted_values = mat * weights
out_sig = weighted_values.sum(axis=1)
return out_sig, upper_tri_df, raw_weights, weights | [
"def",
"agg_wt_avg",
"(",
"mat",
",",
"min_wt",
"=",
"0.01",
",",
"corr_metric",
"=",
"'spearman'",
")",
":",
"assert",
"mat",
".",
"shape",
"[",
"1",
"]",
">",
"0",
",",
"\"mat is empty! mat: {}\"",
".",
"format",
"(",
"mat",
")",
"if",
"mat",
".",
... | Aggregate a set of replicate profiles into a single signature using
a weighted average.
Args:
mat (pandas df): a matrix of replicate profiles, where the columns are
samples and the rows are features; columns correspond to the
replicates of a single perturbagen
min_wt (float): Minimum raw weight when calculating weighted average
corr_metric (string): Spearman or Pearson; the correlation method
Returns:
out_sig (pandas series): weighted average values
upper_tri_df (pandas df): the correlations between each profile that went into the signature
raw weights (pandas series): weights before normalization
weights (pandas series): weights after normalization | [
"Aggregate",
"a",
"set",
"of",
"replicate",
"profiles",
"into",
"a",
"single",
"signature",
"using",
"a",
"weighted",
"average",
"."
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/math/agg_wt_avg.py#L75-L118 |
18,534 | cmap/cmapPy | cmapPy/pandasGEXpress/concat.py | get_file_list | def get_file_list(wildcard):
""" Search for files to be concatenated. Currently very basic, but could
expand to be more sophisticated.
Args:
wildcard (regular expression string)
Returns:
files (list of full file paths)
"""
files = glob.glob(os.path.expanduser(wildcard))
return files | python | def get_file_list(wildcard):
files = glob.glob(os.path.expanduser(wildcard))
return files | [
"def",
"get_file_list",
"(",
"wildcard",
")",
":",
"files",
"=",
"glob",
".",
"glob",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"wildcard",
")",
")",
"return",
"files"
] | Search for files to be concatenated. Currently very basic, but could
expand to be more sophisticated.
Args:
wildcard (regular expression string)
Returns:
files (list of full file paths) | [
"Search",
"for",
"files",
"to",
"be",
"concatenated",
".",
"Currently",
"very",
"basic",
"but",
"could",
"expand",
"to",
"be",
"more",
"sophisticated",
"."
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/concat.py#L158-L170 |
18,535 | cmap/cmapPy | cmapPy/pandasGEXpress/concat.py | hstack | def hstack(gctoos, remove_all_metadata_fields=False, error_report_file=None, fields_to_remove=[], reset_ids=False):
""" Horizontally concatenate gctoos.
Args:
gctoos (list of gctoo objects)
remove_all_metadata_fields (bool): ignore/strip all common metadata when combining gctoos
error_report_file (string): path to write file containing error report indicating
problems that occurred during hstack, mainly for inconsistencies in common metadata
fields_to_remove (list of strings): fields to be removed from the
common metadata because they don't agree across files
reset_ids (bool): set to True if sample ids are not unique
Return:
concated (gctoo object)
"""
# Separate each gctoo into its component dfs
row_meta_dfs = []
col_meta_dfs = []
data_dfs = []
srcs = []
for g in gctoos:
row_meta_dfs.append(g.row_metadata_df)
col_meta_dfs.append(g.col_metadata_df)
data_dfs.append(g.data_df)
srcs.append(g.src)
logger.debug("shapes of row_meta_dfs: {}".format([x.shape for x in row_meta_dfs]))
# Concatenate row metadata
all_row_metadata_df = assemble_common_meta(row_meta_dfs, fields_to_remove, srcs, remove_all_metadata_fields, error_report_file)
# Concatenate col metadata
all_col_metadata_df = assemble_concatenated_meta(col_meta_dfs, remove_all_metadata_fields)
# Concatenate the data_dfs
all_data_df = assemble_data(data_dfs, "horiz")
# Make sure df shapes are correct
assert all_data_df.shape[0] == all_row_metadata_df.shape[0], "Number of rows in metadata does not match number of rows in data - all_data_df.shape[0]: {} all_row_metadata_df.shape[0]: {}".format(all_data_df.shape[0], all_row_metadata_df.shape[0])
assert all_data_df.shape[1] == all_col_metadata_df.shape[0], "Number of columns in data does not match number of columns metadata - all_data_df.shape[1]: {} all_col_metadata_df.shape[0]: {}".format(all_data_df.shape[1], all_col_metadata_df.shape[0])
# If requested, reset sample ids to be unique integers and move old sample
# ids into column metadata
if reset_ids:
do_reset_ids(all_col_metadata_df, all_data_df, "horiz")
logger.info("Build GCToo of all...")
concated = GCToo.GCToo(row_metadata_df=all_row_metadata_df,
col_metadata_df=all_col_metadata_df,
data_df=all_data_df)
return concated | python | def hstack(gctoos, remove_all_metadata_fields=False, error_report_file=None, fields_to_remove=[], reset_ids=False):
# Separate each gctoo into its component dfs
row_meta_dfs = []
col_meta_dfs = []
data_dfs = []
srcs = []
for g in gctoos:
row_meta_dfs.append(g.row_metadata_df)
col_meta_dfs.append(g.col_metadata_df)
data_dfs.append(g.data_df)
srcs.append(g.src)
logger.debug("shapes of row_meta_dfs: {}".format([x.shape for x in row_meta_dfs]))
# Concatenate row metadata
all_row_metadata_df = assemble_common_meta(row_meta_dfs, fields_to_remove, srcs, remove_all_metadata_fields, error_report_file)
# Concatenate col metadata
all_col_metadata_df = assemble_concatenated_meta(col_meta_dfs, remove_all_metadata_fields)
# Concatenate the data_dfs
all_data_df = assemble_data(data_dfs, "horiz")
# Make sure df shapes are correct
assert all_data_df.shape[0] == all_row_metadata_df.shape[0], "Number of rows in metadata does not match number of rows in data - all_data_df.shape[0]: {} all_row_metadata_df.shape[0]: {}".format(all_data_df.shape[0], all_row_metadata_df.shape[0])
assert all_data_df.shape[1] == all_col_metadata_df.shape[0], "Number of columns in data does not match number of columns metadata - all_data_df.shape[1]: {} all_col_metadata_df.shape[0]: {}".format(all_data_df.shape[1], all_col_metadata_df.shape[0])
# If requested, reset sample ids to be unique integers and move old sample
# ids into column metadata
if reset_ids:
do_reset_ids(all_col_metadata_df, all_data_df, "horiz")
logger.info("Build GCToo of all...")
concated = GCToo.GCToo(row_metadata_df=all_row_metadata_df,
col_metadata_df=all_col_metadata_df,
data_df=all_data_df)
return concated | [
"def",
"hstack",
"(",
"gctoos",
",",
"remove_all_metadata_fields",
"=",
"False",
",",
"error_report_file",
"=",
"None",
",",
"fields_to_remove",
"=",
"[",
"]",
",",
"reset_ids",
"=",
"False",
")",
":",
"# Separate each gctoo into its component dfs",
"row_meta_dfs",
... | Horizontally concatenate gctoos.
Args:
gctoos (list of gctoo objects)
remove_all_metadata_fields (bool): ignore/strip all common metadata when combining gctoos
error_report_file (string): path to write file containing error report indicating
problems that occurred during hstack, mainly for inconsistencies in common metadata
fields_to_remove (list of strings): fields to be removed from the
common metadata because they don't agree across files
reset_ids (bool): set to True if sample ids are not unique
Return:
concated (gctoo object) | [
"Horizontally",
"concatenate",
"gctoos",
"."
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/concat.py#L173-L224 |
18,536 | cmap/cmapPy | cmapPy/pandasGEXpress/concat.py | assemble_concatenated_meta | def assemble_concatenated_meta(concated_meta_dfs, remove_all_metadata_fields):
""" Assemble the concatenated metadata dfs together. For example,
if horizontally concatenating, the concatenated metadata dfs are the
column metadata dfs. Both indices are sorted.
Args:
concated_meta_dfs (list of pandas dfs)
Returns:
all_concated_meta_df_sorted (pandas df)
"""
# Concatenate the concated_meta_dfs
if remove_all_metadata_fields:
for df in concated_meta_dfs:
df.drop(df.columns, axis=1, inplace=True)
all_concated_meta_df = pd.concat(concated_meta_dfs, axis=0)
# Sanity check: the number of rows in all_concated_meta_df should correspond
# to the sum of the number of rows in the input dfs
n_rows = all_concated_meta_df.shape[0]
logger.debug("all_concated_meta_df.shape[0]: {}".format(n_rows))
n_rows_cumulative = sum([df.shape[0] for df in concated_meta_dfs])
assert n_rows == n_rows_cumulative
# Sort the index and columns
all_concated_meta_df_sorted = all_concated_meta_df.sort_index(axis=0).sort_index(axis=1)
return all_concated_meta_df_sorted | python | def assemble_concatenated_meta(concated_meta_dfs, remove_all_metadata_fields):
# Concatenate the concated_meta_dfs
if remove_all_metadata_fields:
for df in concated_meta_dfs:
df.drop(df.columns, axis=1, inplace=True)
all_concated_meta_df = pd.concat(concated_meta_dfs, axis=0)
# Sanity check: the number of rows in all_concated_meta_df should correspond
# to the sum of the number of rows in the input dfs
n_rows = all_concated_meta_df.shape[0]
logger.debug("all_concated_meta_df.shape[0]: {}".format(n_rows))
n_rows_cumulative = sum([df.shape[0] for df in concated_meta_dfs])
assert n_rows == n_rows_cumulative
# Sort the index and columns
all_concated_meta_df_sorted = all_concated_meta_df.sort_index(axis=0).sort_index(axis=1)
return all_concated_meta_df_sorted | [
"def",
"assemble_concatenated_meta",
"(",
"concated_meta_dfs",
",",
"remove_all_metadata_fields",
")",
":",
"# Concatenate the concated_meta_dfs",
"if",
"remove_all_metadata_fields",
":",
"for",
"df",
"in",
"concated_meta_dfs",
":",
"df",
".",
"drop",
"(",
"df",
".",
"c... | Assemble the concatenated metadata dfs together. For example,
if horizontally concatenating, the concatenated metadata dfs are the
column metadata dfs. Both indices are sorted.
Args:
concated_meta_dfs (list of pandas dfs)
Returns:
all_concated_meta_df_sorted (pandas df) | [
"Assemble",
"the",
"concatenated",
"metadata",
"dfs",
"together",
".",
"For",
"example",
"if",
"horizontally",
"concatenating",
"the",
"concatenated",
"metadata",
"dfs",
"are",
"the",
"column",
"metadata",
"dfs",
".",
"Both",
"indices",
"are",
"sorted",
"."
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/concat.py#L423-L452 |
18,537 | cmap/cmapPy | cmapPy/pandasGEXpress/concat.py | assemble_data | def assemble_data(data_dfs, concat_direction):
""" Assemble the data dfs together. Both indices are sorted.
Args:
data_dfs (list of pandas dfs)
concat_direction (string): 'horiz' or 'vert'
Returns:
all_data_df_sorted (pandas df)
"""
if concat_direction == "horiz":
# Concatenate the data_dfs horizontally
all_data_df = pd.concat(data_dfs, axis=1)
# Sanity check: the number of columns in all_data_df should
# correspond to the sum of the number of columns in the input dfs
n_cols = all_data_df.shape[1]
logger.debug("all_data_df.shape[1]: {}".format(n_cols))
n_cols_cumulative = sum([df.shape[1] for df in data_dfs])
assert n_cols == n_cols_cumulative
elif concat_direction == "vert":
# Concatenate the data_dfs vertically
all_data_df = pd.concat(data_dfs, axis=0)
# Sanity check: the number of rows in all_data_df should
# correspond to the sum of the number of rows in the input dfs
n_rows = all_data_df.shape[0]
logger.debug("all_data_df.shape[0]: {}".format(n_rows))
n_rows_cumulative = sum([df.shape[0] for df in data_dfs])
assert n_rows == n_rows_cumulative
# Sort both indices
all_data_df_sorted = all_data_df.sort_index(axis=0).sort_index(axis=1)
return all_data_df_sorted | python | def assemble_data(data_dfs, concat_direction):
if concat_direction == "horiz":
# Concatenate the data_dfs horizontally
all_data_df = pd.concat(data_dfs, axis=1)
# Sanity check: the number of columns in all_data_df should
# correspond to the sum of the number of columns in the input dfs
n_cols = all_data_df.shape[1]
logger.debug("all_data_df.shape[1]: {}".format(n_cols))
n_cols_cumulative = sum([df.shape[1] for df in data_dfs])
assert n_cols == n_cols_cumulative
elif concat_direction == "vert":
# Concatenate the data_dfs vertically
all_data_df = pd.concat(data_dfs, axis=0)
# Sanity check: the number of rows in all_data_df should
# correspond to the sum of the number of rows in the input dfs
n_rows = all_data_df.shape[0]
logger.debug("all_data_df.shape[0]: {}".format(n_rows))
n_rows_cumulative = sum([df.shape[0] for df in data_dfs])
assert n_rows == n_rows_cumulative
# Sort both indices
all_data_df_sorted = all_data_df.sort_index(axis=0).sort_index(axis=1)
return all_data_df_sorted | [
"def",
"assemble_data",
"(",
"data_dfs",
",",
"concat_direction",
")",
":",
"if",
"concat_direction",
"==",
"\"horiz\"",
":",
"# Concatenate the data_dfs horizontally",
"all_data_df",
"=",
"pd",
".",
"concat",
"(",
"data_dfs",
",",
"axis",
"=",
"1",
")",
"# Sanity... | Assemble the data dfs together. Both indices are sorted.
Args:
data_dfs (list of pandas dfs)
concat_direction (string): 'horiz' or 'vert'
Returns:
all_data_df_sorted (pandas df) | [
"Assemble",
"the",
"data",
"dfs",
"together",
".",
"Both",
"indices",
"are",
"sorted",
"."
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/concat.py#L455-L492 |
18,538 | cmap/cmapPy | cmapPy/pandasGEXpress/concat.py | do_reset_ids | def do_reset_ids(concatenated_meta_df, data_df, concat_direction):
""" Reset ids in concatenated metadata and data dfs to unique integers and
save the old ids in a metadata column.
Note that the dataframes are modified in-place.
Args:
concatenated_meta_df (pandas df)
data_df (pandas df)
concat_direction (string): 'horiz' or 'vert'
Returns:
None (dfs modified in-place)
"""
if concat_direction == "horiz":
# Make sure cids agree between data_df and concatenated_meta_df
assert concatenated_meta_df.index.equals(data_df.columns), (
"cids in concatenated_meta_df do not agree with cids in data_df.")
# Reset cids in concatenated_meta_df
reset_ids_in_meta_df(concatenated_meta_df)
# Replace cids in data_df with the new ones from concatenated_meta_df
# (just an array of unique integers, zero-indexed)
data_df.columns = pd.Index(concatenated_meta_df.index.values)
elif concat_direction == "vert":
# Make sure rids agree between data_df and concatenated_meta_df
assert concatenated_meta_df.index.equals(data_df.index), (
"rids in concatenated_meta_df do not agree with rids in data_df.")
# Reset rids in concatenated_meta_df
reset_ids_in_meta_df(concatenated_meta_df)
# Replace rids in data_df with the new ones from concatenated_meta_df
# (just an array of unique integers, zero-indexed)
data_df.index = pd.Index(concatenated_meta_df.index.values) | python | def do_reset_ids(concatenated_meta_df, data_df, concat_direction):
if concat_direction == "horiz":
# Make sure cids agree between data_df and concatenated_meta_df
assert concatenated_meta_df.index.equals(data_df.columns), (
"cids in concatenated_meta_df do not agree with cids in data_df.")
# Reset cids in concatenated_meta_df
reset_ids_in_meta_df(concatenated_meta_df)
# Replace cids in data_df with the new ones from concatenated_meta_df
# (just an array of unique integers, zero-indexed)
data_df.columns = pd.Index(concatenated_meta_df.index.values)
elif concat_direction == "vert":
# Make sure rids agree between data_df and concatenated_meta_df
assert concatenated_meta_df.index.equals(data_df.index), (
"rids in concatenated_meta_df do not agree with rids in data_df.")
# Reset rids in concatenated_meta_df
reset_ids_in_meta_df(concatenated_meta_df)
# Replace rids in data_df with the new ones from concatenated_meta_df
# (just an array of unique integers, zero-indexed)
data_df.index = pd.Index(concatenated_meta_df.index.values) | [
"def",
"do_reset_ids",
"(",
"concatenated_meta_df",
",",
"data_df",
",",
"concat_direction",
")",
":",
"if",
"concat_direction",
"==",
"\"horiz\"",
":",
"# Make sure cids agree between data_df and concatenated_meta_df",
"assert",
"concatenated_meta_df",
".",
"index",
".",
"... | Reset ids in concatenated metadata and data dfs to unique integers and
save the old ids in a metadata column.
Note that the dataframes are modified in-place.
Args:
concatenated_meta_df (pandas df)
data_df (pandas df)
concat_direction (string): 'horiz' or 'vert'
Returns:
None (dfs modified in-place) | [
"Reset",
"ids",
"in",
"concatenated",
"metadata",
"and",
"data",
"dfs",
"to",
"unique",
"integers",
"and",
"save",
"the",
"old",
"ids",
"in",
"a",
"metadata",
"column",
"."
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/concat.py#L495-L534 |
18,539 | cmap/cmapPy | cmapPy/pandasGEXpress/concat.py | reset_ids_in_meta_df | def reset_ids_in_meta_df(meta_df):
""" Meta_df is modified inplace. """
# Record original index name, and then change it so that the column that it
# becomes will be appropriately named
original_index_name = meta_df.index.name
meta_df.index.name = "old_id"
# Reset index
meta_df.reset_index(inplace=True)
# Change the index name back to what it was
meta_df.index.name = original_index_name | python | def reset_ids_in_meta_df(meta_df):
# Record original index name, and then change it so that the column that it
# becomes will be appropriately named
original_index_name = meta_df.index.name
meta_df.index.name = "old_id"
# Reset index
meta_df.reset_index(inplace=True)
# Change the index name back to what it was
meta_df.index.name = original_index_name | [
"def",
"reset_ids_in_meta_df",
"(",
"meta_df",
")",
":",
"# Record original index name, and then change it so that the column that it",
"# becomes will be appropriately named",
"original_index_name",
"=",
"meta_df",
".",
"index",
".",
"name",
"meta_df",
".",
"index",
".",
"name... | Meta_df is modified inplace. | [
"Meta_df",
"is",
"modified",
"inplace",
"."
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/concat.py#L537-L549 |
18,540 | cmap/cmapPy | cmapPy/pandasGEXpress/subset_gctoo.py | subset_gctoo | def subset_gctoo(gctoo, row_bool=None, col_bool=None, rid=None, cid=None,
ridx=None, cidx=None, exclude_rid=None, exclude_cid=None):
""" Extract a subset of data from a GCToo object in a variety of ways.
The order of rows and columns will be preserved.
Args:
gctoo (GCToo object)
row_bool (list of bools): length must equal gctoo.data_df.shape[0]
col_bool (list of bools): length must equal gctoo.data_df.shape[1]
rid (list of strings): rids to include
cid (list of strings): cids to include
ridx (list of integers): row integer ids to include
cidx (list of integers): col integer ids to include
exclude_rid (list of strings): rids to exclude
exclude_cid (list of strings): cids to exclude
Returns:
out_gctoo (GCToo object): gctoo after subsetting
"""
assert sum([(rid is not None), (row_bool is not None), (ridx is not None)]) <= 1, (
"Only one of rid, row_bool, and ridx can be provided.")
assert sum([(cid is not None), (col_bool is not None), (cidx is not None)]) <= 1, (
"Only one of cid, col_bool, and cidx can be provided.")
# Figure out what rows and columns to keep
rows_to_keep = get_rows_to_keep(gctoo, rid, row_bool, ridx, exclude_rid)
cols_to_keep = get_cols_to_keep(gctoo, cid, col_bool, cidx, exclude_cid)
# Convert labels to boolean array to preserve order
rows_to_keep_bools = gctoo.data_df.index.isin(rows_to_keep)
cols_to_keep_bools = gctoo.data_df.columns.isin(cols_to_keep)
# Make the output gct
out_gctoo = GCToo.GCToo(
src=gctoo.src, version=gctoo.version,
data_df=gctoo.data_df.loc[rows_to_keep_bools, cols_to_keep_bools],
row_metadata_df=gctoo.row_metadata_df.loc[rows_to_keep_bools, :],
col_metadata_df=gctoo.col_metadata_df.loc[cols_to_keep_bools, :])
assert out_gctoo.data_df.size > 0, "Subsetting yielded an empty gct!"
logger.info(("Initial GCToo with {} rows and {} columns subsetted down to " +
"{} rows and {} columns.").format(
gctoo.data_df.shape[0], gctoo.data_df.shape[1],
out_gctoo.data_df.shape[0], out_gctoo.data_df.shape[1]))
return out_gctoo | python | def subset_gctoo(gctoo, row_bool=None, col_bool=None, rid=None, cid=None,
ridx=None, cidx=None, exclude_rid=None, exclude_cid=None):
assert sum([(rid is not None), (row_bool is not None), (ridx is not None)]) <= 1, (
"Only one of rid, row_bool, and ridx can be provided.")
assert sum([(cid is not None), (col_bool is not None), (cidx is not None)]) <= 1, (
"Only one of cid, col_bool, and cidx can be provided.")
# Figure out what rows and columns to keep
rows_to_keep = get_rows_to_keep(gctoo, rid, row_bool, ridx, exclude_rid)
cols_to_keep = get_cols_to_keep(gctoo, cid, col_bool, cidx, exclude_cid)
# Convert labels to boolean array to preserve order
rows_to_keep_bools = gctoo.data_df.index.isin(rows_to_keep)
cols_to_keep_bools = gctoo.data_df.columns.isin(cols_to_keep)
# Make the output gct
out_gctoo = GCToo.GCToo(
src=gctoo.src, version=gctoo.version,
data_df=gctoo.data_df.loc[rows_to_keep_bools, cols_to_keep_bools],
row_metadata_df=gctoo.row_metadata_df.loc[rows_to_keep_bools, :],
col_metadata_df=gctoo.col_metadata_df.loc[cols_to_keep_bools, :])
assert out_gctoo.data_df.size > 0, "Subsetting yielded an empty gct!"
logger.info(("Initial GCToo with {} rows and {} columns subsetted down to " +
"{} rows and {} columns.").format(
gctoo.data_df.shape[0], gctoo.data_df.shape[1],
out_gctoo.data_df.shape[0], out_gctoo.data_df.shape[1]))
return out_gctoo | [
"def",
"subset_gctoo",
"(",
"gctoo",
",",
"row_bool",
"=",
"None",
",",
"col_bool",
"=",
"None",
",",
"rid",
"=",
"None",
",",
"cid",
"=",
"None",
",",
"ridx",
"=",
"None",
",",
"cidx",
"=",
"None",
",",
"exclude_rid",
"=",
"None",
",",
"exclude_cid"... | Extract a subset of data from a GCToo object in a variety of ways.
The order of rows and columns will be preserved.
Args:
gctoo (GCToo object)
row_bool (list of bools): length must equal gctoo.data_df.shape[0]
col_bool (list of bools): length must equal gctoo.data_df.shape[1]
rid (list of strings): rids to include
cid (list of strings): cids to include
ridx (list of integers): row integer ids to include
cidx (list of integers): col integer ids to include
exclude_rid (list of strings): rids to exclude
exclude_cid (list of strings): cids to exclude
Returns:
out_gctoo (GCToo object): gctoo after subsetting | [
"Extract",
"a",
"subset",
"of",
"data",
"from",
"a",
"GCToo",
"object",
"in",
"a",
"variety",
"of",
"ways",
".",
"The",
"order",
"of",
"rows",
"and",
"columns",
"will",
"be",
"preserved",
"."
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/subset_gctoo.py#L19-L65 |
18,541 | cmap/cmapPy | cmapPy/pandasGEXpress/subset_gctoo.py | get_rows_to_keep | def get_rows_to_keep(gctoo, rid=None, row_bool=None, ridx=None, exclude_rid=None):
""" Figure out based on the possible row inputs which rows to keep.
Args:
gctoo (GCToo object):
rid (list of strings):
row_bool (boolean array):
ridx (list of integers):
exclude_rid (list of strings):
Returns:
rows_to_keep (list of strings): row ids to be kept
"""
# Use rid if provided
if rid is not None:
assert type(rid) == list, "rid must be a list. rid: {}".format(rid)
rows_to_keep = [gctoo_row for gctoo_row in gctoo.data_df.index if gctoo_row in rid]
# Tell user if some rids not found
num_missing_rids = len(rid) - len(rows_to_keep)
if num_missing_rids != 0:
logger.info("{} rids were not found in the GCT.".format(num_missing_rids))
# Use row_bool if provided
elif row_bool is not None:
assert len(row_bool) == gctoo.data_df.shape[0], (
"row_bool must have length equal to gctoo.data_df.shape[0]. " +
"len(row_bool): {}, gctoo.data_df.shape[0]: {}".format(
len(row_bool), gctoo.data_df.shape[0]))
rows_to_keep = gctoo.data_df.index[row_bool].values
# Use ridx if provided
elif ridx is not None:
assert type(ridx[0]) is int, (
"ridx must be a list of integers. ridx[0]: {}, " +
"type(ridx[0]): {}").format(ridx[0], type(ridx[0]))
assert max(ridx) <= gctoo.data_df.shape[0], (
"ridx contains an integer larger than the number of rows in " +
"the GCToo. max(ridx): {}, gctoo.data_df.shape[0]: {}").format(
max(ridx), gctoo.data_df.shape[0])
rows_to_keep = gctoo.data_df.index[ridx].values
# If rid, row_bool, and ridx are all None, return all rows
else:
rows_to_keep = gctoo.data_df.index.values
# Use exclude_rid if provided
if exclude_rid is not None:
# Keep only those rows that are not in exclude_rid
rows_to_keep = [row_to_keep for row_to_keep in rows_to_keep if row_to_keep not in exclude_rid]
return rows_to_keep | python | def get_rows_to_keep(gctoo, rid=None, row_bool=None, ridx=None, exclude_rid=None):
# Use rid if provided
if rid is not None:
assert type(rid) == list, "rid must be a list. rid: {}".format(rid)
rows_to_keep = [gctoo_row for gctoo_row in gctoo.data_df.index if gctoo_row in rid]
# Tell user if some rids not found
num_missing_rids = len(rid) - len(rows_to_keep)
if num_missing_rids != 0:
logger.info("{} rids were not found in the GCT.".format(num_missing_rids))
# Use row_bool if provided
elif row_bool is not None:
assert len(row_bool) == gctoo.data_df.shape[0], (
"row_bool must have length equal to gctoo.data_df.shape[0]. " +
"len(row_bool): {}, gctoo.data_df.shape[0]: {}".format(
len(row_bool), gctoo.data_df.shape[0]))
rows_to_keep = gctoo.data_df.index[row_bool].values
# Use ridx if provided
elif ridx is not None:
assert type(ridx[0]) is int, (
"ridx must be a list of integers. ridx[0]: {}, " +
"type(ridx[0]): {}").format(ridx[0], type(ridx[0]))
assert max(ridx) <= gctoo.data_df.shape[0], (
"ridx contains an integer larger than the number of rows in " +
"the GCToo. max(ridx): {}, gctoo.data_df.shape[0]: {}").format(
max(ridx), gctoo.data_df.shape[0])
rows_to_keep = gctoo.data_df.index[ridx].values
# If rid, row_bool, and ridx are all None, return all rows
else:
rows_to_keep = gctoo.data_df.index.values
# Use exclude_rid if provided
if exclude_rid is not None:
# Keep only those rows that are not in exclude_rid
rows_to_keep = [row_to_keep for row_to_keep in rows_to_keep if row_to_keep not in exclude_rid]
return rows_to_keep | [
"def",
"get_rows_to_keep",
"(",
"gctoo",
",",
"rid",
"=",
"None",
",",
"row_bool",
"=",
"None",
",",
"ridx",
"=",
"None",
",",
"exclude_rid",
"=",
"None",
")",
":",
"# Use rid if provided",
"if",
"rid",
"is",
"not",
"None",
":",
"assert",
"type",
"(",
... | Figure out based on the possible row inputs which rows to keep.
Args:
gctoo (GCToo object):
rid (list of strings):
row_bool (boolean array):
ridx (list of integers):
exclude_rid (list of strings):
Returns:
rows_to_keep (list of strings): row ids to be kept | [
"Figure",
"out",
"based",
"on",
"the",
"possible",
"row",
"inputs",
"which",
"rows",
"to",
"keep",
"."
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/subset_gctoo.py#L68-L126 |
18,542 | cmap/cmapPy | cmapPy/pandasGEXpress/subset_gctoo.py | get_cols_to_keep | def get_cols_to_keep(gctoo, cid=None, col_bool=None, cidx=None, exclude_cid=None):
""" Figure out based on the possible columns inputs which columns to keep.
Args:
gctoo (GCToo object):
cid (list of strings):
col_bool (boolean array):
cidx (list of integers):
exclude_cid (list of strings):
Returns:
cols_to_keep (list of strings): col ids to be kept
"""
# Use cid if provided
if cid is not None:
assert type(cid) == list, "cid must be a list. cid: {}".format(cid)
cols_to_keep = [gctoo_col for gctoo_col in gctoo.data_df.columns if gctoo_col in cid]
# Tell user if some cids not found
num_missing_cids = len(cid) - len(cols_to_keep)
if num_missing_cids != 0:
logger.info("{} cids were not found in the GCT.".format(num_missing_cids))
# Use col_bool if provided
elif col_bool is not None:
assert len(col_bool) == gctoo.data_df.shape[1], (
"col_bool must have length equal to gctoo.data_df.shape[1]. " +
"len(col_bool): {}, gctoo.data_df.shape[1]: {}".format(
len(col_bool), gctoo.data_df.shape[1]))
cols_to_keep = gctoo.data_df.columns[col_bool].values
# Use cidx if provided
elif cidx is not None:
assert type(cidx[0]) is int, (
"cidx must be a list of integers. cidx[0]: {}, " +
"type(cidx[0]): {}").format(cidx[0], type(cidx[0]))
assert max(cidx) <= gctoo.data_df.shape[1], (
"cidx contains an integer larger than the number of columns in " +
"the GCToo. max(cidx): {}, gctoo.data_df.shape[1]: {}").format(
max(cidx), gctoo.data_df.shape[1])
cols_to_keep = gctoo.data_df.columns[cidx].values
# If cid, col_bool, and cidx are all None, return all columns
else:
cols_to_keep = gctoo.data_df.columns.values
# Use exclude_cid if provided
if exclude_cid is not None:
# Keep only those columns that are not in exclude_cid
cols_to_keep = [col_to_keep for col_to_keep in cols_to_keep if col_to_keep not in exclude_cid]
return cols_to_keep | python | def get_cols_to_keep(gctoo, cid=None, col_bool=None, cidx=None, exclude_cid=None):
# Use cid if provided
if cid is not None:
assert type(cid) == list, "cid must be a list. cid: {}".format(cid)
cols_to_keep = [gctoo_col for gctoo_col in gctoo.data_df.columns if gctoo_col in cid]
# Tell user if some cids not found
num_missing_cids = len(cid) - len(cols_to_keep)
if num_missing_cids != 0:
logger.info("{} cids were not found in the GCT.".format(num_missing_cids))
# Use col_bool if provided
elif col_bool is not None:
assert len(col_bool) == gctoo.data_df.shape[1], (
"col_bool must have length equal to gctoo.data_df.shape[1]. " +
"len(col_bool): {}, gctoo.data_df.shape[1]: {}".format(
len(col_bool), gctoo.data_df.shape[1]))
cols_to_keep = gctoo.data_df.columns[col_bool].values
# Use cidx if provided
elif cidx is not None:
assert type(cidx[0]) is int, (
"cidx must be a list of integers. cidx[0]: {}, " +
"type(cidx[0]): {}").format(cidx[0], type(cidx[0]))
assert max(cidx) <= gctoo.data_df.shape[1], (
"cidx contains an integer larger than the number of columns in " +
"the GCToo. max(cidx): {}, gctoo.data_df.shape[1]: {}").format(
max(cidx), gctoo.data_df.shape[1])
cols_to_keep = gctoo.data_df.columns[cidx].values
# If cid, col_bool, and cidx are all None, return all columns
else:
cols_to_keep = gctoo.data_df.columns.values
# Use exclude_cid if provided
if exclude_cid is not None:
# Keep only those columns that are not in exclude_cid
cols_to_keep = [col_to_keep for col_to_keep in cols_to_keep if col_to_keep not in exclude_cid]
return cols_to_keep | [
"def",
"get_cols_to_keep",
"(",
"gctoo",
",",
"cid",
"=",
"None",
",",
"col_bool",
"=",
"None",
",",
"cidx",
"=",
"None",
",",
"exclude_cid",
"=",
"None",
")",
":",
"# Use cid if provided",
"if",
"cid",
"is",
"not",
"None",
":",
"assert",
"type",
"(",
... | Figure out based on the possible columns inputs which columns to keep.
Args:
gctoo (GCToo object):
cid (list of strings):
col_bool (boolean array):
cidx (list of integers):
exclude_cid (list of strings):
Returns:
cols_to_keep (list of strings): col ids to be kept | [
"Figure",
"out",
"based",
"on",
"the",
"possible",
"columns",
"inputs",
"which",
"columns",
"to",
"keep",
"."
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/subset_gctoo.py#L129-L188 |
18,543 | cmap/cmapPy | cmapPy/set_io/grp.py | read | def read(in_path):
""" Read a grp file at the path specified by in_path.
Args:
in_path (string): path to GRP file
Returns:
grp (list)
"""
assert os.path.exists(in_path), "The following GRP file can't be found. in_path: {}".format(in_path)
with open(in_path, "r") as f:
lines = f.readlines()
# need the second conditional to ignore comment lines
grp = [line.strip() for line in lines if line and not re.match("^#", line)]
return grp | python | def read(in_path):
assert os.path.exists(in_path), "The following GRP file can't be found. in_path: {}".format(in_path)
with open(in_path, "r") as f:
lines = f.readlines()
# need the second conditional to ignore comment lines
grp = [line.strip() for line in lines if line and not re.match("^#", line)]
return grp | [
"def",
"read",
"(",
"in_path",
")",
":",
"assert",
"os",
".",
"path",
".",
"exists",
"(",
"in_path",
")",
",",
"\"The following GRP file can't be found. in_path: {}\"",
".",
"format",
"(",
"in_path",
")",
"with",
"open",
"(",
"in_path",
",",
"\"r\"",
")",
"a... | Read a grp file at the path specified by in_path.
Args:
in_path (string): path to GRP file
Returns:
grp (list) | [
"Read",
"a",
"grp",
"file",
"at",
"the",
"path",
"specified",
"by",
"in_path",
"."
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/set_io/grp.py#L16-L33 |
18,544 | cmap/cmapPy | cmapPy/set_io/grp.py | write | def write(grp, out_path):
""" Write a GRP to a text file.
Args:
grp (list): GRP object to write to new-line delimited text file
out_path (string): output path
Returns:
None
"""
with open(out_path, "w") as f:
for x in grp:
f.write(str(x) + "\n") | python | def write(grp, out_path):
with open(out_path, "w") as f:
for x in grp:
f.write(str(x) + "\n") | [
"def",
"write",
"(",
"grp",
",",
"out_path",
")",
":",
"with",
"open",
"(",
"out_path",
",",
"\"w\"",
")",
"as",
"f",
":",
"for",
"x",
"in",
"grp",
":",
"f",
".",
"write",
"(",
"str",
"(",
"x",
")",
"+",
"\"\\n\"",
")"
] | Write a GRP to a text file.
Args:
grp (list): GRP object to write to new-line delimited text file
out_path (string): output path
Returns:
None | [
"Write",
"a",
"GRP",
"to",
"a",
"text",
"file",
"."
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/set_io/grp.py#L36-L49 |
18,545 | cmap/cmapPy | cmapPy/pandasGEXpress/random_slice.py | make_specified_size_gctoo | def make_specified_size_gctoo(og_gctoo, num_entries, dim):
"""
Subsets a GCToo instance along either rows or columns to obtain a specified size.
Input:
- og_gctoo (GCToo): a GCToo instance
- num_entries (int): the number of entries to keep
- dim (str): the dimension along which to subset. Must be "row" or "col"
Output:
- new_gctoo (GCToo): the GCToo instance subsetted as specified.
"""
assert dim in ["row", "col"], "dim specified must be either 'row' or 'col'"
dim_index = 0 if "row" == dim else 1
assert num_entries <= og_gctoo.data_df.shape[dim_index], ("number of entries must be smaller than dimension being "
"subsetted - num_entries: {} dim: {} dim_index: {} og_gctoo.data_df.shape[dim_index]: {}".format(
num_entries, dim, dim_index, og_gctoo.data_df.shape[dim_index]))
if dim == "col":
columns = [x for x in og_gctoo.data_df.columns.values]
numpy.random.shuffle(columns)
columns = columns[0:num_entries]
rows = og_gctoo.data_df.index.values
else:
rows = [x for x in og_gctoo.data_df.index.values]
numpy.random.shuffle(rows)
rows = rows[0:num_entries]
columns = og_gctoo.data_df.columns.values
new_data_df = og_gctoo.data_df.loc[rows, columns]
new_row_meta = og_gctoo.row_metadata_df.loc[rows]
new_col_meta = og_gctoo.col_metadata_df.loc[columns]
logger.debug(
"after slice - new_col_meta.shape: {} new_row_meta.shape: {}".format(new_col_meta.shape, new_row_meta.shape))
# make & return new gctoo instance
new_gctoo = GCToo.GCToo(data_df=new_data_df, row_metadata_df=new_row_meta, col_metadata_df=new_col_meta)
return new_gctoo | python | def make_specified_size_gctoo(og_gctoo, num_entries, dim):
assert dim in ["row", "col"], "dim specified must be either 'row' or 'col'"
dim_index = 0 if "row" == dim else 1
assert num_entries <= og_gctoo.data_df.shape[dim_index], ("number of entries must be smaller than dimension being "
"subsetted - num_entries: {} dim: {} dim_index: {} og_gctoo.data_df.shape[dim_index]: {}".format(
num_entries, dim, dim_index, og_gctoo.data_df.shape[dim_index]))
if dim == "col":
columns = [x for x in og_gctoo.data_df.columns.values]
numpy.random.shuffle(columns)
columns = columns[0:num_entries]
rows = og_gctoo.data_df.index.values
else:
rows = [x for x in og_gctoo.data_df.index.values]
numpy.random.shuffle(rows)
rows = rows[0:num_entries]
columns = og_gctoo.data_df.columns.values
new_data_df = og_gctoo.data_df.loc[rows, columns]
new_row_meta = og_gctoo.row_metadata_df.loc[rows]
new_col_meta = og_gctoo.col_metadata_df.loc[columns]
logger.debug(
"after slice - new_col_meta.shape: {} new_row_meta.shape: {}".format(new_col_meta.shape, new_row_meta.shape))
# make & return new gctoo instance
new_gctoo = GCToo.GCToo(data_df=new_data_df, row_metadata_df=new_row_meta, col_metadata_df=new_col_meta)
return new_gctoo | [
"def",
"make_specified_size_gctoo",
"(",
"og_gctoo",
",",
"num_entries",
",",
"dim",
")",
":",
"assert",
"dim",
"in",
"[",
"\"row\"",
",",
"\"col\"",
"]",
",",
"\"dim specified must be either 'row' or 'col'\"",
"dim_index",
"=",
"0",
"if",
"\"row\"",
"==",
"dim",
... | Subsets a GCToo instance along either rows or columns to obtain a specified size.
Input:
- og_gctoo (GCToo): a GCToo instance
- num_entries (int): the number of entries to keep
- dim (str): the dimension along which to subset. Must be "row" or "col"
Output:
- new_gctoo (GCToo): the GCToo instance subsetted as specified. | [
"Subsets",
"a",
"GCToo",
"instance",
"along",
"either",
"rows",
"or",
"columns",
"to",
"obtain",
"a",
"specified",
"size",
"."
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/random_slice.py#L15-L55 |
18,546 | cmap/cmapPy | cmapPy/pandasGEXpress/write_gctx.py | write | def write(gctoo_object, out_file_name, convert_back_to_neg_666=True, gzip_compression_level=6,
max_chunk_kb=1024, matrix_dtype=numpy.float32):
"""
Writes a GCToo instance to specified file.
Input:
- gctoo_object (GCToo): A GCToo instance.
- out_file_name (str): file name to write gctoo_object to.
- convert_back_to_neg_666 (bool): whether to convert np.NAN in metadata back to "-666"
- gzip_compression_level (int, default=6): Compression level to use for metadata.
- max_chunk_kb (int, default=1024): The maximum number of KB a given chunk will occupy
- matrix_dtype (numpy dtype, default=numpy.float32): Storage data type for data matrix.
"""
# make sure out file has a .gctx suffix
gctx_out_name = add_gctx_to_out_name(out_file_name)
# open an hdf5 file to write to
hdf5_out = h5py.File(gctx_out_name, "w")
# write version
write_version(hdf5_out)
# write src
write_src(hdf5_out, gctoo_object, gctx_out_name)
# set chunk size for data matrix
elem_per_kb = calculate_elem_per_kb(max_chunk_kb, matrix_dtype)
chunk_size = set_data_matrix_chunk_size(gctoo_object.data_df.shape, max_chunk_kb, elem_per_kb)
# write data matrix
hdf5_out.create_dataset(data_matrix_node, data=gctoo_object.data_df.transpose().values,
dtype=matrix_dtype)
# write col metadata
write_metadata(hdf5_out, "col", gctoo_object.col_metadata_df, convert_back_to_neg_666,
gzip_compression=gzip_compression_level)
# write row metadata
write_metadata(hdf5_out, "row", gctoo_object.row_metadata_df, convert_back_to_neg_666,
gzip_compression=gzip_compression_level)
# close gctx file
hdf5_out.close() | python | def write(gctoo_object, out_file_name, convert_back_to_neg_666=True, gzip_compression_level=6,
max_chunk_kb=1024, matrix_dtype=numpy.float32):
# make sure out file has a .gctx suffix
gctx_out_name = add_gctx_to_out_name(out_file_name)
# open an hdf5 file to write to
hdf5_out = h5py.File(gctx_out_name, "w")
# write version
write_version(hdf5_out)
# write src
write_src(hdf5_out, gctoo_object, gctx_out_name)
# set chunk size for data matrix
elem_per_kb = calculate_elem_per_kb(max_chunk_kb, matrix_dtype)
chunk_size = set_data_matrix_chunk_size(gctoo_object.data_df.shape, max_chunk_kb, elem_per_kb)
# write data matrix
hdf5_out.create_dataset(data_matrix_node, data=gctoo_object.data_df.transpose().values,
dtype=matrix_dtype)
# write col metadata
write_metadata(hdf5_out, "col", gctoo_object.col_metadata_df, convert_back_to_neg_666,
gzip_compression=gzip_compression_level)
# write row metadata
write_metadata(hdf5_out, "row", gctoo_object.row_metadata_df, convert_back_to_neg_666,
gzip_compression=gzip_compression_level)
# close gctx file
hdf5_out.close() | [
"def",
"write",
"(",
"gctoo_object",
",",
"out_file_name",
",",
"convert_back_to_neg_666",
"=",
"True",
",",
"gzip_compression_level",
"=",
"6",
",",
"max_chunk_kb",
"=",
"1024",
",",
"matrix_dtype",
"=",
"numpy",
".",
"float32",
")",
":",
"# make sure out file ha... | Writes a GCToo instance to specified file.
Input:
- gctoo_object (GCToo): A GCToo instance.
- out_file_name (str): file name to write gctoo_object to.
- convert_back_to_neg_666 (bool): whether to convert np.NAN in metadata back to "-666"
- gzip_compression_level (int, default=6): Compression level to use for metadata.
- max_chunk_kb (int, default=1024): The maximum number of KB a given chunk will occupy
- matrix_dtype (numpy dtype, default=numpy.float32): Storage data type for data matrix. | [
"Writes",
"a",
"GCToo",
"instance",
"to",
"specified",
"file",
"."
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/write_gctx.py#L19-L61 |
18,547 | cmap/cmapPy | cmapPy/pandasGEXpress/write_gctx.py | write_src | def write_src(hdf5_out, gctoo_object, out_file_name):
"""
Writes src as attribute of gctx out file.
Input:
- hdf5_out (h5py): hdf5 file to write to
- gctoo_object (GCToo): GCToo instance to be written to .gctx
- out_file_name (str): name of hdf5 out file.
"""
if gctoo_object.src == None:
hdf5_out.attrs[src_attr] = out_file_name
else:
hdf5_out.attrs[src_attr] = gctoo_object.src | python | def write_src(hdf5_out, gctoo_object, out_file_name):
if gctoo_object.src == None:
hdf5_out.attrs[src_attr] = out_file_name
else:
hdf5_out.attrs[src_attr] = gctoo_object.src | [
"def",
"write_src",
"(",
"hdf5_out",
",",
"gctoo_object",
",",
"out_file_name",
")",
":",
"if",
"gctoo_object",
".",
"src",
"==",
"None",
":",
"hdf5_out",
".",
"attrs",
"[",
"src_attr",
"]",
"=",
"out_file_name",
"else",
":",
"hdf5_out",
".",
"attrs",
"[",... | Writes src as attribute of gctx out file.
Input:
- hdf5_out (h5py): hdf5 file to write to
- gctoo_object (GCToo): GCToo instance to be written to .gctx
- out_file_name (str): name of hdf5 out file. | [
"Writes",
"src",
"as",
"attribute",
"of",
"gctx",
"out",
"file",
"."
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/write_gctx.py#L80-L92 |
18,548 | cmap/cmapPy | cmapPy/pandasGEXpress/write_gctx.py | calculate_elem_per_kb | def calculate_elem_per_kb(max_chunk_kb, matrix_dtype):
"""
Calculates the number of elem per kb depending on the max chunk size set.
Input:
- max_chunk_kb (int, default=1024): The maximum number of KB a given chunk will occupy
- matrix_dtype (numpy dtype, default=numpy.float32): Storage data type for data matrix.
Currently needs to be np.float32 or np.float64 (TODO: figure out a better way to get bits from a numpy dtype).
Returns:
elem_per_kb (int), the number of elements per kb for matrix dtype specified.
"""
if matrix_dtype == numpy.float32:
return (max_chunk_kb * 8)/32
elif matrix_dtype == numpy.float64:
return (max_chunk_kb * 8)/64
else:
msg = "Invalid matrix_dtype: {}; only numpy.float32 and numpy.float64 are currently supported".format(matrix_dtype)
logger.error(msg)
raise Exception("write_gctx.calculate_elem_per_kb " + msg) | python | def calculate_elem_per_kb(max_chunk_kb, matrix_dtype):
if matrix_dtype == numpy.float32:
return (max_chunk_kb * 8)/32
elif matrix_dtype == numpy.float64:
return (max_chunk_kb * 8)/64
else:
msg = "Invalid matrix_dtype: {}; only numpy.float32 and numpy.float64 are currently supported".format(matrix_dtype)
logger.error(msg)
raise Exception("write_gctx.calculate_elem_per_kb " + msg) | [
"def",
"calculate_elem_per_kb",
"(",
"max_chunk_kb",
",",
"matrix_dtype",
")",
":",
"if",
"matrix_dtype",
"==",
"numpy",
".",
"float32",
":",
"return",
"(",
"max_chunk_kb",
"*",
"8",
")",
"/",
"32",
"elif",
"matrix_dtype",
"==",
"numpy",
".",
"float64",
":",... | Calculates the number of elem per kb depending on the max chunk size set.
Input:
- max_chunk_kb (int, default=1024): The maximum number of KB a given chunk will occupy
- matrix_dtype (numpy dtype, default=numpy.float32): Storage data type for data matrix.
Currently needs to be np.float32 or np.float64 (TODO: figure out a better way to get bits from a numpy dtype).
Returns:
elem_per_kb (int), the number of elements per kb for matrix dtype specified. | [
"Calculates",
"the",
"number",
"of",
"elem",
"per",
"kb",
"depending",
"on",
"the",
"max",
"chunk",
"size",
"set",
"."
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/write_gctx.py#L104-L123 |
18,549 | cmap/cmapPy | cmapPy/pandasGEXpress/write_gctx.py | set_data_matrix_chunk_size | def set_data_matrix_chunk_size(df_shape, max_chunk_kb, elem_per_kb):
"""
Sets chunk size to use for writing data matrix.
Note. Calculation used here is for compatibility with cmapM and cmapR.
Input:
- df_shape (tuple): shape of input data_df.
- max_chunk_kb (int, default=1024): The maximum number of KB a given chunk will occupy
- elem_per_kb (int): Number of elements per kb
Returns:
chunk size (tuple) to use for chunking the data matrix
"""
row_chunk_size = min(df_shape[0], 1000)
col_chunk_size = min(((max_chunk_kb*elem_per_kb)//row_chunk_size), df_shape[1])
return (row_chunk_size, col_chunk_size) | python | def set_data_matrix_chunk_size(df_shape, max_chunk_kb, elem_per_kb):
row_chunk_size = min(df_shape[0], 1000)
col_chunk_size = min(((max_chunk_kb*elem_per_kb)//row_chunk_size), df_shape[1])
return (row_chunk_size, col_chunk_size) | [
"def",
"set_data_matrix_chunk_size",
"(",
"df_shape",
",",
"max_chunk_kb",
",",
"elem_per_kb",
")",
":",
"row_chunk_size",
"=",
"min",
"(",
"df_shape",
"[",
"0",
"]",
",",
"1000",
")",
"col_chunk_size",
"=",
"min",
"(",
"(",
"(",
"max_chunk_kb",
"*",
"elem_p... | Sets chunk size to use for writing data matrix.
Note. Calculation used here is for compatibility with cmapM and cmapR.
Input:
- df_shape (tuple): shape of input data_df.
- max_chunk_kb (int, default=1024): The maximum number of KB a given chunk will occupy
- elem_per_kb (int): Number of elements per kb
Returns:
chunk size (tuple) to use for chunking the data matrix | [
"Sets",
"chunk",
"size",
"to",
"use",
"for",
"writing",
"data",
"matrix",
".",
"Note",
".",
"Calculation",
"used",
"here",
"is",
"for",
"compatibility",
"with",
"cmapM",
"and",
"cmapR",
"."
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/write_gctx.py#L126-L141 |
18,550 | danfairs/django-lazysignup | lazysignup/models.py | LazyUserManager.convert | def convert(self, form):
""" Convert a lazy user to a non-lazy one. The form passed
in is expected to be a ModelForm instance, bound to the user
to be converted.
The converted ``User`` object is returned.
Raises a TypeError if the user is not lazy.
"""
if not is_lazy_user(form.instance):
raise NotLazyError('You cannot convert a non-lazy user')
user = form.save()
# We need to remove the LazyUser instance assocated with the
# newly-converted user
self.filter(user=user).delete()
converted.send(self, user=user)
return user | python | def convert(self, form):
if not is_lazy_user(form.instance):
raise NotLazyError('You cannot convert a non-lazy user')
user = form.save()
# We need to remove the LazyUser instance assocated with the
# newly-converted user
self.filter(user=user).delete()
converted.send(self, user=user)
return user | [
"def",
"convert",
"(",
"self",
",",
"form",
")",
":",
"if",
"not",
"is_lazy_user",
"(",
"form",
".",
"instance",
")",
":",
"raise",
"NotLazyError",
"(",
"'You cannot convert a non-lazy user'",
")",
"user",
"=",
"form",
".",
"save",
"(",
")",
"# We need to re... | Convert a lazy user to a non-lazy one. The form passed
in is expected to be a ModelForm instance, bound to the user
to be converted.
The converted ``User`` object is returned.
Raises a TypeError if the user is not lazy. | [
"Convert",
"a",
"lazy",
"user",
"to",
"a",
"non",
"-",
"lazy",
"one",
".",
"The",
"form",
"passed",
"in",
"is",
"expected",
"to",
"be",
"a",
"ModelForm",
"instance",
"bound",
"to",
"the",
"user",
"to",
"be",
"converted",
"."
] | cfe77e12976d439e1a5aae4387531b2f0f835c6a | https://github.com/danfairs/django-lazysignup/blob/cfe77e12976d439e1a5aae4387531b2f0f835c6a/lazysignup/models.py#L47-L65 |
18,551 | danfairs/django-lazysignup | lazysignup/models.py | LazyUserManager.generate_username | def generate_username(self, user_class):
""" Generate a new username for a user
"""
m = getattr(user_class, 'generate_username', None)
if m:
return m()
else:
max_length = user_class._meta.get_field(
self.username_field).max_length
return uuid.uuid4().hex[:max_length] | python | def generate_username(self, user_class):
m = getattr(user_class, 'generate_username', None)
if m:
return m()
else:
max_length = user_class._meta.get_field(
self.username_field).max_length
return uuid.uuid4().hex[:max_length] | [
"def",
"generate_username",
"(",
"self",
",",
"user_class",
")",
":",
"m",
"=",
"getattr",
"(",
"user_class",
",",
"'generate_username'",
",",
"None",
")",
"if",
"m",
":",
"return",
"m",
"(",
")",
"else",
":",
"max_length",
"=",
"user_class",
".",
"_meta... | Generate a new username for a user | [
"Generate",
"a",
"new",
"username",
"for",
"a",
"user"
] | cfe77e12976d439e1a5aae4387531b2f0f835c6a | https://github.com/danfairs/django-lazysignup/blob/cfe77e12976d439e1a5aae4387531b2f0f835c6a/lazysignup/models.py#L67-L76 |
18,552 | danfairs/django-lazysignup | lazysignup/utils.py | is_lazy_user | def is_lazy_user(user):
""" Return True if the passed user is a lazy user. """
# Anonymous users are not lazy.
if user.is_anonymous:
return False
# Check the user backend. If the lazy signup backend
# authenticated them, then the user is lazy.
backend = getattr(user, 'backend', None)
if backend == 'lazysignup.backends.LazySignupBackend':
return True
# Otherwise, we have to fall back to checking the database.
from lazysignup.models import LazyUser
return bool(LazyUser.objects.filter(user=user).count() > 0) | python | def is_lazy_user(user):
# Anonymous users are not lazy.
if user.is_anonymous:
return False
# Check the user backend. If the lazy signup backend
# authenticated them, then the user is lazy.
backend = getattr(user, 'backend', None)
if backend == 'lazysignup.backends.LazySignupBackend':
return True
# Otherwise, we have to fall back to checking the database.
from lazysignup.models import LazyUser
return bool(LazyUser.objects.filter(user=user).count() > 0) | [
"def",
"is_lazy_user",
"(",
"user",
")",
":",
"# Anonymous users are not lazy.",
"if",
"user",
".",
"is_anonymous",
":",
"return",
"False",
"# Check the user backend. If the lazy signup backend",
"# authenticated them, then the user is lazy.",
"backend",
"=",
"getattr",
"(",
... | Return True if the passed user is a lazy user. | [
"Return",
"True",
"if",
"the",
"passed",
"user",
"is",
"a",
"lazy",
"user",
"."
] | cfe77e12976d439e1a5aae4387531b2f0f835c6a | https://github.com/danfairs/django-lazysignup/blob/cfe77e12976d439e1a5aae4387531b2f0f835c6a/lazysignup/utils.py#L1-L16 |
18,553 | bslatkin/dpxdt | dpxdt/server/work_queue.py | add | def add(queue_name, payload=None, content_type=None, source=None, task_id=None,
build_id=None, release_id=None, run_id=None):
"""Adds a work item to a queue.
Args:
queue_name: Name of the queue to add the work item to.
payload: Optional. Payload that describes the work to do as a string.
If not a string and content_type is not provided, then this
function assumes the payload is a JSON-able Python object.
content_type: Optional. Content type of the payload.
source: Optional. Who or what originally created the task.
task_id: Optional. When supplied, only enqueue this task if a task
with this ID does not already exist. If a task with this ID already
exists, then this function will do nothing.
build_id: Build ID to associate with this task. May be None.
release_id: Release ID to associate with this task. May be None.
run_id: Run ID to associate with this task. May be None.
Returns:
ID of the task that was added.
"""
if task_id:
task = WorkQueue.query.filter_by(task_id=task_id).first()
if task:
return task.task_id
else:
task_id = uuid.uuid4().hex
if payload and not content_type and not isinstance(payload, basestring):
payload = json.dumps(payload)
content_type = 'application/json'
now = datetime.datetime.utcnow()
task = WorkQueue(
task_id=task_id,
queue_name=queue_name,
eta=now,
source=source,
build_id=build_id,
release_id=release_id,
run_id=run_id,
payload=payload,
content_type=content_type)
db.session.add(task)
return task.task_id | python | def add(queue_name, payload=None, content_type=None, source=None, task_id=None,
build_id=None, release_id=None, run_id=None):
if task_id:
task = WorkQueue.query.filter_by(task_id=task_id).first()
if task:
return task.task_id
else:
task_id = uuid.uuid4().hex
if payload and not content_type and not isinstance(payload, basestring):
payload = json.dumps(payload)
content_type = 'application/json'
now = datetime.datetime.utcnow()
task = WorkQueue(
task_id=task_id,
queue_name=queue_name,
eta=now,
source=source,
build_id=build_id,
release_id=release_id,
run_id=run_id,
payload=payload,
content_type=content_type)
db.session.add(task)
return task.task_id | [
"def",
"add",
"(",
"queue_name",
",",
"payload",
"=",
"None",
",",
"content_type",
"=",
"None",
",",
"source",
"=",
"None",
",",
"task_id",
"=",
"None",
",",
"build_id",
"=",
"None",
",",
"release_id",
"=",
"None",
",",
"run_id",
"=",
"None",
")",
":... | Adds a work item to a queue.
Args:
queue_name: Name of the queue to add the work item to.
payload: Optional. Payload that describes the work to do as a string.
If not a string and content_type is not provided, then this
function assumes the payload is a JSON-able Python object.
content_type: Optional. Content type of the payload.
source: Optional. Who or what originally created the task.
task_id: Optional. When supplied, only enqueue this task if a task
with this ID does not already exist. If a task with this ID already
exists, then this function will do nothing.
build_id: Build ID to associate with this task. May be None.
release_id: Release ID to associate with this task. May be None.
run_id: Run ID to associate with this task. May be None.
Returns:
ID of the task that was added. | [
"Adds",
"a",
"work",
"item",
"to",
"a",
"queue",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/work_queue.py#L100-L145 |
18,554 | bslatkin/dpxdt | dpxdt/server/work_queue.py | _task_to_dict | def _task_to_dict(task):
"""Converts a WorkQueue to a JSON-able dictionary."""
payload = task.payload
if payload and task.content_type == 'application/json':
payload = json.loads(payload)
return dict(
task_id=task.task_id,
queue_name=task.queue_name,
eta=_datetime_to_epoch_seconds(task.eta),
source=task.source,
created=_datetime_to_epoch_seconds(task.created),
lease_attempts=task.lease_attempts,
last_lease=_datetime_to_epoch_seconds(task.last_lease),
payload=payload,
content_type=task.content_type) | python | def _task_to_dict(task):
payload = task.payload
if payload and task.content_type == 'application/json':
payload = json.loads(payload)
return dict(
task_id=task.task_id,
queue_name=task.queue_name,
eta=_datetime_to_epoch_seconds(task.eta),
source=task.source,
created=_datetime_to_epoch_seconds(task.created),
lease_attempts=task.lease_attempts,
last_lease=_datetime_to_epoch_seconds(task.last_lease),
payload=payload,
content_type=task.content_type) | [
"def",
"_task_to_dict",
"(",
"task",
")",
":",
"payload",
"=",
"task",
".",
"payload",
"if",
"payload",
"and",
"task",
".",
"content_type",
"==",
"'application/json'",
":",
"payload",
"=",
"json",
".",
"loads",
"(",
"payload",
")",
"return",
"dict",
"(",
... | Converts a WorkQueue to a JSON-able dictionary. | [
"Converts",
"a",
"WorkQueue",
"to",
"a",
"JSON",
"-",
"able",
"dictionary",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/work_queue.py#L155-L170 |
18,555 | bslatkin/dpxdt | dpxdt/server/work_queue.py | lease | def lease(queue_name, owner, count=1, timeout_seconds=60):
"""Leases a work item from a queue, usually the oldest task available.
Args:
queue_name: Name of the queue to lease work from.
owner: Who or what is leasing the task.
count: Lease up to this many tasks. Return value will never have more
than this many items present.
timeout_seconds: Number of seconds to lock the task for before
allowing another owner to lease it.
Returns:
List of dictionaries representing the task that was leased, or
an empty list if no tasks are available to be leased.
"""
now = datetime.datetime.utcnow()
query = (
WorkQueue.query
.filter_by(queue_name=queue_name, status=WorkQueue.LIVE)
.filter(WorkQueue.eta <= now)
.order_by(WorkQueue.eta)
.with_lockmode('update')
.limit(count))
task_list = query.all()
if not task_list:
return None
next_eta = now + datetime.timedelta(seconds=timeout_seconds)
for task in task_list:
task.eta = next_eta
task.lease_attempts += 1
task.last_owner = owner
task.last_lease = now
task.heartbeat = None
task.heartbeat_number = 0
db.session.add(task)
return [_task_to_dict(task) for task in task_list] | python | def lease(queue_name, owner, count=1, timeout_seconds=60):
now = datetime.datetime.utcnow()
query = (
WorkQueue.query
.filter_by(queue_name=queue_name, status=WorkQueue.LIVE)
.filter(WorkQueue.eta <= now)
.order_by(WorkQueue.eta)
.with_lockmode('update')
.limit(count))
task_list = query.all()
if not task_list:
return None
next_eta = now + datetime.timedelta(seconds=timeout_seconds)
for task in task_list:
task.eta = next_eta
task.lease_attempts += 1
task.last_owner = owner
task.last_lease = now
task.heartbeat = None
task.heartbeat_number = 0
db.session.add(task)
return [_task_to_dict(task) for task in task_list] | [
"def",
"lease",
"(",
"queue_name",
",",
"owner",
",",
"count",
"=",
"1",
",",
"timeout_seconds",
"=",
"60",
")",
":",
"now",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"query",
"=",
"(",
"WorkQueue",
".",
"query",
".",
"filter_by",
"(... | Leases a work item from a queue, usually the oldest task available.
Args:
queue_name: Name of the queue to lease work from.
owner: Who or what is leasing the task.
count: Lease up to this many tasks. Return value will never have more
than this many items present.
timeout_seconds: Number of seconds to lock the task for before
allowing another owner to lease it.
Returns:
List of dictionaries representing the task that was leased, or
an empty list if no tasks are available to be leased. | [
"Leases",
"a",
"work",
"item",
"from",
"a",
"queue",
"usually",
"the",
"oldest",
"task",
"available",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/work_queue.py#L177-L216 |
18,556 | bslatkin/dpxdt | dpxdt/server/work_queue.py | _get_task_with_policy | def _get_task_with_policy(queue_name, task_id, owner):
"""Fetches the specified task and enforces ownership policy.
Args:
queue_name: Name of the queue the work item is on.
task_id: ID of the task that is finished.
owner: Who or what has the current lease on the task.
Returns:
The valid WorkQueue task that is currently owned.
Raises:
TaskDoesNotExistError if the task does not exist.
LeaseExpiredError if the lease is no longer active.
NotOwnerError if the specified owner no longer owns the task.
"""
now = datetime.datetime.utcnow()
task = (
WorkQueue.query
.filter_by(queue_name=queue_name, task_id=task_id)
.with_lockmode('update')
.first())
if not task:
raise TaskDoesNotExistError('task_id=%r' % task_id)
# Lease delta should be positive, meaning it has not yet expired!
lease_delta = now - task.eta
if lease_delta > datetime.timedelta(0):
db.session.rollback()
raise LeaseExpiredError('queue=%r, task_id=%r expired %s' % (
task.queue_name, task_id, lease_delta))
if task.last_owner != owner:
db.session.rollback()
raise NotOwnerError('queue=%r, task_id=%r, owner=%r' % (
task.queue_name, task_id, task.last_owner))
return task | python | def _get_task_with_policy(queue_name, task_id, owner):
now = datetime.datetime.utcnow()
task = (
WorkQueue.query
.filter_by(queue_name=queue_name, task_id=task_id)
.with_lockmode('update')
.first())
if not task:
raise TaskDoesNotExistError('task_id=%r' % task_id)
# Lease delta should be positive, meaning it has not yet expired!
lease_delta = now - task.eta
if lease_delta > datetime.timedelta(0):
db.session.rollback()
raise LeaseExpiredError('queue=%r, task_id=%r expired %s' % (
task.queue_name, task_id, lease_delta))
if task.last_owner != owner:
db.session.rollback()
raise NotOwnerError('queue=%r, task_id=%r, owner=%r' % (
task.queue_name, task_id, task.last_owner))
return task | [
"def",
"_get_task_with_policy",
"(",
"queue_name",
",",
"task_id",
",",
"owner",
")",
":",
"now",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"task",
"=",
"(",
"WorkQueue",
".",
"query",
".",
"filter_by",
"(",
"queue_name",
"=",
"queue_name"... | Fetches the specified task and enforces ownership policy.
Args:
queue_name: Name of the queue the work item is on.
task_id: ID of the task that is finished.
owner: Who or what has the current lease on the task.
Returns:
The valid WorkQueue task that is currently owned.
Raises:
TaskDoesNotExistError if the task does not exist.
LeaseExpiredError if the lease is no longer active.
NotOwnerError if the specified owner no longer owns the task. | [
"Fetches",
"the",
"specified",
"task",
"and",
"enforces",
"ownership",
"policy",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/work_queue.py#L219-L256 |
18,557 | bslatkin/dpxdt | dpxdt/server/work_queue.py | heartbeat | def heartbeat(queue_name, task_id, owner, message, index):
"""Sets the heartbeat status of the task and extends its lease.
The task's lease is extended by the same amount as its last lease to
ensure that any operations following the heartbeat will still hold the
lock for the original lock period.
Args:
queue_name: Name of the queue the work item is on.
task_id: ID of the task that is finished.
owner: Who or what has the current lease on the task.
message: Message to report as the task's current status.
index: Number of this message in the sequence of messages from the
current task owner, starting at zero. This lets the API receive
heartbeats out of order, yet ensure that the most recent message
is actually saved to the database. This requires the owner issuing
heartbeat messages to issue heartbeat indexes sequentially.
Returns:
True if the heartbeat message was set, False if it is lower than the
current heartbeat index.
Raises:
TaskDoesNotExistError if the task does not exist.
LeaseExpiredError if the lease is no longer active.
NotOwnerError if the specified owner no longer owns the task.
"""
task = _get_task_with_policy(queue_name, task_id, owner)
if task.heartbeat_number > index:
return False
task.heartbeat = message
task.heartbeat_number = index
# Extend the lease by the time of the last lease.
now = datetime.datetime.utcnow()
timeout_delta = task.eta - task.last_lease
task.eta = now + timeout_delta
task.last_lease = now
db.session.add(task)
signals.task_updated.send(app, task=task)
return True | python | def heartbeat(queue_name, task_id, owner, message, index):
task = _get_task_with_policy(queue_name, task_id, owner)
if task.heartbeat_number > index:
return False
task.heartbeat = message
task.heartbeat_number = index
# Extend the lease by the time of the last lease.
now = datetime.datetime.utcnow()
timeout_delta = task.eta - task.last_lease
task.eta = now + timeout_delta
task.last_lease = now
db.session.add(task)
signals.task_updated.send(app, task=task)
return True | [
"def",
"heartbeat",
"(",
"queue_name",
",",
"task_id",
",",
"owner",
",",
"message",
",",
"index",
")",
":",
"task",
"=",
"_get_task_with_policy",
"(",
"queue_name",
",",
"task_id",
",",
"owner",
")",
"if",
"task",
".",
"heartbeat_number",
">",
"index",
":... | Sets the heartbeat status of the task and extends its lease.
The task's lease is extended by the same amount as its last lease to
ensure that any operations following the heartbeat will still hold the
lock for the original lock period.
Args:
queue_name: Name of the queue the work item is on.
task_id: ID of the task that is finished.
owner: Who or what has the current lease on the task.
message: Message to report as the task's current status.
index: Number of this message in the sequence of messages from the
current task owner, starting at zero. This lets the API receive
heartbeats out of order, yet ensure that the most recent message
is actually saved to the database. This requires the owner issuing
heartbeat messages to issue heartbeat indexes sequentially.
Returns:
True if the heartbeat message was set, False if it is lower than the
current heartbeat index.
Raises:
TaskDoesNotExistError if the task does not exist.
LeaseExpiredError if the lease is no longer active.
NotOwnerError if the specified owner no longer owns the task. | [
"Sets",
"the",
"heartbeat",
"status",
"of",
"the",
"task",
"and",
"extends",
"its",
"lease",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/work_queue.py#L259-L303 |
18,558 | bslatkin/dpxdt | dpxdt/server/work_queue.py | finish | def finish(queue_name, task_id, owner, error=False):
"""Marks a work item on a queue as finished.
Args:
queue_name: Name of the queue the work item is on.
task_id: ID of the task that is finished.
owner: Who or what has the current lease on the task.
error: Defaults to false. True if this task's final state is an error.
Returns:
True if the task has been finished for the first time; False if the
task was already finished.
Raises:
TaskDoesNotExistError if the task does not exist.
LeaseExpiredError if the lease is no longer active.
NotOwnerError if the specified owner no longer owns the task.
"""
task = _get_task_with_policy(queue_name, task_id, owner)
if not task.status == WorkQueue.LIVE:
logging.warning('Finishing already dead task. queue=%r, task_id=%r, '
'owner=%r, status=%r',
task.queue_name, task_id, owner, task.status)
return False
if not error:
task.status = WorkQueue.DONE
else:
task.status = WorkQueue.ERROR
task.finished = datetime.datetime.utcnow()
db.session.add(task)
signals.task_updated.send(app, task=task)
return True | python | def finish(queue_name, task_id, owner, error=False):
task = _get_task_with_policy(queue_name, task_id, owner)
if not task.status == WorkQueue.LIVE:
logging.warning('Finishing already dead task. queue=%r, task_id=%r, '
'owner=%r, status=%r',
task.queue_name, task_id, owner, task.status)
return False
if not error:
task.status = WorkQueue.DONE
else:
task.status = WorkQueue.ERROR
task.finished = datetime.datetime.utcnow()
db.session.add(task)
signals.task_updated.send(app, task=task)
return True | [
"def",
"finish",
"(",
"queue_name",
",",
"task_id",
",",
"owner",
",",
"error",
"=",
"False",
")",
":",
"task",
"=",
"_get_task_with_policy",
"(",
"queue_name",
",",
"task_id",
",",
"owner",
")",
"if",
"not",
"task",
".",
"status",
"==",
"WorkQueue",
"."... | Marks a work item on a queue as finished.
Args:
queue_name: Name of the queue the work item is on.
task_id: ID of the task that is finished.
owner: Who or what has the current lease on the task.
error: Defaults to false. True if this task's final state is an error.
Returns:
True if the task has been finished for the first time; False if the
task was already finished.
Raises:
TaskDoesNotExistError if the task does not exist.
LeaseExpiredError if the lease is no longer active.
NotOwnerError if the specified owner no longer owns the task. | [
"Marks",
"a",
"work",
"item",
"on",
"a",
"queue",
"as",
"finished",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/work_queue.py#L306-L342 |
18,559 | bslatkin/dpxdt | dpxdt/server/work_queue.py | cancel | def cancel(**kwargs):
"""Cancels work items based on their criteria.
Args:
**kwargs: Same parameters as the query() method.
Returns:
The number of tasks that were canceled.
"""
task_list = _query(**kwargs)
for task in task_list:
task.status = WorkQueue.CANCELED
task.finished = datetime.datetime.utcnow()
db.session.add(task)
return len(task_list) | python | def cancel(**kwargs):
task_list = _query(**kwargs)
for task in task_list:
task.status = WorkQueue.CANCELED
task.finished = datetime.datetime.utcnow()
db.session.add(task)
return len(task_list) | [
"def",
"cancel",
"(",
"*",
"*",
"kwargs",
")",
":",
"task_list",
"=",
"_query",
"(",
"*",
"*",
"kwargs",
")",
"for",
"task",
"in",
"task_list",
":",
"task",
".",
"status",
"=",
"WorkQueue",
".",
"CANCELED",
"task",
".",
"finished",
"=",
"datetime",
"... | Cancels work items based on their criteria.
Args:
**kwargs: Same parameters as the query() method.
Returns:
The number of tasks that were canceled. | [
"Cancels",
"work",
"items",
"based",
"on",
"their",
"criteria",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/work_queue.py#L410-L424 |
18,560 | bslatkin/dpxdt | dpxdt/server/work_queue_handlers.py | handle_add | def handle_add(queue_name):
"""Adds a task to a queue."""
source = request.form.get('source', request.remote_addr, type=str)
try:
task_id = work_queue.add(
queue_name,
payload=request.form.get('payload', type=str),
content_type=request.form.get('content_type', type=str),
source=source,
task_id=request.form.get('task_id', type=str))
except work_queue.Error, e:
return utils.jsonify_error(e)
db.session.commit()
logging.info('Task added: queue=%r, task_id=%r, source=%r',
queue_name, task_id, source)
return flask.jsonify(task_id=task_id) | python | def handle_add(queue_name):
source = request.form.get('source', request.remote_addr, type=str)
try:
task_id = work_queue.add(
queue_name,
payload=request.form.get('payload', type=str),
content_type=request.form.get('content_type', type=str),
source=source,
task_id=request.form.get('task_id', type=str))
except work_queue.Error, e:
return utils.jsonify_error(e)
db.session.commit()
logging.info('Task added: queue=%r, task_id=%r, source=%r',
queue_name, task_id, source)
return flask.jsonify(task_id=task_id) | [
"def",
"handle_add",
"(",
"queue_name",
")",
":",
"source",
"=",
"request",
".",
"form",
".",
"get",
"(",
"'source'",
",",
"request",
".",
"remote_addr",
",",
"type",
"=",
"str",
")",
"try",
":",
"task_id",
"=",
"work_queue",
".",
"add",
"(",
"queue_na... | Adds a task to a queue. | [
"Adds",
"a",
"task",
"to",
"a",
"queue",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/work_queue_handlers.py#L37-L53 |
18,561 | bslatkin/dpxdt | dpxdt/server/work_queue_handlers.py | handle_lease | def handle_lease(queue_name):
"""Leases a task from a queue."""
owner = request.form.get('owner', request.remote_addr, type=str)
try:
task_list = work_queue.lease(
queue_name,
owner,
request.form.get('count', 1, type=int),
request.form.get('timeout', 60, type=int))
except work_queue.Error, e:
return utils.jsonify_error(e)
if not task_list:
return flask.jsonify(tasks=[])
db.session.commit()
task_ids = [t['task_id'] for t in task_list]
logging.debug('Task leased: queue=%r, task_ids=%r, owner=%r',
queue_name, task_ids, owner)
return flask.jsonify(tasks=task_list) | python | def handle_lease(queue_name):
owner = request.form.get('owner', request.remote_addr, type=str)
try:
task_list = work_queue.lease(
queue_name,
owner,
request.form.get('count', 1, type=int),
request.form.get('timeout', 60, type=int))
except work_queue.Error, e:
return utils.jsonify_error(e)
if not task_list:
return flask.jsonify(tasks=[])
db.session.commit()
task_ids = [t['task_id'] for t in task_list]
logging.debug('Task leased: queue=%r, task_ids=%r, owner=%r',
queue_name, task_ids, owner)
return flask.jsonify(tasks=task_list) | [
"def",
"handle_lease",
"(",
"queue_name",
")",
":",
"owner",
"=",
"request",
".",
"form",
".",
"get",
"(",
"'owner'",
",",
"request",
".",
"remote_addr",
",",
"type",
"=",
"str",
")",
"try",
":",
"task_list",
"=",
"work_queue",
".",
"lease",
"(",
"queu... | Leases a task from a queue. | [
"Leases",
"a",
"task",
"from",
"a",
"queue",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/work_queue_handlers.py#L59-L78 |
18,562 | bslatkin/dpxdt | dpxdt/server/work_queue_handlers.py | handle_heartbeat | def handle_heartbeat(queue_name):
"""Updates the heartbeat message for a task."""
task_id = request.form.get('task_id', type=str)
message = request.form.get('message', type=str)
index = request.form.get('index', type=int)
try:
work_queue.heartbeat(
queue_name,
task_id,
request.form.get('owner', request.remote_addr, type=str),
message,
index)
except work_queue.Error, e:
return utils.jsonify_error(e)
db.session.commit()
logging.debug('Task heartbeat: queue=%r, task_id=%r, message=%r, index=%d',
queue_name, task_id, message, index)
return flask.jsonify(success=True) | python | def handle_heartbeat(queue_name):
task_id = request.form.get('task_id', type=str)
message = request.form.get('message', type=str)
index = request.form.get('index', type=int)
try:
work_queue.heartbeat(
queue_name,
task_id,
request.form.get('owner', request.remote_addr, type=str),
message,
index)
except work_queue.Error, e:
return utils.jsonify_error(e)
db.session.commit()
logging.debug('Task heartbeat: queue=%r, task_id=%r, message=%r, index=%d',
queue_name, task_id, message, index)
return flask.jsonify(success=True) | [
"def",
"handle_heartbeat",
"(",
"queue_name",
")",
":",
"task_id",
"=",
"request",
".",
"form",
".",
"get",
"(",
"'task_id'",
",",
"type",
"=",
"str",
")",
"message",
"=",
"request",
".",
"form",
".",
"get",
"(",
"'message'",
",",
"type",
"=",
"str",
... | Updates the heartbeat message for a task. | [
"Updates",
"the",
"heartbeat",
"message",
"for",
"a",
"task",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/work_queue_handlers.py#L84-L102 |
18,563 | bslatkin/dpxdt | dpxdt/server/work_queue_handlers.py | handle_finish | def handle_finish(queue_name):
"""Marks a task on a queue as finished."""
task_id = request.form.get('task_id', type=str)
owner = request.form.get('owner', request.remote_addr, type=str)
error = request.form.get('error', type=str) is not None
try:
work_queue.finish(queue_name, task_id, owner, error=error)
except work_queue.Error, e:
return utils.jsonify_error(e)
db.session.commit()
logging.debug('Task finished: queue=%r, task_id=%r, owner=%r, error=%r',
queue_name, task_id, owner, error)
return flask.jsonify(success=True) | python | def handle_finish(queue_name):
task_id = request.form.get('task_id', type=str)
owner = request.form.get('owner', request.remote_addr, type=str)
error = request.form.get('error', type=str) is not None
try:
work_queue.finish(queue_name, task_id, owner, error=error)
except work_queue.Error, e:
return utils.jsonify_error(e)
db.session.commit()
logging.debug('Task finished: queue=%r, task_id=%r, owner=%r, error=%r',
queue_name, task_id, owner, error)
return flask.jsonify(success=True) | [
"def",
"handle_finish",
"(",
"queue_name",
")",
":",
"task_id",
"=",
"request",
".",
"form",
".",
"get",
"(",
"'task_id'",
",",
"type",
"=",
"str",
")",
"owner",
"=",
"request",
".",
"form",
".",
"get",
"(",
"'owner'",
",",
"request",
".",
"remote_addr... | Marks a task on a queue as finished. | [
"Marks",
"a",
"task",
"on",
"a",
"queue",
"as",
"finished",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/work_queue_handlers.py#L108-L121 |
18,564 | bslatkin/dpxdt | dpxdt/server/work_queue_handlers.py | view_all_work_queues | def view_all_work_queues():
"""Page for viewing the index of all active work queues."""
count_list = list(
db.session.query(
work_queue.WorkQueue.queue_name,
work_queue.WorkQueue.status,
func.count(work_queue.WorkQueue.task_id))
.group_by(work_queue.WorkQueue.queue_name,
work_queue.WorkQueue.status))
queue_dict = {}
for name, status, count in count_list:
queue_dict[(name, status)] = dict(
name=name, status=status, count=count)
max_created_list = list(
db.session.query(
work_queue.WorkQueue.queue_name,
work_queue.WorkQueue.status,
func.max(work_queue.WorkQueue.created))
.group_by(work_queue.WorkQueue.queue_name,
work_queue.WorkQueue.status))
for name, status, newest_created in max_created_list:
queue_dict[(name, status)]['newest_created'] = newest_created
min_eta_list = list(
db.session.query(
work_queue.WorkQueue.queue_name,
work_queue.WorkQueue.status,
func.min(work_queue.WorkQueue.eta))
.group_by(work_queue.WorkQueue.queue_name,
work_queue.WorkQueue.status))
for name, status, oldest_eta in min_eta_list:
queue_dict[(name, status)]['oldest_eta'] = oldest_eta
queue_list = list(queue_dict.values())
queue_list.sort(key=lambda x: (x['name'], x['status']))
context = dict(
queue_list=queue_list,
)
return render_template('view_work_queue_index.html', **context) | python | def view_all_work_queues():
count_list = list(
db.session.query(
work_queue.WorkQueue.queue_name,
work_queue.WorkQueue.status,
func.count(work_queue.WorkQueue.task_id))
.group_by(work_queue.WorkQueue.queue_name,
work_queue.WorkQueue.status))
queue_dict = {}
for name, status, count in count_list:
queue_dict[(name, status)] = dict(
name=name, status=status, count=count)
max_created_list = list(
db.session.query(
work_queue.WorkQueue.queue_name,
work_queue.WorkQueue.status,
func.max(work_queue.WorkQueue.created))
.group_by(work_queue.WorkQueue.queue_name,
work_queue.WorkQueue.status))
for name, status, newest_created in max_created_list:
queue_dict[(name, status)]['newest_created'] = newest_created
min_eta_list = list(
db.session.query(
work_queue.WorkQueue.queue_name,
work_queue.WorkQueue.status,
func.min(work_queue.WorkQueue.eta))
.group_by(work_queue.WorkQueue.queue_name,
work_queue.WorkQueue.status))
for name, status, oldest_eta in min_eta_list:
queue_dict[(name, status)]['oldest_eta'] = oldest_eta
queue_list = list(queue_dict.values())
queue_list.sort(key=lambda x: (x['name'], x['status']))
context = dict(
queue_list=queue_list,
)
return render_template('view_work_queue_index.html', **context) | [
"def",
"view_all_work_queues",
"(",
")",
":",
"count_list",
"=",
"list",
"(",
"db",
".",
"session",
".",
"query",
"(",
"work_queue",
".",
"WorkQueue",
".",
"queue_name",
",",
"work_queue",
".",
"WorkQueue",
".",
"status",
",",
"func",
".",
"count",
"(",
... | Page for viewing the index of all active work queues. | [
"Page",
"for",
"viewing",
"the",
"index",
"of",
"all",
"active",
"work",
"queues",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/work_queue_handlers.py#L126-L169 |
18,565 | bslatkin/dpxdt | dpxdt/server/work_queue_handlers.py | manage_work_queue | def manage_work_queue(queue_name):
"""Page for viewing the contents of a work queue."""
modify_form = forms.ModifyWorkQueueTaskForm()
if modify_form.validate_on_submit():
primary_key = (modify_form.task_id.data, queue_name)
task = work_queue.WorkQueue.query.get(primary_key)
if task:
logging.info('Action: %s task_id=%r',
modify_form.action.data, modify_form.task_id.data)
if modify_form.action.data == 'retry':
task.status = work_queue.WorkQueue.LIVE
task.lease_attempts = 0
task.heartbeat = 'Retrying ...'
db.session.add(task)
else:
db.session.delete(task)
db.session.commit()
else:
logging.warning('Could not find task_id=%r to delete',
modify_form.task_id.data)
return redirect(url_for('manage_work_queue', queue_name=queue_name))
query = (
work_queue.WorkQueue.query
.filter_by(queue_name=queue_name)
.order_by(work_queue.WorkQueue.created.desc()))
status = request.args.get('status', '', type=str).lower()
if status in work_queue.WorkQueue.STATES:
query = query.filter_by(status=status)
else:
status = None
item_list = list(query.limit(100))
work_list = []
for item in item_list:
form = forms.ModifyWorkQueueTaskForm()
form.task_id.data = item.task_id
form.delete.data = True
work_list.append((item, form))
context = dict(
queue_name=queue_name,
status=status,
work_list=work_list,
)
return render_template('view_work_queue.html', **context) | python | def manage_work_queue(queue_name):
modify_form = forms.ModifyWorkQueueTaskForm()
if modify_form.validate_on_submit():
primary_key = (modify_form.task_id.data, queue_name)
task = work_queue.WorkQueue.query.get(primary_key)
if task:
logging.info('Action: %s task_id=%r',
modify_form.action.data, modify_form.task_id.data)
if modify_form.action.data == 'retry':
task.status = work_queue.WorkQueue.LIVE
task.lease_attempts = 0
task.heartbeat = 'Retrying ...'
db.session.add(task)
else:
db.session.delete(task)
db.session.commit()
else:
logging.warning('Could not find task_id=%r to delete',
modify_form.task_id.data)
return redirect(url_for('manage_work_queue', queue_name=queue_name))
query = (
work_queue.WorkQueue.query
.filter_by(queue_name=queue_name)
.order_by(work_queue.WorkQueue.created.desc()))
status = request.args.get('status', '', type=str).lower()
if status in work_queue.WorkQueue.STATES:
query = query.filter_by(status=status)
else:
status = None
item_list = list(query.limit(100))
work_list = []
for item in item_list:
form = forms.ModifyWorkQueueTaskForm()
form.task_id.data = item.task_id
form.delete.data = True
work_list.append((item, form))
context = dict(
queue_name=queue_name,
status=status,
work_list=work_list,
)
return render_template('view_work_queue.html', **context) | [
"def",
"manage_work_queue",
"(",
"queue_name",
")",
":",
"modify_form",
"=",
"forms",
".",
"ModifyWorkQueueTaskForm",
"(",
")",
"if",
"modify_form",
".",
"validate_on_submit",
"(",
")",
":",
"primary_key",
"=",
"(",
"modify_form",
".",
"task_id",
".",
"data",
... | Page for viewing the contents of a work queue. | [
"Page",
"for",
"viewing",
"the",
"contents",
"of",
"a",
"work",
"queue",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/work_queue_handlers.py#L174-L220 |
18,566 | bslatkin/dpxdt | dpxdt/server/utils.py | retryable_transaction | def retryable_transaction(attempts=3, exceptions=(OperationalError,)):
"""Decorator retries a function when expected exceptions are raised."""
assert len(exceptions) > 0
assert attempts > 0
def wrapper(f):
@functools.wraps(f)
def wrapped(*args, **kwargs):
for i in xrange(attempts):
try:
return f(*args, **kwargs)
except exceptions, e:
if i == (attempts - 1):
raise
logging.warning(
'Retryable error in transaction on attempt %d. %s: %s',
i + 1, e.__class__.__name__, e)
db.session.rollback()
return wrapped
return wrapper | python | def retryable_transaction(attempts=3, exceptions=(OperationalError,)):
assert len(exceptions) > 0
assert attempts > 0
def wrapper(f):
@functools.wraps(f)
def wrapped(*args, **kwargs):
for i in xrange(attempts):
try:
return f(*args, **kwargs)
except exceptions, e:
if i == (attempts - 1):
raise
logging.warning(
'Retryable error in transaction on attempt %d. %s: %s',
i + 1, e.__class__.__name__, e)
db.session.rollback()
return wrapped
return wrapper | [
"def",
"retryable_transaction",
"(",
"attempts",
"=",
"3",
",",
"exceptions",
"=",
"(",
"OperationalError",
",",
")",
")",
":",
"assert",
"len",
"(",
"exceptions",
")",
">",
"0",
"assert",
"attempts",
">",
"0",
"def",
"wrapper",
"(",
"f",
")",
":",
"@"... | Decorator retries a function when expected exceptions are raised. | [
"Decorator",
"retries",
"a",
"function",
"when",
"expected",
"exceptions",
"are",
"raised",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/utils.py#L37-L58 |
18,567 | bslatkin/dpxdt | dpxdt/server/utils.py | jsonify_assert | def jsonify_assert(asserted, message, status_code=400):
"""Asserts something is true, aborts the request if not."""
if asserted:
return
try:
raise AssertionError(message)
except AssertionError, e:
stack = traceback.extract_stack()
stack.pop()
logging.error('Assertion failed: %s\n%s',
str(e), ''.join(traceback.format_list(stack)))
abort(jsonify_error(e, status_code=status_code)) | python | def jsonify_assert(asserted, message, status_code=400):
if asserted:
return
try:
raise AssertionError(message)
except AssertionError, e:
stack = traceback.extract_stack()
stack.pop()
logging.error('Assertion failed: %s\n%s',
str(e), ''.join(traceback.format_list(stack)))
abort(jsonify_error(e, status_code=status_code)) | [
"def",
"jsonify_assert",
"(",
"asserted",
",",
"message",
",",
"status_code",
"=",
"400",
")",
":",
"if",
"asserted",
":",
"return",
"try",
":",
"raise",
"AssertionError",
"(",
"message",
")",
"except",
"AssertionError",
",",
"e",
":",
"stack",
"=",
"trace... | Asserts something is true, aborts the request if not. | [
"Asserts",
"something",
"is",
"true",
"aborts",
"the",
"request",
"if",
"not",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/utils.py#L61-L72 |
18,568 | bslatkin/dpxdt | dpxdt/server/utils.py | jsonify_error | def jsonify_error(message_or_exception, status_code=400):
"""Returns a JSON payload that indicates the request had an error."""
if isinstance(message_or_exception, Exception):
message = '%s: %s' % (
message_or_exception.__class__.__name__, message_or_exception)
else:
message = message_or_exception
logging.debug('Returning status=%s, error message: %s',
status_code, message)
response = jsonify(error=message)
response.status_code = status_code
return response | python | def jsonify_error(message_or_exception, status_code=400):
if isinstance(message_or_exception, Exception):
message = '%s: %s' % (
message_or_exception.__class__.__name__, message_or_exception)
else:
message = message_or_exception
logging.debug('Returning status=%s, error message: %s',
status_code, message)
response = jsonify(error=message)
response.status_code = status_code
return response | [
"def",
"jsonify_error",
"(",
"message_or_exception",
",",
"status_code",
"=",
"400",
")",
":",
"if",
"isinstance",
"(",
"message_or_exception",
",",
"Exception",
")",
":",
"message",
"=",
"'%s: %s'",
"%",
"(",
"message_or_exception",
".",
"__class__",
".",
"__na... | Returns a JSON payload that indicates the request had an error. | [
"Returns",
"a",
"JSON",
"payload",
"that",
"indicates",
"the",
"request",
"had",
"an",
"error",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/utils.py#L75-L87 |
18,569 | bslatkin/dpxdt | dpxdt/server/utils.py | ignore_exceptions | def ignore_exceptions(f):
"""Decorator catches and ignores any exceptions raised by this function."""
@functools.wraps(f)
def wrapped(*args, **kwargs):
try:
return f(*args, **kwargs)
except:
logging.exception("Ignoring exception in %r", f)
return wrapped | python | def ignore_exceptions(f):
@functools.wraps(f)
def wrapped(*args, **kwargs):
try:
return f(*args, **kwargs)
except:
logging.exception("Ignoring exception in %r", f)
return wrapped | [
"def",
"ignore_exceptions",
"(",
"f",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"wrapped",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"ex... | Decorator catches and ignores any exceptions raised by this function. | [
"Decorator",
"catches",
"and",
"ignores",
"any",
"exceptions",
"raised",
"by",
"this",
"function",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/utils.py#L90-L98 |
18,570 | bslatkin/dpxdt | dpxdt/server/utils.py | timesince | def timesince(when):
"""Returns string representing "time since" or "time until".
Examples:
3 days ago, 5 hours ago, 3 minutes from now, 5 hours from now, now.
"""
if not when:
return ''
now = datetime.datetime.utcnow()
if now > when:
diff = now - when
suffix = 'ago'
else:
diff = when - now
suffix = 'from now'
periods = (
(diff.days / 365, 'year', 'years'),
(diff.days / 30, 'month', 'months'),
(diff.days / 7, 'week', 'weeks'),
(diff.days, 'day', 'days'),
(diff.seconds / 3600, 'hour', 'hours'),
(diff.seconds / 60, 'minute', 'minutes'),
(diff.seconds, 'second', 'seconds'),
)
for period, singular, plural in periods:
if period:
return '%d %s %s' % (
period,
singular if period == 1 else plural,
suffix)
return 'now' | python | def timesince(when):
if not when:
return ''
now = datetime.datetime.utcnow()
if now > when:
diff = now - when
suffix = 'ago'
else:
diff = when - now
suffix = 'from now'
periods = (
(diff.days / 365, 'year', 'years'),
(diff.days / 30, 'month', 'months'),
(diff.days / 7, 'week', 'weeks'),
(diff.days, 'day', 'days'),
(diff.seconds / 3600, 'hour', 'hours'),
(diff.seconds / 60, 'minute', 'minutes'),
(diff.seconds, 'second', 'seconds'),
)
for period, singular, plural in periods:
if period:
return '%d %s %s' % (
period,
singular if period == 1 else plural,
suffix)
return 'now' | [
"def",
"timesince",
"(",
"when",
")",
":",
"if",
"not",
"when",
":",
"return",
"''",
"now",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"if",
"now",
">",
"when",
":",
"diff",
"=",
"now",
"-",
"when",
"suffix",
"=",
"'ago'",
"else",
... | Returns string representing "time since" or "time until".
Examples:
3 days ago, 5 hours ago, 3 minutes from now, 5 hours from now, now. | [
"Returns",
"string",
"representing",
"time",
"since",
"or",
"time",
"until",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/utils.py#L103-L137 |
18,571 | bslatkin/dpxdt | dpxdt/server/utils.py | human_uuid | def human_uuid():
"""Returns a good UUID for using as a human readable string."""
return base64.b32encode(
hashlib.sha1(uuid.uuid4().bytes).digest()).lower().strip('=') | python | def human_uuid():
return base64.b32encode(
hashlib.sha1(uuid.uuid4().bytes).digest()).lower().strip('=') | [
"def",
"human_uuid",
"(",
")",
":",
"return",
"base64",
".",
"b32encode",
"(",
"hashlib",
".",
"sha1",
"(",
"uuid",
".",
"uuid4",
"(",
")",
".",
"bytes",
")",
".",
"digest",
"(",
")",
")",
".",
"lower",
"(",
")",
".",
"strip",
"(",
"'='",
")"
] | Returns a good UUID for using as a human readable string. | [
"Returns",
"a",
"good",
"UUID",
"for",
"using",
"as",
"a",
"human",
"readable",
"string",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/utils.py#L140-L143 |
18,572 | bslatkin/dpxdt | dpxdt/server/utils.py | get_deployment_timestamp | def get_deployment_timestamp():
"""Returns a unique string represeting the current deployment.
Used for busting caches.
"""
# TODO: Support other deployment situations.
if os.environ.get('SERVER_SOFTWARE', '').startswith('Google App Engine'):
version_id = os.environ.get('CURRENT_VERSION_ID')
major_version, timestamp = version_id.split('.', 1)
return timestamp
return 'test' | python | def get_deployment_timestamp():
# TODO: Support other deployment situations.
if os.environ.get('SERVER_SOFTWARE', '').startswith('Google App Engine'):
version_id = os.environ.get('CURRENT_VERSION_ID')
major_version, timestamp = version_id.split('.', 1)
return timestamp
return 'test' | [
"def",
"get_deployment_timestamp",
"(",
")",
":",
"# TODO: Support other deployment situations.",
"if",
"os",
".",
"environ",
".",
"get",
"(",
"'SERVER_SOFTWARE'",
",",
"''",
")",
".",
"startswith",
"(",
"'Google App Engine'",
")",
":",
"version_id",
"=",
"os",
".... | Returns a unique string represeting the current deployment.
Used for busting caches. | [
"Returns",
"a",
"unique",
"string",
"represeting",
"the",
"current",
"deployment",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/utils.py#L163-L173 |
18,573 | bslatkin/dpxdt | dpxdt/tools/url_pair_diff.py | real_main | def real_main(new_url=None,
baseline_url=None,
upload_build_id=None,
upload_release_name=None):
"""Runs the ur_pair_diff."""
coordinator = workers.get_coordinator()
fetch_worker.register(coordinator)
coordinator.start()
item = UrlPairDiff(
new_url,
baseline_url,
upload_build_id,
upload_release_name=upload_release_name,
heartbeat=workers.PrintWorkflow)
item.root = True
coordinator.input_queue.put(item)
coordinator.wait_one()
coordinator.stop()
coordinator.join() | python | def real_main(new_url=None,
baseline_url=None,
upload_build_id=None,
upload_release_name=None):
coordinator = workers.get_coordinator()
fetch_worker.register(coordinator)
coordinator.start()
item = UrlPairDiff(
new_url,
baseline_url,
upload_build_id,
upload_release_name=upload_release_name,
heartbeat=workers.PrintWorkflow)
item.root = True
coordinator.input_queue.put(item)
coordinator.wait_one()
coordinator.stop()
coordinator.join() | [
"def",
"real_main",
"(",
"new_url",
"=",
"None",
",",
"baseline_url",
"=",
"None",
",",
"upload_build_id",
"=",
"None",
",",
"upload_release_name",
"=",
"None",
")",
":",
"coordinator",
"=",
"workers",
".",
"get_coordinator",
"(",
")",
"fetch_worker",
".",
"... | Runs the ur_pair_diff. | [
"Runs",
"the",
"ur_pair_diff",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/tools/url_pair_diff.py#L132-L152 |
18,574 | bslatkin/dpxdt | dpxdt/client/fetch_worker.py | fetch_internal | def fetch_internal(item, request):
"""Fetches the given request by using the local Flask context."""
# Break client dependence on Flask if internal fetches aren't being used.
from flask import make_response
from werkzeug.test import EnvironBuilder
# Break circular dependencies.
from dpxdt.server import app
# Attempt to create a Flask environment from a urllib2.Request object.
environ_base = {
'REMOTE_ADDR': '127.0.0.1',
}
# The data object may be a generator from poster.multipart_encode, so we
# need to convert that to raw bytes here. Unfortunately EnvironBuilder
# only works with the whole request buffered in memory.
data = request.get_data()
if data and not isinstance(data, str):
data = ''.join(list(data))
builder = EnvironBuilder(
path=request.get_selector(),
base_url='%s://%s' % (request.get_type(), request.get_host()),
method=request.get_method(),
data=data,
headers=request.header_items(),
environ_base=environ_base)
with app.request_context(builder.get_environ()):
response = make_response(app.dispatch_request())
LOGGER.info('"%s" %s via internal routing',
request.get_selector(), response.status_code)
item.status_code = response.status_code
item.content_type = response.mimetype
if item.result_path:
# TODO: Is there a better way to access the response stream?
with open(item.result_path, 'wb') as result_file:
for piece in response.iter_encoded():
result_file.write(piece)
else:
item.data = response.get_data()
return item | python | def fetch_internal(item, request):
# Break client dependence on Flask if internal fetches aren't being used.
from flask import make_response
from werkzeug.test import EnvironBuilder
# Break circular dependencies.
from dpxdt.server import app
# Attempt to create a Flask environment from a urllib2.Request object.
environ_base = {
'REMOTE_ADDR': '127.0.0.1',
}
# The data object may be a generator from poster.multipart_encode, so we
# need to convert that to raw bytes here. Unfortunately EnvironBuilder
# only works with the whole request buffered in memory.
data = request.get_data()
if data and not isinstance(data, str):
data = ''.join(list(data))
builder = EnvironBuilder(
path=request.get_selector(),
base_url='%s://%s' % (request.get_type(), request.get_host()),
method=request.get_method(),
data=data,
headers=request.header_items(),
environ_base=environ_base)
with app.request_context(builder.get_environ()):
response = make_response(app.dispatch_request())
LOGGER.info('"%s" %s via internal routing',
request.get_selector(), response.status_code)
item.status_code = response.status_code
item.content_type = response.mimetype
if item.result_path:
# TODO: Is there a better way to access the response stream?
with open(item.result_path, 'wb') as result_file:
for piece in response.iter_encoded():
result_file.write(piece)
else:
item.data = response.get_data()
return item | [
"def",
"fetch_internal",
"(",
"item",
",",
"request",
")",
":",
"# Break client dependence on Flask if internal fetches aren't being used.",
"from",
"flask",
"import",
"make_response",
"from",
"werkzeug",
".",
"test",
"import",
"EnvironBuilder",
"# Break circular dependencies."... | Fetches the given request by using the local Flask context. | [
"Fetches",
"the",
"given",
"request",
"by",
"using",
"the",
"local",
"Flask",
"context",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/client/fetch_worker.py#L118-L160 |
18,575 | bslatkin/dpxdt | dpxdt/client/fetch_worker.py | fetch_normal | def fetch_normal(item, request):
"""Fetches the given request over HTTP."""
try:
conn = urllib2.urlopen(request, timeout=item.timeout_seconds)
except urllib2.HTTPError, e:
conn = e
except (urllib2.URLError, ssl.SSLError), e:
# TODO: Make this status more clear
item.status_code = 400
return item
try:
item.status_code = conn.getcode()
item.content_type = conn.info().gettype()
if item.result_path:
with open(item.result_path, 'wb') as result_file:
shutil.copyfileobj(conn, result_file)
else:
item.data = conn.read()
except socket.timeout, e:
# TODO: Make this status more clear
item.status_code = 400
return item
finally:
conn.close()
return item | python | def fetch_normal(item, request):
try:
conn = urllib2.urlopen(request, timeout=item.timeout_seconds)
except urllib2.HTTPError, e:
conn = e
except (urllib2.URLError, ssl.SSLError), e:
# TODO: Make this status more clear
item.status_code = 400
return item
try:
item.status_code = conn.getcode()
item.content_type = conn.info().gettype()
if item.result_path:
with open(item.result_path, 'wb') as result_file:
shutil.copyfileobj(conn, result_file)
else:
item.data = conn.read()
except socket.timeout, e:
# TODO: Make this status more clear
item.status_code = 400
return item
finally:
conn.close()
return item | [
"def",
"fetch_normal",
"(",
"item",
",",
"request",
")",
":",
"try",
":",
"conn",
"=",
"urllib2",
".",
"urlopen",
"(",
"request",
",",
"timeout",
"=",
"item",
".",
"timeout_seconds",
")",
"except",
"urllib2",
".",
"HTTPError",
",",
"e",
":",
"conn",
"=... | Fetches the given request over HTTP. | [
"Fetches",
"the",
"given",
"request",
"over",
"HTTP",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/client/fetch_worker.py#L163-L189 |
18,576 | bslatkin/dpxdt | dpxdt/client/fetch_worker.py | FetchItem.json | def json(self):
"""Returns de-JSONed data or None if it's a different content type."""
if self._data_json:
return self._data_json
if not self.data or self.content_type != 'application/json':
return None
self._data_json = json.loads(self.data)
return self._data_json | python | def json(self):
if self._data_json:
return self._data_json
if not self.data or self.content_type != 'application/json':
return None
self._data_json = json.loads(self.data)
return self._data_json | [
"def",
"json",
"(",
"self",
")",
":",
"if",
"self",
".",
"_data_json",
":",
"return",
"self",
".",
"_data_json",
"if",
"not",
"self",
".",
"data",
"or",
"self",
".",
"content_type",
"!=",
"'application/json'",
":",
"return",
"None",
"self",
".",
"_data_j... | Returns de-JSONed data or None if it's a different content type. | [
"Returns",
"de",
"-",
"JSONed",
"data",
"or",
"None",
"if",
"it",
"s",
"a",
"different",
"content",
"type",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/client/fetch_worker.py#L106-L115 |
18,577 | bslatkin/dpxdt | dpxdt/tools/local_pdiff.py | CaptureAndDiffWorkflowItem.maybe_imgur | def maybe_imgur(self, path):
'''Uploads a file to imgur if requested via command line flags.
Returns either "path" or "path url" depending on the course of action.
'''
if not FLAGS.imgur_client_id:
return path
im = pyimgur.Imgur(FLAGS.imgur_client_id)
uploaded_image = im.upload_image(path)
return '%s %s' % (path, uploaded_image.link) | python | def maybe_imgur(self, path):
'''Uploads a file to imgur if requested via command line flags.
Returns either "path" or "path url" depending on the course of action.
'''
if not FLAGS.imgur_client_id:
return path
im = pyimgur.Imgur(FLAGS.imgur_client_id)
uploaded_image = im.upload_image(path)
return '%s %s' % (path, uploaded_image.link) | [
"def",
"maybe_imgur",
"(",
"self",
",",
"path",
")",
":",
"if",
"not",
"FLAGS",
".",
"imgur_client_id",
":",
"return",
"path",
"im",
"=",
"pyimgur",
".",
"Imgur",
"(",
"FLAGS",
".",
"imgur_client_id",
")",
"uploaded_image",
"=",
"im",
".",
"upload_image",
... | Uploads a file to imgur if requested via command line flags.
Returns either "path" or "path url" depending on the course of action. | [
"Uploads",
"a",
"file",
"to",
"imgur",
"if",
"requested",
"via",
"command",
"line",
"flags",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/tools/local_pdiff.py#L254-L264 |
18,578 | bslatkin/dpxdt | dpxdt/tools/diff_my_images.py | real_main | def real_main(release_url=None,
tests_json_path=None,
upload_build_id=None,
upload_release_name=None):
"""Runs diff_my_images."""
coordinator = workers.get_coordinator()
fetch_worker.register(coordinator)
coordinator.start()
data = open(FLAGS.tests_json_path).read()
tests = load_tests(data)
item = DiffMyImages(
release_url,
tests,
upload_build_id,
upload_release_name,
heartbeat=workers.PrintWorkflow)
item.root = True
coordinator.input_queue.put(item)
coordinator.wait_one()
coordinator.stop()
coordinator.join() | python | def real_main(release_url=None,
tests_json_path=None,
upload_build_id=None,
upload_release_name=None):
coordinator = workers.get_coordinator()
fetch_worker.register(coordinator)
coordinator.start()
data = open(FLAGS.tests_json_path).read()
tests = load_tests(data)
item = DiffMyImages(
release_url,
tests,
upload_build_id,
upload_release_name,
heartbeat=workers.PrintWorkflow)
item.root = True
coordinator.input_queue.put(item)
coordinator.wait_one()
coordinator.stop()
coordinator.join() | [
"def",
"real_main",
"(",
"release_url",
"=",
"None",
",",
"tests_json_path",
"=",
"None",
",",
"upload_build_id",
"=",
"None",
",",
"upload_release_name",
"=",
"None",
")",
":",
"coordinator",
"=",
"workers",
".",
"get_coordinator",
"(",
")",
"fetch_worker",
"... | Runs diff_my_images. | [
"Runs",
"diff_my_images",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/tools/diff_my_images.py#L175-L198 |
18,579 | bslatkin/dpxdt | dpxdt/tools/site_diff.py | clean_url | def clean_url(url, force_scheme=None):
"""Cleans the given URL."""
# URL should be ASCII according to RFC 3986
url = str(url)
# Collapse ../../ and related
url_parts = urlparse.urlparse(url)
path_parts = []
for part in url_parts.path.split('/'):
if part == '.':
continue
elif part == '..':
if path_parts:
path_parts.pop()
else:
path_parts.append(part)
url_parts = list(url_parts)
if force_scheme:
url_parts[0] = force_scheme
url_parts[2] = '/'.join(path_parts)
if FLAGS.keep_query_string == False:
url_parts[4] = '' # No query string
url_parts[5] = '' # No path
# Always have a trailing slash
if not url_parts[2]:
url_parts[2] = '/'
return urlparse.urlunparse(url_parts) | python | def clean_url(url, force_scheme=None):
# URL should be ASCII according to RFC 3986
url = str(url)
# Collapse ../../ and related
url_parts = urlparse.urlparse(url)
path_parts = []
for part in url_parts.path.split('/'):
if part == '.':
continue
elif part == '..':
if path_parts:
path_parts.pop()
else:
path_parts.append(part)
url_parts = list(url_parts)
if force_scheme:
url_parts[0] = force_scheme
url_parts[2] = '/'.join(path_parts)
if FLAGS.keep_query_string == False:
url_parts[4] = '' # No query string
url_parts[5] = '' # No path
# Always have a trailing slash
if not url_parts[2]:
url_parts[2] = '/'
return urlparse.urlunparse(url_parts) | [
"def",
"clean_url",
"(",
"url",
",",
"force_scheme",
"=",
"None",
")",
":",
"# URL should be ASCII according to RFC 3986",
"url",
"=",
"str",
"(",
"url",
")",
"# Collapse ../../ and related",
"url_parts",
"=",
"urlparse",
".",
"urlparse",
"(",
"url",
")",
"path_pa... | Cleans the given URL. | [
"Cleans",
"the",
"given",
"URL",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/tools/site_diff.py#L105-L135 |
18,580 | bslatkin/dpxdt | dpxdt/tools/site_diff.py | extract_urls | def extract_urls(url, data, unescape=HTMLParser.HTMLParser().unescape):
"""Extracts the URLs from an HTML document."""
parts = urlparse.urlparse(url)
prefix = '%s://%s' % (parts.scheme, parts.netloc)
accessed_dir = os.path.dirname(parts.path)
if not accessed_dir.endswith('/'):
accessed_dir += '/'
for pattern, replacement in REPLACEMENT_REGEXES:
fixed = replacement % {
'base': prefix,
'accessed_dir': accessed_dir,
}
data = re.sub(pattern, fixed, data)
result = set()
for match in re.finditer(MAYBE_HTML_URL_REGEX, data):
found_url = unescape(match.groupdict()['absurl'])
found_url = clean_url(
found_url,
force_scheme=parts[0]) # Use the main page's scheme
result.add(found_url)
return result | python | def extract_urls(url, data, unescape=HTMLParser.HTMLParser().unescape):
parts = urlparse.urlparse(url)
prefix = '%s://%s' % (parts.scheme, parts.netloc)
accessed_dir = os.path.dirname(parts.path)
if not accessed_dir.endswith('/'):
accessed_dir += '/'
for pattern, replacement in REPLACEMENT_REGEXES:
fixed = replacement % {
'base': prefix,
'accessed_dir': accessed_dir,
}
data = re.sub(pattern, fixed, data)
result = set()
for match in re.finditer(MAYBE_HTML_URL_REGEX, data):
found_url = unescape(match.groupdict()['absurl'])
found_url = clean_url(
found_url,
force_scheme=parts[0]) # Use the main page's scheme
result.add(found_url)
return result | [
"def",
"extract_urls",
"(",
"url",
",",
"data",
",",
"unescape",
"=",
"HTMLParser",
".",
"HTMLParser",
"(",
")",
".",
"unescape",
")",
":",
"parts",
"=",
"urlparse",
".",
"urlparse",
"(",
"url",
")",
"prefix",
"=",
"'%s://%s'",
"%",
"(",
"parts",
".",
... | Extracts the URLs from an HTML document. | [
"Extracts",
"the",
"URLs",
"from",
"an",
"HTML",
"document",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/tools/site_diff.py#L138-L162 |
18,581 | bslatkin/dpxdt | dpxdt/tools/site_diff.py | prune_urls | def prune_urls(url_set, start_url, allowed_list, ignored_list):
"""Prunes URLs that should be ignored."""
result = set()
for url in url_set:
allowed = False
for allow_url in allowed_list:
if url.startswith(allow_url):
allowed = True
break
if not allowed:
continue
ignored = False
for ignore_url in ignored_list:
if url.startswith(ignore_url):
ignored = True
break
if ignored:
continue
prefix, suffix = (url.rsplit('.', 1) + [''])[:2]
if suffix.lower() in IGNORE_SUFFIXES:
continue
result.add(url)
return result | python | def prune_urls(url_set, start_url, allowed_list, ignored_list):
result = set()
for url in url_set:
allowed = False
for allow_url in allowed_list:
if url.startswith(allow_url):
allowed = True
break
if not allowed:
continue
ignored = False
for ignore_url in ignored_list:
if url.startswith(ignore_url):
ignored = True
break
if ignored:
continue
prefix, suffix = (url.rsplit('.', 1) + [''])[:2]
if suffix.lower() in IGNORE_SUFFIXES:
continue
result.add(url)
return result | [
"def",
"prune_urls",
"(",
"url_set",
",",
"start_url",
",",
"allowed_list",
",",
"ignored_list",
")",
":",
"result",
"=",
"set",
"(",
")",
"for",
"url",
"in",
"url_set",
":",
"allowed",
"=",
"False",
"for",
"allow_url",
"in",
"allowed_list",
":",
"if",
"... | Prunes URLs that should be ignored. | [
"Prunes",
"URLs",
"that",
"should",
"be",
"ignored",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/tools/site_diff.py#L169-L198 |
18,582 | bslatkin/dpxdt | dpxdt/tools/site_diff.py | real_main | def real_main(start_url=None,
ignore_prefixes=None,
upload_build_id=None,
upload_release_name=None):
"""Runs the site_diff."""
coordinator = workers.get_coordinator()
fetch_worker.register(coordinator)
coordinator.start()
item = SiteDiff(
start_url=start_url,
ignore_prefixes=ignore_prefixes,
upload_build_id=upload_build_id,
upload_release_name=upload_release_name,
heartbeat=workers.PrintWorkflow)
item.root = True
coordinator.input_queue.put(item)
coordinator.wait_one()
coordinator.stop()
coordinator.join() | python | def real_main(start_url=None,
ignore_prefixes=None,
upload_build_id=None,
upload_release_name=None):
coordinator = workers.get_coordinator()
fetch_worker.register(coordinator)
coordinator.start()
item = SiteDiff(
start_url=start_url,
ignore_prefixes=ignore_prefixes,
upload_build_id=upload_build_id,
upload_release_name=upload_release_name,
heartbeat=workers.PrintWorkflow)
item.root = True
coordinator.input_queue.put(item)
coordinator.wait_one()
coordinator.stop()
coordinator.join() | [
"def",
"real_main",
"(",
"start_url",
"=",
"None",
",",
"ignore_prefixes",
"=",
"None",
",",
"upload_build_id",
"=",
"None",
",",
"upload_release_name",
"=",
"None",
")",
":",
"coordinator",
"=",
"workers",
".",
"get_coordinator",
"(",
")",
"fetch_worker",
"."... | Runs the site_diff. | [
"Runs",
"the",
"site_diff",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/tools/site_diff.py#L328-L348 |
18,583 | bslatkin/dpxdt | dpxdt/server/emails.py | render_or_send | def render_or_send(func, message):
"""Renders an email message for debugging or actually sends it."""
if request.endpoint != func.func_name:
mail.send(message)
if (current_user.is_authenticated() and current_user.superuser):
return render_template('debug_email.html', message=message) | python | def render_or_send(func, message):
if request.endpoint != func.func_name:
mail.send(message)
if (current_user.is_authenticated() and current_user.superuser):
return render_template('debug_email.html', message=message) | [
"def",
"render_or_send",
"(",
"func",
",",
"message",
")",
":",
"if",
"request",
".",
"endpoint",
"!=",
"func",
".",
"func_name",
":",
"mail",
".",
"send",
"(",
"message",
")",
"if",
"(",
"current_user",
".",
"is_authenticated",
"(",
")",
"and",
"current... | Renders an email message for debugging or actually sends it. | [
"Renders",
"an",
"email",
"message",
"for",
"debugging",
"or",
"actually",
"sends",
"it",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/emails.py#L33-L39 |
18,584 | bslatkin/dpxdt | dpxdt/server/emails.py | send_ready_for_review | def send_ready_for_review(build_id, release_name, release_number):
"""Sends an email indicating that the release is ready for review."""
build = models.Build.query.get(build_id)
if not build.send_email:
logging.debug(
'Not sending ready for review email because build does not have '
'email enabled. build_id=%r', build.id)
return
ops = operations.BuildOps(build_id)
release, run_list, stats_dict, _ = ops.get_release(
release_name, release_number)
if not run_list:
logging.debug(
'Not sending ready for review email because there are '
' no runs. build_id=%r, release_name=%r, release_number=%d',
build.id, release.name, release.number)
return
title = '%s: %s - Ready for review' % (build.name, release.name)
email_body = render_template(
'email_ready_for_review.html',
build=build,
release=release,
run_list=run_list,
stats_dict=stats_dict)
recipients = []
if build.email_alias:
recipients.append(build.email_alias)
else:
for user in build.owners:
recipients.append(user.email_address)
if not recipients:
logging.debug(
'Not sending ready for review email because there are no '
'recipients. build_id=%r, release_name=%r, release_number=%d',
build.id, release.name, release.number)
return
message = Message(title, recipients=recipients)
message.html = email_body
logging.info('Sending ready for review email for build_id=%r, '
'release_name=%r, release_number=%d to %r',
build.id, release.name, release.number, recipients)
return render_or_send(send_ready_for_review, message) | python | def send_ready_for_review(build_id, release_name, release_number):
build = models.Build.query.get(build_id)
if not build.send_email:
logging.debug(
'Not sending ready for review email because build does not have '
'email enabled. build_id=%r', build.id)
return
ops = operations.BuildOps(build_id)
release, run_list, stats_dict, _ = ops.get_release(
release_name, release_number)
if not run_list:
logging.debug(
'Not sending ready for review email because there are '
' no runs. build_id=%r, release_name=%r, release_number=%d',
build.id, release.name, release.number)
return
title = '%s: %s - Ready for review' % (build.name, release.name)
email_body = render_template(
'email_ready_for_review.html',
build=build,
release=release,
run_list=run_list,
stats_dict=stats_dict)
recipients = []
if build.email_alias:
recipients.append(build.email_alias)
else:
for user in build.owners:
recipients.append(user.email_address)
if not recipients:
logging.debug(
'Not sending ready for review email because there are no '
'recipients. build_id=%r, release_name=%r, release_number=%d',
build.id, release.name, release.number)
return
message = Message(title, recipients=recipients)
message.html = email_body
logging.info('Sending ready for review email for build_id=%r, '
'release_name=%r, release_number=%d to %r',
build.id, release.name, release.number, recipients)
return render_or_send(send_ready_for_review, message) | [
"def",
"send_ready_for_review",
"(",
"build_id",
",",
"release_name",
",",
"release_number",
")",
":",
"build",
"=",
"models",
".",
"Build",
".",
"query",
".",
"get",
"(",
"build_id",
")",
"if",
"not",
"build",
".",
"send_email",
":",
"logging",
".",
"debu... | Sends an email indicating that the release is ready for review. | [
"Sends",
"an",
"email",
"indicating",
"that",
"the",
"release",
"is",
"ready",
"for",
"review",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/emails.py#L45-L96 |
18,585 | bslatkin/dpxdt | dpxdt/server/frontend.py | homepage | def homepage():
"""Renders the homepage."""
if current_user.is_authenticated():
if not login_fresh():
logging.debug('User needs a fresh token')
abort(login.needs_refresh())
auth.claim_invitations(current_user)
build_list = operations.UserOps(current_user.get_id()).get_builds()
return render_template(
'home.html',
build_list=build_list,
show_video_and_promo_text=app.config['SHOW_VIDEO_AND_PROMO_TEXT']) | python | def homepage():
if current_user.is_authenticated():
if not login_fresh():
logging.debug('User needs a fresh token')
abort(login.needs_refresh())
auth.claim_invitations(current_user)
build_list = operations.UserOps(current_user.get_id()).get_builds()
return render_template(
'home.html',
build_list=build_list,
show_video_and_promo_text=app.config['SHOW_VIDEO_AND_PROMO_TEXT']) | [
"def",
"homepage",
"(",
")",
":",
"if",
"current_user",
".",
"is_authenticated",
"(",
")",
":",
"if",
"not",
"login_fresh",
"(",
")",
":",
"logging",
".",
"debug",
"(",
"'User needs a fresh token'",
")",
"abort",
"(",
"login",
".",
"needs_refresh",
"(",
")... | Renders the homepage. | [
"Renders",
"the",
"homepage",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/frontend.py#L55-L68 |
18,586 | bslatkin/dpxdt | dpxdt/server/frontend.py | new_build | def new_build():
"""Page for crediting or editing a build."""
form = forms.BuildForm()
if form.validate_on_submit():
build = models.Build()
form.populate_obj(build)
build.owners.append(current_user)
db.session.add(build)
db.session.flush()
auth.save_admin_log(build, created_build=True, message=build.name)
db.session.commit()
operations.UserOps(current_user.get_id()).evict()
logging.info('Created build via UI: build_id=%r, name=%r',
build.id, build.name)
return redirect(url_for('view_build', id=build.id))
return render_template(
'new_build.html',
build_form=form) | python | def new_build():
form = forms.BuildForm()
if form.validate_on_submit():
build = models.Build()
form.populate_obj(build)
build.owners.append(current_user)
db.session.add(build)
db.session.flush()
auth.save_admin_log(build, created_build=True, message=build.name)
db.session.commit()
operations.UserOps(current_user.get_id()).evict()
logging.info('Created build via UI: build_id=%r, name=%r',
build.id, build.name)
return redirect(url_for('view_build', id=build.id))
return render_template(
'new_build.html',
build_form=form) | [
"def",
"new_build",
"(",
")",
":",
"form",
"=",
"forms",
".",
"BuildForm",
"(",
")",
"if",
"form",
".",
"validate_on_submit",
"(",
")",
":",
"build",
"=",
"models",
".",
"Build",
"(",
")",
"form",
".",
"populate_obj",
"(",
"build",
")",
"build",
".",... | Page for crediting or editing a build. | [
"Page",
"for",
"crediting",
"or",
"editing",
"a",
"build",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/frontend.py#L73-L96 |
18,587 | bslatkin/dpxdt | dpxdt/server/frontend.py | view_build | def view_build():
"""Page for viewing all releases in a build."""
build = g.build
page_size = min(request.args.get('page_size', 10, type=int), 50)
offset = request.args.get('offset', 0, type=int)
ops = operations.BuildOps(build.id)
has_next_page, candidate_list, stats_counts = ops.get_candidates(
page_size, offset)
# Collate by release name, order releases by latest creation. Init stats.
release_dict = {}
created_dict = {}
run_stats_dict = {}
for candidate in candidate_list:
release_list = release_dict.setdefault(candidate.name, [])
release_list.append(candidate)
max_created = created_dict.get(candidate.name, candidate.created)
created_dict[candidate.name] = max(candidate.created, max_created)
run_stats_dict[candidate.id] = dict(
runs_total=0,
runs_complete=0,
runs_successful=0,
runs_failed=0,
runs_baseline=0,
runs_pending=0)
# Sort each release by candidate number descending
for release_list in release_dict.itervalues():
release_list.sort(key=lambda x: x.number, reverse=True)
# Sort all releases by created time descending
release_age_list = [
(value, key) for key, value in created_dict.iteritems()]
release_age_list.sort(reverse=True)
release_name_list = [key for _, key in release_age_list]
# Count totals for each run state within that release.
for candidate_id, status, count in stats_counts:
stats_dict = run_stats_dict[candidate_id]
for key in ops.get_stats_keys(status):
stats_dict[key] += count
return render_template(
'view_build.html',
build=build,
release_name_list=release_name_list,
release_dict=release_dict,
run_stats_dict=run_stats_dict,
has_next_page=has_next_page,
current_offset=offset,
next_offset=offset + page_size,
last_offset=max(0, offset - page_size),
page_size=page_size) | python | def view_build():
build = g.build
page_size = min(request.args.get('page_size', 10, type=int), 50)
offset = request.args.get('offset', 0, type=int)
ops = operations.BuildOps(build.id)
has_next_page, candidate_list, stats_counts = ops.get_candidates(
page_size, offset)
# Collate by release name, order releases by latest creation. Init stats.
release_dict = {}
created_dict = {}
run_stats_dict = {}
for candidate in candidate_list:
release_list = release_dict.setdefault(candidate.name, [])
release_list.append(candidate)
max_created = created_dict.get(candidate.name, candidate.created)
created_dict[candidate.name] = max(candidate.created, max_created)
run_stats_dict[candidate.id] = dict(
runs_total=0,
runs_complete=0,
runs_successful=0,
runs_failed=0,
runs_baseline=0,
runs_pending=0)
# Sort each release by candidate number descending
for release_list in release_dict.itervalues():
release_list.sort(key=lambda x: x.number, reverse=True)
# Sort all releases by created time descending
release_age_list = [
(value, key) for key, value in created_dict.iteritems()]
release_age_list.sort(reverse=True)
release_name_list = [key for _, key in release_age_list]
# Count totals for each run state within that release.
for candidate_id, status, count in stats_counts:
stats_dict = run_stats_dict[candidate_id]
for key in ops.get_stats_keys(status):
stats_dict[key] += count
return render_template(
'view_build.html',
build=build,
release_name_list=release_name_list,
release_dict=release_dict,
run_stats_dict=run_stats_dict,
has_next_page=has_next_page,
current_offset=offset,
next_offset=offset + page_size,
last_offset=max(0, offset - page_size),
page_size=page_size) | [
"def",
"view_build",
"(",
")",
":",
"build",
"=",
"g",
".",
"build",
"page_size",
"=",
"min",
"(",
"request",
".",
"args",
".",
"get",
"(",
"'page_size'",
",",
"10",
",",
"type",
"=",
"int",
")",
",",
"50",
")",
"offset",
"=",
"request",
".",
"ar... | Page for viewing all releases in a build. | [
"Page",
"for",
"viewing",
"all",
"releases",
"in",
"a",
"build",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/frontend.py#L101-L154 |
18,588 | bslatkin/dpxdt | dpxdt/server/frontend.py | view_release | def view_release():
"""Page for viewing all tests runs in a release."""
build = g.build
if request.method == 'POST':
form = forms.ReleaseForm(request.form)
else:
form = forms.ReleaseForm(request.args)
form.validate()
ops = operations.BuildOps(build.id)
release, run_list, stats_dict, approval_log = ops.get_release(
form.name.data, form.number.data)
if not release:
abort(404)
if request.method == 'POST':
decision_states = (
models.Release.REVIEWING,
models.Release.RECEIVING,
models.Release.PROCESSING)
if form.good.data and release.status in decision_states:
release.status = models.Release.GOOD
auth.save_admin_log(build, release_good=True, release=release)
elif form.bad.data and release.status in decision_states:
release.status = models.Release.BAD
auth.save_admin_log(build, release_bad=True, release=release)
elif form.reviewing.data and release.status in (
models.Release.GOOD, models.Release.BAD):
release.status = models.Release.REVIEWING
auth.save_admin_log(build, release_reviewing=True, release=release)
else:
logging.warning(
'Bad state transition for name=%r, number=%r, form=%r',
release.name, release.number, form.data)
abort(400)
db.session.add(release)
db.session.commit()
ops.evict()
return redirect(url_for(
'view_release',
id=build.id,
name=release.name,
number=release.number))
# Update form values for rendering
form.good.data = True
form.bad.data = True
form.reviewing.data = True
return render_template(
'view_release.html',
build=build,
release=release,
run_list=run_list,
release_form=form,
approval_log=approval_log,
stats_dict=stats_dict) | python | def view_release():
build = g.build
if request.method == 'POST':
form = forms.ReleaseForm(request.form)
else:
form = forms.ReleaseForm(request.args)
form.validate()
ops = operations.BuildOps(build.id)
release, run_list, stats_dict, approval_log = ops.get_release(
form.name.data, form.number.data)
if not release:
abort(404)
if request.method == 'POST':
decision_states = (
models.Release.REVIEWING,
models.Release.RECEIVING,
models.Release.PROCESSING)
if form.good.data and release.status in decision_states:
release.status = models.Release.GOOD
auth.save_admin_log(build, release_good=True, release=release)
elif form.bad.data and release.status in decision_states:
release.status = models.Release.BAD
auth.save_admin_log(build, release_bad=True, release=release)
elif form.reviewing.data and release.status in (
models.Release.GOOD, models.Release.BAD):
release.status = models.Release.REVIEWING
auth.save_admin_log(build, release_reviewing=True, release=release)
else:
logging.warning(
'Bad state transition for name=%r, number=%r, form=%r',
release.name, release.number, form.data)
abort(400)
db.session.add(release)
db.session.commit()
ops.evict()
return redirect(url_for(
'view_release',
id=build.id,
name=release.name,
number=release.number))
# Update form values for rendering
form.good.data = True
form.bad.data = True
form.reviewing.data = True
return render_template(
'view_release.html',
build=build,
release=release,
run_list=run_list,
release_form=form,
approval_log=approval_log,
stats_dict=stats_dict) | [
"def",
"view_release",
"(",
")",
":",
"build",
"=",
"g",
".",
"build",
"if",
"request",
".",
"method",
"==",
"'POST'",
":",
"form",
"=",
"forms",
".",
"ReleaseForm",
"(",
"request",
".",
"form",
")",
"else",
":",
"form",
"=",
"forms",
".",
"ReleaseFo... | Page for viewing all tests runs in a release. | [
"Page",
"for",
"viewing",
"all",
"tests",
"runs",
"in",
"a",
"release",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/frontend.py#L159-L221 |
18,589 | bslatkin/dpxdt | dpxdt/server/frontend.py | _get_artifact_context | def _get_artifact_context(run, file_type):
"""Gets the artifact details for the given run and file_type."""
sha1sum = None
image_file = False
log_file = False
config_file = False
if request.path == '/image':
image_file = True
if file_type == 'before':
sha1sum = run.ref_image
elif file_type == 'diff':
sha1sum = run.diff_image
elif file_type == 'after':
sha1sum = run.image
else:
abort(400)
elif request.path == '/log':
log_file = True
if file_type == 'before':
sha1sum = run.ref_log
elif file_type == 'diff':
sha1sum = run.diff_log
elif file_type == 'after':
sha1sum = run.log
else:
abort(400)
elif request.path == '/config':
config_file = True
if file_type == 'before':
sha1sum = run.ref_config
elif file_type == 'after':
sha1sum = run.config
else:
abort(400)
return image_file, log_file, config_file, sha1sum | python | def _get_artifact_context(run, file_type):
sha1sum = None
image_file = False
log_file = False
config_file = False
if request.path == '/image':
image_file = True
if file_type == 'before':
sha1sum = run.ref_image
elif file_type == 'diff':
sha1sum = run.diff_image
elif file_type == 'after':
sha1sum = run.image
else:
abort(400)
elif request.path == '/log':
log_file = True
if file_type == 'before':
sha1sum = run.ref_log
elif file_type == 'diff':
sha1sum = run.diff_log
elif file_type == 'after':
sha1sum = run.log
else:
abort(400)
elif request.path == '/config':
config_file = True
if file_type == 'before':
sha1sum = run.ref_config
elif file_type == 'after':
sha1sum = run.config
else:
abort(400)
return image_file, log_file, config_file, sha1sum | [
"def",
"_get_artifact_context",
"(",
"run",
",",
"file_type",
")",
":",
"sha1sum",
"=",
"None",
"image_file",
"=",
"False",
"log_file",
"=",
"False",
"config_file",
"=",
"False",
"if",
"request",
".",
"path",
"==",
"'/image'",
":",
"image_file",
"=",
"True",... | Gets the artifact details for the given run and file_type. | [
"Gets",
"the",
"artifact",
"details",
"for",
"the",
"given",
"run",
"and",
"file_type",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/frontend.py#L224-L260 |
18,590 | bslatkin/dpxdt | dpxdt/client/workers.py | get_coordinator | def get_coordinator():
"""Creates a coordinator and returns it."""
workflow_queue = Queue.Queue()
complete_queue = Queue.Queue()
coordinator = WorkflowThread(workflow_queue, complete_queue)
coordinator.register(WorkflowItem, workflow_queue)
return coordinator | python | def get_coordinator():
workflow_queue = Queue.Queue()
complete_queue = Queue.Queue()
coordinator = WorkflowThread(workflow_queue, complete_queue)
coordinator.register(WorkflowItem, workflow_queue)
return coordinator | [
"def",
"get_coordinator",
"(",
")",
":",
"workflow_queue",
"=",
"Queue",
".",
"Queue",
"(",
")",
"complete_queue",
"=",
"Queue",
".",
"Queue",
"(",
")",
"coordinator",
"=",
"WorkflowThread",
"(",
"workflow_queue",
",",
"complete_queue",
")",
"coordinator",
"."... | Creates a coordinator and returns it. | [
"Creates",
"a",
"coordinator",
"and",
"returns",
"it",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/client/workers.py#L553-L559 |
18,591 | bslatkin/dpxdt | dpxdt/client/workers.py | WorkItem._print_repr | def _print_repr(self, depth):
"""Print this WorkItem to the given stack depth.
The depth parameter ensures that we can print WorkItems in
arbitrarily long chains without hitting the max stack depth.
This can happen with WaitForUrlWorkflowItems, which
create long chains of small waits.
"""
if depth <= 0:
return '%s.%s#%d' % (
self.__class__.__module__,
self.__class__.__name__,
id(self))
return '%s.%s(%s)#%d' % (
self.__class__.__module__,
self.__class__.__name__,
self._print_tree(self._get_dict_for_repr(), depth - 1),
id(self)) | python | def _print_repr(self, depth):
if depth <= 0:
return '%s.%s#%d' % (
self.__class__.__module__,
self.__class__.__name__,
id(self))
return '%s.%s(%s)#%d' % (
self.__class__.__module__,
self.__class__.__name__,
self._print_tree(self._get_dict_for_repr(), depth - 1),
id(self)) | [
"def",
"_print_repr",
"(",
"self",
",",
"depth",
")",
":",
"if",
"depth",
"<=",
"0",
":",
"return",
"'%s.%s#%d'",
"%",
"(",
"self",
".",
"__class__",
".",
"__module__",
",",
"self",
".",
"__class__",
".",
"__name__",
",",
"id",
"(",
"self",
")",
")",... | Print this WorkItem to the given stack depth.
The depth parameter ensures that we can print WorkItems in
arbitrarily long chains without hitting the max stack depth.
This can happen with WaitForUrlWorkflowItems, which
create long chains of small waits. | [
"Print",
"this",
"WorkItem",
"to",
"the",
"given",
"stack",
"depth",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/client/workers.py#L74-L92 |
18,592 | bslatkin/dpxdt | dpxdt/client/workers.py | ResultList.error | def error(self):
"""Returns the error for this barrier and all work items, if any."""
# Copy the error from any failed item to be the error for the whole
# barrier. The first error seen "wins". Also handles the case where
# the WorkItems passed into the barrier have already completed and
# been marked with errors.
for item in self:
if isinstance(item, WorkItem) and item.error:
return item.error
return None | python | def error(self):
# Copy the error from any failed item to be the error for the whole
# barrier. The first error seen "wins". Also handles the case where
# the WorkItems passed into the barrier have already completed and
# been marked with errors.
for item in self:
if isinstance(item, WorkItem) and item.error:
return item.error
return None | [
"def",
"error",
"(",
"self",
")",
":",
"# Copy the error from any failed item to be the error for the whole",
"# barrier. The first error seen \"wins\". Also handles the case where",
"# the WorkItems passed into the barrier have already completed and",
"# been marked with errors.",
"for",
"ite... | Returns the error for this barrier and all work items, if any. | [
"Returns",
"the",
"error",
"for",
"this",
"barrier",
"and",
"all",
"work",
"items",
"if",
"any",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/client/workers.py#L227-L236 |
18,593 | bslatkin/dpxdt | dpxdt/client/workers.py | Barrier.outstanding | def outstanding(self):
"""Returns whether or not this barrier has pending work."""
# Allow the same WorkItem to be yielded multiple times but not
# count towards blocking the barrier.
done_count = 0
for item in self:
if not self.wait_any and item.fire_and_forget:
# Only count fire_and_forget items as done if this is
# *not* a WaitAny barrier. We only want to return control
# to the caller when at least one of the blocking items
# has completed.
done_count += 1
elif item.done:
done_count += 1
if self.wait_any and done_count > 0:
return False
if done_count == len(self):
return False
return True | python | def outstanding(self):
# Allow the same WorkItem to be yielded multiple times but not
# count towards blocking the barrier.
done_count = 0
for item in self:
if not self.wait_any and item.fire_and_forget:
# Only count fire_and_forget items as done if this is
# *not* a WaitAny barrier. We only want to return control
# to the caller when at least one of the blocking items
# has completed.
done_count += 1
elif item.done:
done_count += 1
if self.wait_any and done_count > 0:
return False
if done_count == len(self):
return False
return True | [
"def",
"outstanding",
"(",
"self",
")",
":",
"# Allow the same WorkItem to be yielded multiple times but not",
"# count towards blocking the barrier.",
"done_count",
"=",
"0",
"for",
"item",
"in",
"self",
":",
"if",
"not",
"self",
".",
"wait_any",
"and",
"item",
".",
... | Returns whether or not this barrier has pending work. | [
"Returns",
"whether",
"or",
"not",
"this",
"barrier",
"has",
"pending",
"work",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/client/workers.py#L274-L295 |
18,594 | bslatkin/dpxdt | dpxdt/client/workers.py | Barrier.get_item | def get_item(self):
"""Returns the item to send back into the workflow generator."""
if self.was_list:
result = ResultList()
for item in self:
if isinstance(item, WorkflowItem):
if item.done and not item.error:
result.append(item.result)
else:
# When there's an error or the workflow isn't done yet,
# just return the original WorkflowItem so the caller
# can inspect its entire state.
result.append(item)
else:
result.append(item)
return result
else:
return self[0] | python | def get_item(self):
if self.was_list:
result = ResultList()
for item in self:
if isinstance(item, WorkflowItem):
if item.done and not item.error:
result.append(item.result)
else:
# When there's an error or the workflow isn't done yet,
# just return the original WorkflowItem so the caller
# can inspect its entire state.
result.append(item)
else:
result.append(item)
return result
else:
return self[0] | [
"def",
"get_item",
"(",
"self",
")",
":",
"if",
"self",
".",
"was_list",
":",
"result",
"=",
"ResultList",
"(",
")",
"for",
"item",
"in",
"self",
":",
"if",
"isinstance",
"(",
"item",
",",
"WorkflowItem",
")",
":",
"if",
"item",
".",
"done",
"and",
... | Returns the item to send back into the workflow generator. | [
"Returns",
"the",
"item",
"to",
"send",
"back",
"into",
"the",
"workflow",
"generator",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/client/workers.py#L297-L314 |
18,595 | bslatkin/dpxdt | dpxdt/client/workers.py | WorkflowThread.start | def start(self):
"""Starts the coordinator thread and all related worker threads."""
assert not self.interrupted
for thread in self.worker_threads:
thread.start()
WorkerThread.start(self) | python | def start(self):
assert not self.interrupted
for thread in self.worker_threads:
thread.start()
WorkerThread.start(self) | [
"def",
"start",
"(",
"self",
")",
":",
"assert",
"not",
"self",
".",
"interrupted",
"for",
"thread",
"in",
"self",
".",
"worker_threads",
":",
"thread",
".",
"start",
"(",
")",
"WorkerThread",
".",
"start",
"(",
"self",
")"
] | Starts the coordinator thread and all related worker threads. | [
"Starts",
"the",
"coordinator",
"thread",
"and",
"all",
"related",
"worker",
"threads",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/client/workers.py#L429-L434 |
18,596 | bslatkin/dpxdt | dpxdt/client/workers.py | WorkflowThread.stop | def stop(self):
"""Stops the coordinator thread and all related threads."""
if self.interrupted:
return
for thread in self.worker_threads:
thread.interrupted = True
self.interrupted = True | python | def stop(self):
if self.interrupted:
return
for thread in self.worker_threads:
thread.interrupted = True
self.interrupted = True | [
"def",
"stop",
"(",
"self",
")",
":",
"if",
"self",
".",
"interrupted",
":",
"return",
"for",
"thread",
"in",
"self",
".",
"worker_threads",
":",
"thread",
".",
"interrupted",
"=",
"True",
"self",
".",
"interrupted",
"=",
"True"
] | Stops the coordinator thread and all related threads. | [
"Stops",
"the",
"coordinator",
"thread",
"and",
"all",
"related",
"threads",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/client/workers.py#L436-L442 |
18,597 | bslatkin/dpxdt | dpxdt/client/workers.py | WorkflowThread.join | def join(self):
"""Joins the coordinator thread and all worker threads."""
for thread in self.worker_threads:
thread.join()
WorkerThread.join(self) | python | def join(self):
for thread in self.worker_threads:
thread.join()
WorkerThread.join(self) | [
"def",
"join",
"(",
"self",
")",
":",
"for",
"thread",
"in",
"self",
".",
"worker_threads",
":",
"thread",
".",
"join",
"(",
")",
"WorkerThread",
".",
"join",
"(",
"self",
")"
] | Joins the coordinator thread and all worker threads. | [
"Joins",
"the",
"coordinator",
"thread",
"and",
"all",
"worker",
"threads",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/client/workers.py#L444-L448 |
18,598 | bslatkin/dpxdt | dpxdt/client/workers.py | WorkflowThread.wait_one | def wait_one(self):
"""Waits until this worker has finished one work item or died."""
while True:
try:
item = self.output_queue.get(True, self.polltime)
except Queue.Empty:
continue
except KeyboardInterrupt:
LOGGER.debug('Exiting')
return
else:
item.check_result()
return | python | def wait_one(self):
while True:
try:
item = self.output_queue.get(True, self.polltime)
except Queue.Empty:
continue
except KeyboardInterrupt:
LOGGER.debug('Exiting')
return
else:
item.check_result()
return | [
"def",
"wait_one",
"(",
"self",
")",
":",
"while",
"True",
":",
"try",
":",
"item",
"=",
"self",
".",
"output_queue",
".",
"get",
"(",
"True",
",",
"self",
".",
"polltime",
")",
"except",
"Queue",
".",
"Empty",
":",
"continue",
"except",
"KeyboardInter... | Waits until this worker has finished one work item or died. | [
"Waits",
"until",
"this",
"worker",
"has",
"finished",
"one",
"work",
"item",
"or",
"died",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/client/workers.py#L450-L462 |
18,599 | bslatkin/dpxdt | dpxdt/server/auth.py | superuser_required | def superuser_required(f):
"""Requires the requestor to be a super user."""
@functools.wraps(f)
@login_required
def wrapped(*args, **kwargs):
if not (current_user.is_authenticated() and current_user.superuser):
abort(403)
return f(*args, **kwargs)
return wrapped | python | def superuser_required(f):
@functools.wraps(f)
@login_required
def wrapped(*args, **kwargs):
if not (current_user.is_authenticated() and current_user.superuser):
abort(403)
return f(*args, **kwargs)
return wrapped | [
"def",
"superuser_required",
"(",
"f",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"@",
"login_required",
"def",
"wrapped",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"(",
"current_user",
".",
"is_authenticated",
"("... | Requires the requestor to be a super user. | [
"Requires",
"the",
"requestor",
"to",
"be",
"a",
"super",
"user",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/auth.py#L174-L182 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.