repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
SuperCowPowers/workbench | workbench/server/els_indexer.py | ELSStubIndexer.index_data | def index_data(self, data, index_name, doc_type):
"""Index data in Stub Indexer."""
print 'ELS Stub Indexer getting called...'
print '%s %s %s %s' % (self, data, index_name, doc_type) | python | def index_data(self, data, index_name, doc_type):
"""Index data in Stub Indexer."""
print 'ELS Stub Indexer getting called...'
print '%s %s %s %s' % (self, data, index_name, doc_type) | [
"def",
"index_data",
"(",
"self",
",",
"data",
",",
"index_name",
",",
"doc_type",
")",
":",
"print",
"'ELS Stub Indexer getting called...'",
"print",
"'%s %s %s %s'",
"%",
"(",
"self",
",",
"data",
",",
"index_name",
",",
"doc_type",
")"
] | Index data in Stub Indexer. | [
"Index",
"data",
"in",
"Stub",
"Indexer",
"."
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/server/els_indexer.py#L86-L90 | train | 43,200 |
SuperCowPowers/workbench | workbench/workers/help_formatter.py | HelpFormatter.execute | def execute(self, input_data):
''' Do CLI formatting and coloring based on the type_tag '''
input_data = input_data['help_base']
type_tag = input_data['type_tag']
# Standard help text
if type_tag == 'help':
output = '%s%s%s' % (color.LightBlue, input_data['help'], color.Normal)
# Worker
elif type_tag == 'worker':
output = '%s%s' % (color.Yellow, input_data['name'])
output += '\n %sInput: %s%s%s' % (color.LightBlue, color.Green, input_data['dependencies'], color.Normal)
output += '\n %s%s' % (color.Green, input_data['docstring'])
# Command
elif type_tag == 'command':
output = '%s%s%s %s' % (color.Yellow, input_data['command'], color.LightBlue, input_data['sig'])
output += '\n %s%s%s' % (color.Green, input_data['docstring'], color.Normal)
# WTF: Alert on unknown type_tag and return a string of the input_data
else:
print 'Alert: help_formatter worker received malformed object: %s' % str(input_data)
output = '\n%s%s%s' % (color.Red, str(input_data), color.Normal)
# Return the formatted and colored help
return {'help': output} | python | def execute(self, input_data):
''' Do CLI formatting and coloring based on the type_tag '''
input_data = input_data['help_base']
type_tag = input_data['type_tag']
# Standard help text
if type_tag == 'help':
output = '%s%s%s' % (color.LightBlue, input_data['help'], color.Normal)
# Worker
elif type_tag == 'worker':
output = '%s%s' % (color.Yellow, input_data['name'])
output += '\n %sInput: %s%s%s' % (color.LightBlue, color.Green, input_data['dependencies'], color.Normal)
output += '\n %s%s' % (color.Green, input_data['docstring'])
# Command
elif type_tag == 'command':
output = '%s%s%s %s' % (color.Yellow, input_data['command'], color.LightBlue, input_data['sig'])
output += '\n %s%s%s' % (color.Green, input_data['docstring'], color.Normal)
# WTF: Alert on unknown type_tag and return a string of the input_data
else:
print 'Alert: help_formatter worker received malformed object: %s' % str(input_data)
output = '\n%s%s%s' % (color.Red, str(input_data), color.Normal)
# Return the formatted and colored help
return {'help': output} | [
"def",
"execute",
"(",
"self",
",",
"input_data",
")",
":",
"input_data",
"=",
"input_data",
"[",
"'help_base'",
"]",
"type_tag",
"=",
"input_data",
"[",
"'type_tag'",
"]",
"# Standard help text",
"if",
"type_tag",
"==",
"'help'",
":",
"output",
"=",
"'%s%s%s'... | Do CLI formatting and coloring based on the type_tag | [
"Do",
"CLI",
"formatting",
"and",
"coloring",
"based",
"on",
"the",
"type_tag"
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/workers/help_formatter.py#L11-L37 | train | 43,201 |
SuperCowPowers/workbench | workbench/server/workbench_server.py | run | def run():
""" Run the workbench server """
# Load the configuration file relative to this script location
config_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'config.ini')
workbench_conf = ConfigParser.ConfigParser()
config_ini = workbench_conf.read(config_path)
if not config_ini:
print 'Could not locate config.ini file, tried %s : exiting...' % config_path
exit(1)
# Pull configuration settings
datastore_uri = workbench_conf.get('workbench', 'datastore_uri')
database = workbench_conf.get('workbench', 'database')
worker_cap = workbench_conf.getint('workbench', 'worker_cap')
samples_cap = workbench_conf.getint('workbench', 'samples_cap')
# Spin up Workbench ZeroRPC
try:
store_args = {'uri': datastore_uri, 'database': database, 'worker_cap':worker_cap, 'samples_cap':samples_cap}
workbench = zerorpc.Server(WorkBench(store_args=store_args), name='workbench', heartbeat=60)
workbench.bind('tcp://0.0.0.0:4242')
print '\nWorkbench is ready and feeling super duper!'
gevent_signal(signal.SIGTERM, workbench.stop)
gevent_signal(signal.SIGINT, workbench.stop)
gevent_signal(signal.SIGKILL, workbench.stop)
workbench.run()
print '\nWorkbench Server Shutting Down... and dreaming of sheep...'
except zmq.error.ZMQError:
print '\nInfo: Could not start Workbench server (no worries, probably already running...)\n' | python | def run():
""" Run the workbench server """
# Load the configuration file relative to this script location
config_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'config.ini')
workbench_conf = ConfigParser.ConfigParser()
config_ini = workbench_conf.read(config_path)
if not config_ini:
print 'Could not locate config.ini file, tried %s : exiting...' % config_path
exit(1)
# Pull configuration settings
datastore_uri = workbench_conf.get('workbench', 'datastore_uri')
database = workbench_conf.get('workbench', 'database')
worker_cap = workbench_conf.getint('workbench', 'worker_cap')
samples_cap = workbench_conf.getint('workbench', 'samples_cap')
# Spin up Workbench ZeroRPC
try:
store_args = {'uri': datastore_uri, 'database': database, 'worker_cap':worker_cap, 'samples_cap':samples_cap}
workbench = zerorpc.Server(WorkBench(store_args=store_args), name='workbench', heartbeat=60)
workbench.bind('tcp://0.0.0.0:4242')
print '\nWorkbench is ready and feeling super duper!'
gevent_signal(signal.SIGTERM, workbench.stop)
gevent_signal(signal.SIGINT, workbench.stop)
gevent_signal(signal.SIGKILL, workbench.stop)
workbench.run()
print '\nWorkbench Server Shutting Down... and dreaming of sheep...'
except zmq.error.ZMQError:
print '\nInfo: Could not start Workbench server (no worries, probably already running...)\n' | [
"def",
"run",
"(",
")",
":",
"# Load the configuration file relative to this script location",
"config_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"realpath",
"(",
"__file__",
")",
")",
","... | Run the workbench server | [
"Run",
"the",
"workbench",
"server"
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/server/workbench_server.py#L844-L874 | train | 43,202 |
SuperCowPowers/workbench | workbench/server/workbench_server.py | WorkBench.combine_samples | def combine_samples(self, md5_list, filename, type_tag):
"""Combine samples together. This may have various use cases the most significant
involving a bunch of sample 'chunks' got uploaded and now we combine them together
Args:
md5_list: The list of md5s to combine, order matters!
filename: name of the file (used purely as meta data not for lookup)
type_tag: ('exe','pcap','pdf','json','swf', or ...)
Returns:
the computed md5 of the combined samples
"""
total_bytes = ""
for md5 in md5_list:
total_bytes += self.get_sample(md5)['sample']['raw_bytes']
self.remove_sample(md5)
# Store it
return self.store_sample(total_bytes, filename, type_tag) | python | def combine_samples(self, md5_list, filename, type_tag):
"""Combine samples together. This may have various use cases the most significant
involving a bunch of sample 'chunks' got uploaded and now we combine them together
Args:
md5_list: The list of md5s to combine, order matters!
filename: name of the file (used purely as meta data not for lookup)
type_tag: ('exe','pcap','pdf','json','swf', or ...)
Returns:
the computed md5 of the combined samples
"""
total_bytes = ""
for md5 in md5_list:
total_bytes += self.get_sample(md5)['sample']['raw_bytes']
self.remove_sample(md5)
# Store it
return self.store_sample(total_bytes, filename, type_tag) | [
"def",
"combine_samples",
"(",
"self",
",",
"md5_list",
",",
"filename",
",",
"type_tag",
")",
":",
"total_bytes",
"=",
"\"\"",
"for",
"md5",
"in",
"md5_list",
":",
"total_bytes",
"+=",
"self",
".",
"get_sample",
"(",
"md5",
")",
"[",
"'sample'",
"]",
"[... | Combine samples together. This may have various use cases the most significant
involving a bunch of sample 'chunks' got uploaded and now we combine them together
Args:
md5_list: The list of md5s to combine, order matters!
filename: name of the file (used purely as meta data not for lookup)
type_tag: ('exe','pcap','pdf','json','swf', or ...)
Returns:
the computed md5 of the combined samples | [
"Combine",
"samples",
"together",
".",
"This",
"may",
"have",
"various",
"use",
"cases",
"the",
"most",
"significant",
"involving",
"a",
"bunch",
"of",
"sample",
"chunks",
"got",
"uploaded",
"and",
"now",
"we",
"combine",
"them",
"together"
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/server/workbench_server.py#L184-L201 | train | 43,203 |
SuperCowPowers/workbench | workbench/server/workbench_server.py | WorkBench.guess_type_tag | def guess_type_tag(self, input_bytes, filename):
""" Try to guess the type_tag for this sample """
mime_to_type = {'application/jar': 'jar',
'application/java-archive': 'jar',
'application/octet-stream': 'data',
'application/pdf': 'pdf',
'application/vnd.ms-cab-compressed': 'cab',
'application/vnd.ms-fontobject': 'ms_font',
'application/vnd.tcpdump.pcap': 'pcap',
'application/x-dosexec': 'exe',
'application/x-empty': 'empty',
'application/x-shockwave-flash': 'swf',
'application/xml': 'xml',
'application/zip': 'zip',
'image/gif': 'gif',
'text/html': 'html',
'image/jpeg': 'jpg',
'image/png': 'png',
'image/x-icon': 'icon',
'text/plain': 'txt'
}
# See what filemagic can determine
with magic.Magic(flags=magic.MAGIC_MIME_TYPE) as mag:
mime_type = mag.id_buffer(input_bytes[:1024])
if mime_type in mime_to_type:
type_tag = mime_to_type[mime_type]
# If we get 'data' back look at the filename
if type_tag == 'data':
print 'Info: File -- Trying to Determine Type from filename...'
ext = os.path.splitext(filename)[1][1:]
if ext in ['mem','vmem']:
type_tag = 'mem'
else:
print 'Alert: Failed to Determine Type for %s' % filename
exit(1) # Temp
return type_tag
else:
print 'Alert: Sample Type could not be Determined'
return 'unknown' | python | def guess_type_tag(self, input_bytes, filename):
""" Try to guess the type_tag for this sample """
mime_to_type = {'application/jar': 'jar',
'application/java-archive': 'jar',
'application/octet-stream': 'data',
'application/pdf': 'pdf',
'application/vnd.ms-cab-compressed': 'cab',
'application/vnd.ms-fontobject': 'ms_font',
'application/vnd.tcpdump.pcap': 'pcap',
'application/x-dosexec': 'exe',
'application/x-empty': 'empty',
'application/x-shockwave-flash': 'swf',
'application/xml': 'xml',
'application/zip': 'zip',
'image/gif': 'gif',
'text/html': 'html',
'image/jpeg': 'jpg',
'image/png': 'png',
'image/x-icon': 'icon',
'text/plain': 'txt'
}
# See what filemagic can determine
with magic.Magic(flags=magic.MAGIC_MIME_TYPE) as mag:
mime_type = mag.id_buffer(input_bytes[:1024])
if mime_type in mime_to_type:
type_tag = mime_to_type[mime_type]
# If we get 'data' back look at the filename
if type_tag == 'data':
print 'Info: File -- Trying to Determine Type from filename...'
ext = os.path.splitext(filename)[1][1:]
if ext in ['mem','vmem']:
type_tag = 'mem'
else:
print 'Alert: Failed to Determine Type for %s' % filename
exit(1) # Temp
return type_tag
else:
print 'Alert: Sample Type could not be Determined'
return 'unknown' | [
"def",
"guess_type_tag",
"(",
"self",
",",
"input_bytes",
",",
"filename",
")",
":",
"mime_to_type",
"=",
"{",
"'application/jar'",
":",
"'jar'",
",",
"'application/java-archive'",
":",
"'jar'",
",",
"'application/octet-stream'",
":",
"'data'",
",",
"'application/pd... | Try to guess the type_tag for this sample | [
"Try",
"to",
"guess",
"the",
"type_tag",
"for",
"this",
"sample"
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/server/workbench_server.py#L271-L311 | train | 43,204 |
SuperCowPowers/workbench | workbench/server/workbench_server.py | WorkBench.add_tags | def add_tags(self, md5, tags):
"""Add tags to this sample"""
if not tags: return
tag_set = set(self.get_tags(md5)) if self.get_tags(md5) else set()
if isinstance(tags, str):
tags = [tags]
for tag in tags:
tag_set.add(tag)
self.data_store.store_work_results({'tags': list(tag_set)}, 'tags', md5) | python | def add_tags(self, md5, tags):
"""Add tags to this sample"""
if not tags: return
tag_set = set(self.get_tags(md5)) if self.get_tags(md5) else set()
if isinstance(tags, str):
tags = [tags]
for tag in tags:
tag_set.add(tag)
self.data_store.store_work_results({'tags': list(tag_set)}, 'tags', md5) | [
"def",
"add_tags",
"(",
"self",
",",
"md5",
",",
"tags",
")",
":",
"if",
"not",
"tags",
":",
"return",
"tag_set",
"=",
"set",
"(",
"self",
".",
"get_tags",
"(",
"md5",
")",
")",
"if",
"self",
".",
"get_tags",
"(",
"md5",
")",
"else",
"set",
"(",
... | Add tags to this sample | [
"Add",
"tags",
"to",
"this",
"sample"
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/server/workbench_server.py#L313-L321 | train | 43,205 |
SuperCowPowers/workbench | workbench/server/workbench_server.py | WorkBench.set_tags | def set_tags(self, md5, tags):
"""Set the tags for this sample"""
if isinstance(tags, str):
tags = [tags]
tag_set = set(tags)
self.data_store.store_work_results({'tags': list(tag_set)}, 'tags', md5) | python | def set_tags(self, md5, tags):
"""Set the tags for this sample"""
if isinstance(tags, str):
tags = [tags]
tag_set = set(tags)
self.data_store.store_work_results({'tags': list(tag_set)}, 'tags', md5) | [
"def",
"set_tags",
"(",
"self",
",",
"md5",
",",
"tags",
")",
":",
"if",
"isinstance",
"(",
"tags",
",",
"str",
")",
":",
"tags",
"=",
"[",
"tags",
"]",
"tag_set",
"=",
"set",
"(",
"tags",
")",
"self",
".",
"data_store",
".",
"store_work_results",
... | Set the tags for this sample | [
"Set",
"the",
"tags",
"for",
"this",
"sample"
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/server/workbench_server.py#L323-L328 | train | 43,206 |
SuperCowPowers/workbench | workbench/server/workbench_server.py | WorkBench.get_tags | def get_tags(self, md5):
"""Get tags for this sample"""
tag_data = self.data_store.get_work_results('tags', md5)
return tag_data['tags'] if tag_data else None | python | def get_tags(self, md5):
"""Get tags for this sample"""
tag_data = self.data_store.get_work_results('tags', md5)
return tag_data['tags'] if tag_data else None | [
"def",
"get_tags",
"(",
"self",
",",
"md5",
")",
":",
"tag_data",
"=",
"self",
".",
"data_store",
".",
"get_work_results",
"(",
"'tags'",
",",
"md5",
")",
"return",
"tag_data",
"[",
"'tags'",
"]",
"if",
"tag_data",
"else",
"None"
] | Get tags for this sample | [
"Get",
"tags",
"for",
"this",
"sample"
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/server/workbench_server.py#L330-L333 | train | 43,207 |
SuperCowPowers/workbench | workbench/server/workbench_server.py | WorkBench.generate_sample_set | def generate_sample_set(self, tags=None):
"""Generate a sample_set that maches the tags or all if tags are not specified.
Args:
tags: Match samples against this tag list (or all if not specified)
Returns:
The sample_set of those samples matching the tags
"""
if isinstance(tags, str):
tags = [tags]
md5_list = self.data_store.tag_match(tags)
return self.store_sample_set(md5_list) | python | def generate_sample_set(self, tags=None):
"""Generate a sample_set that maches the tags or all if tags are not specified.
Args:
tags: Match samples against this tag list (or all if not specified)
Returns:
The sample_set of those samples matching the tags
"""
if isinstance(tags, str):
tags = [tags]
md5_list = self.data_store.tag_match(tags)
return self.store_sample_set(md5_list) | [
"def",
"generate_sample_set",
"(",
"self",
",",
"tags",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"tags",
",",
"str",
")",
":",
"tags",
"=",
"[",
"tags",
"]",
"md5_list",
"=",
"self",
".",
"data_store",
".",
"tag_match",
"(",
"tags",
")",
"retu... | Generate a sample_set that maches the tags or all if tags are not specified.
Args:
tags: Match samples against this tag list (or all if not specified)
Returns:
The sample_set of those samples matching the tags | [
"Generate",
"a",
"sample_set",
"that",
"maches",
"the",
"tags",
"or",
"all",
"if",
"tags",
"are",
"not",
"specified",
"."
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/server/workbench_server.py#L558-L570 | train | 43,208 |
SuperCowPowers/workbench | workbench/server/workbench_server.py | WorkBench.help | def help(self, topic=None):
""" Returns the formatted, colored help """
if not topic:
topic = 'workbench'
# It's possible to ask for help on something that doesn't exist
# so we'll catch the exception and push back an object that
# indicates we didn't find what they were asking for
try:
return self.work_request('help_formatter', topic)['help_formatter']['help']
except WorkBench.DataNotFound as e:
# Okay this is a bit tricky we want to give the user a nice error
# message that has both the md5 of what they were looking for and
# a nice informative message that explains what might have happened
sample_md5 = e.args[0]
return '%s%s\n\t%s%s%s' % (color.Yellow, sample_md5, color.Green, e.message(), color.Normal) | python | def help(self, topic=None):
""" Returns the formatted, colored help """
if not topic:
topic = 'workbench'
# It's possible to ask for help on something that doesn't exist
# so we'll catch the exception and push back an object that
# indicates we didn't find what they were asking for
try:
return self.work_request('help_formatter', topic)['help_formatter']['help']
except WorkBench.DataNotFound as e:
# Okay this is a bit tricky we want to give the user a nice error
# message that has both the md5 of what they were looking for and
# a nice informative message that explains what might have happened
sample_md5 = e.args[0]
return '%s%s\n\t%s%s%s' % (color.Yellow, sample_md5, color.Green, e.message(), color.Normal) | [
"def",
"help",
"(",
"self",
",",
"topic",
"=",
"None",
")",
":",
"if",
"not",
"topic",
":",
"topic",
"=",
"'workbench'",
"# It's possible to ask for help on something that doesn't exist",
"# so we'll catch the exception and push back an object that",
"# indicates we didn't find... | Returns the formatted, colored help | [
"Returns",
"the",
"formatted",
"colored",
"help"
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/server/workbench_server.py#L611-L627 | train | 43,209 |
SuperCowPowers/workbench | workbench/server/workbench_server.py | WorkBench._help_workbench | def _help_workbench(self):
""" Help on Workbench """
help = '%sWelcome to Workbench Help:%s' % (color.Yellow, color.Normal)
help += '\n\t%s- workbench.help(\'basic\') %s for getting started help' % (color.Green, color.LightBlue)
help += '\n\t%s- workbench.help(\'workers\') %s for help on available workers' % (color.Green, color.LightBlue)
help += '\n\t%s- workbench.help(\'commands\') %s for help on workbench commands' % (color.Green, color.LightBlue)
help += '\n\t%s- workbench.help(topic) %s where topic can be a help, command or worker' % (color.Green, color.LightBlue)
help += '\n\n%sSee http://github.com/SuperCowPowers/workbench for more information\n%s' % (color.Yellow, color.Normal)
return help | python | def _help_workbench(self):
""" Help on Workbench """
help = '%sWelcome to Workbench Help:%s' % (color.Yellow, color.Normal)
help += '\n\t%s- workbench.help(\'basic\') %s for getting started help' % (color.Green, color.LightBlue)
help += '\n\t%s- workbench.help(\'workers\') %s for help on available workers' % (color.Green, color.LightBlue)
help += '\n\t%s- workbench.help(\'commands\') %s for help on workbench commands' % (color.Green, color.LightBlue)
help += '\n\t%s- workbench.help(topic) %s where topic can be a help, command or worker' % (color.Green, color.LightBlue)
help += '\n\n%sSee http://github.com/SuperCowPowers/workbench for more information\n%s' % (color.Yellow, color.Normal)
return help | [
"def",
"_help_workbench",
"(",
"self",
")",
":",
"help",
"=",
"'%sWelcome to Workbench Help:%s'",
"%",
"(",
"color",
".",
"Yellow",
",",
"color",
".",
"Normal",
")",
"help",
"+=",
"'\\n\\t%s- workbench.help(\\'basic\\') %s for getting started help'",
"%",
"(",
"color"... | Help on Workbench | [
"Help",
"on",
"Workbench"
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/server/workbench_server.py#L630-L638 | train | 43,210 |
SuperCowPowers/workbench | workbench/server/workbench_server.py | WorkBench._help_basic | def _help_basic(self):
""" Help for Workbench Basics """
help = '%sWorkbench: Getting started...' % (color.Yellow)
help += '\n%sStore a sample into Workbench:' % (color.Green)
help += '\n\t%s$ workbench.store_sample(raw_bytes, filename, type_tag)' % (color.LightBlue)
help += '\n\n%sNotice store_sample returns an md5 of the sample...'% (color.Yellow)
help += '\n%sRun workers on the sample (view, meta, whatever...):' % (color.Green)
help += '\n\t%s$ workbench.work_request(\'view\', md5)%s' % (color.LightBlue, color.Normal)
return help | python | def _help_basic(self):
""" Help for Workbench Basics """
help = '%sWorkbench: Getting started...' % (color.Yellow)
help += '\n%sStore a sample into Workbench:' % (color.Green)
help += '\n\t%s$ workbench.store_sample(raw_bytes, filename, type_tag)' % (color.LightBlue)
help += '\n\n%sNotice store_sample returns an md5 of the sample...'% (color.Yellow)
help += '\n%sRun workers on the sample (view, meta, whatever...):' % (color.Green)
help += '\n\t%s$ workbench.work_request(\'view\', md5)%s' % (color.LightBlue, color.Normal)
return help | [
"def",
"_help_basic",
"(",
"self",
")",
":",
"help",
"=",
"'%sWorkbench: Getting started...'",
"%",
"(",
"color",
".",
"Yellow",
")",
"help",
"+=",
"'\\n%sStore a sample into Workbench:'",
"%",
"(",
"color",
".",
"Green",
")",
"help",
"+=",
"'\\n\\t%s$ workbench.s... | Help for Workbench Basics | [
"Help",
"for",
"Workbench",
"Basics"
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/server/workbench_server.py#L640-L648 | train | 43,211 |
SuperCowPowers/workbench | workbench/server/workbench_server.py | WorkBench._help_commands | def _help_commands(self):
""" Help on all the available commands """
help = 'Workbench Commands:'
for command in self.list_all_commands():
full_help = self.work_request('help_formatter', command)['help_formatter']['help']
compact_help = full_help.split('\n')[:2]
help += '\n\n%s' % '\n'.join(compact_help)
return help | python | def _help_commands(self):
""" Help on all the available commands """
help = 'Workbench Commands:'
for command in self.list_all_commands():
full_help = self.work_request('help_formatter', command)['help_formatter']['help']
compact_help = full_help.split('\n')[:2]
help += '\n\n%s' % '\n'.join(compact_help)
return help | [
"def",
"_help_commands",
"(",
"self",
")",
":",
"help",
"=",
"'Workbench Commands:'",
"for",
"command",
"in",
"self",
".",
"list_all_commands",
"(",
")",
":",
"full_help",
"=",
"self",
".",
"work_request",
"(",
"'help_formatter'",
",",
"command",
")",
"[",
"... | Help on all the available commands | [
"Help",
"on",
"all",
"the",
"available",
"commands"
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/server/workbench_server.py#L650-L657 | train | 43,212 |
SuperCowPowers/workbench | workbench/server/workbench_server.py | WorkBench._help_workers | def _help_workers(self):
""" Help on all the available workers """
help = 'Workbench Workers:'
for worker in self.list_all_workers():
full_help = self.work_request('help_formatter', worker)['help_formatter']['help']
compact_help = full_help.split('\n')[:4]
help += '\n\n%s' % '\n'.join(compact_help)
return help | python | def _help_workers(self):
""" Help on all the available workers """
help = 'Workbench Workers:'
for worker in self.list_all_workers():
full_help = self.work_request('help_formatter', worker)['help_formatter']['help']
compact_help = full_help.split('\n')[:4]
help += '\n\n%s' % '\n'.join(compact_help)
return help | [
"def",
"_help_workers",
"(",
"self",
")",
":",
"help",
"=",
"'Workbench Workers:'",
"for",
"worker",
"in",
"self",
".",
"list_all_workers",
"(",
")",
":",
"full_help",
"=",
"self",
".",
"work_request",
"(",
"'help_formatter'",
",",
"worker",
")",
"[",
"'help... | Help on all the available workers | [
"Help",
"on",
"all",
"the",
"available",
"workers"
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/server/workbench_server.py#L659-L666 | train | 43,213 |
SuperCowPowers/workbench | workbench/server/workbench_server.py | WorkBench.get_info | def get_info(self, component):
""" Get the information about this component """
# Grab it, clean it and ship it
work_results = self._get_work_results('info', component)
return self.data_store.clean_for_serialization(work_results) | python | def get_info(self, component):
""" Get the information about this component """
# Grab it, clean it and ship it
work_results = self._get_work_results('info', component)
return self.data_store.clean_for_serialization(work_results) | [
"def",
"get_info",
"(",
"self",
",",
"component",
")",
":",
"# Grab it, clean it and ship it",
"work_results",
"=",
"self",
".",
"_get_work_results",
"(",
"'info'",
",",
"component",
")",
"return",
"self",
".",
"data_store",
".",
"clean_for_serialization",
"(",
"w... | Get the information about this component | [
"Get",
"the",
"information",
"about",
"this",
"component"
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/server/workbench_server.py#L681-L686 | train | 43,214 |
SuperCowPowers/workbench | workbench/server/workbench_server.py | WorkBench.store_info | def store_info(self, info_dict, component, type_tag):
""" Store information about a component. The component could be a
worker or a commands or a class, or whatever you want, the
only thing to be aware of is name collisions. """
# Enforce dictionary input
if not isinstance(info_dict, dict):
print 'Critical: info_dict must be a python dictionary, got %s' % type(info_dict)
return
# Ensure values are not functions/methods/classes
info_storage = {key:value for key, value in info_dict.iteritems() if not hasattr(value, '__call__')}
# Place the type_tag on it and store it
info_storage['type_tag'] = type_tag
self._store_work_results(info_storage, 'info', component) | python | def store_info(self, info_dict, component, type_tag):
""" Store information about a component. The component could be a
worker or a commands or a class, or whatever you want, the
only thing to be aware of is name collisions. """
# Enforce dictionary input
if not isinstance(info_dict, dict):
print 'Critical: info_dict must be a python dictionary, got %s' % type(info_dict)
return
# Ensure values are not functions/methods/classes
info_storage = {key:value for key, value in info_dict.iteritems() if not hasattr(value, '__call__')}
# Place the type_tag on it and store it
info_storage['type_tag'] = type_tag
self._store_work_results(info_storage, 'info', component) | [
"def",
"store_info",
"(",
"self",
",",
"info_dict",
",",
"component",
",",
"type_tag",
")",
":",
"# Enforce dictionary input",
"if",
"not",
"isinstance",
"(",
"info_dict",
",",
"dict",
")",
":",
"print",
"'Critical: info_dict must be a python dictionary, got %s'",
"%"... | Store information about a component. The component could be a
worker or a commands or a class, or whatever you want, the
only thing to be aware of is name collisions. | [
"Store",
"information",
"about",
"a",
"component",
".",
"The",
"component",
"could",
"be",
"a",
"worker",
"or",
"a",
"commands",
"or",
"a",
"class",
"or",
"whatever",
"you",
"want",
"the",
"only",
"thing",
"to",
"be",
"aware",
"of",
"is",
"name",
"collis... | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/server/workbench_server.py#L688-L703 | train | 43,215 |
SuperCowPowers/workbench | workbench/server/workbench_server.py | WorkBench._store_information | def _store_information(self):
""" Store infomation about Workbench and its commands """
print '<<< Generating Information Storage >>>'
# Stores information on Workbench commands and signatures
for name, meth in inspect.getmembers(self, predicate=inspect.isroutine):
if not name.startswith('_'):
info = {'command': name, 'sig': str(funcsigs.signature(meth)), 'docstring': meth.__doc__}
self.store_info(info, name, type_tag='command')
# Stores help text into the workbench information system
self.store_info({'help': '<<< Workbench Server Version %s >>>' % self.version}, 'version', type_tag='help')
self.store_info({'help': self._help_workbench()}, 'workbench', type_tag='help')
self.store_info({'help': self._help_basic()}, 'basic', type_tag='help')
self.store_info({'help': self._help_commands()}, 'commands', type_tag='help')
self.store_info({'help': self._help_workers()}, 'workers', type_tag='help') | python | def _store_information(self):
""" Store infomation about Workbench and its commands """
print '<<< Generating Information Storage >>>'
# Stores information on Workbench commands and signatures
for name, meth in inspect.getmembers(self, predicate=inspect.isroutine):
if not name.startswith('_'):
info = {'command': name, 'sig': str(funcsigs.signature(meth)), 'docstring': meth.__doc__}
self.store_info(info, name, type_tag='command')
# Stores help text into the workbench information system
self.store_info({'help': '<<< Workbench Server Version %s >>>' % self.version}, 'version', type_tag='help')
self.store_info({'help': self._help_workbench()}, 'workbench', type_tag='help')
self.store_info({'help': self._help_basic()}, 'basic', type_tag='help')
self.store_info({'help': self._help_commands()}, 'commands', type_tag='help')
self.store_info({'help': self._help_workers()}, 'workers', type_tag='help') | [
"def",
"_store_information",
"(",
"self",
")",
":",
"print",
"'<<< Generating Information Storage >>>'",
"# Stores information on Workbench commands and signatures",
"for",
"name",
",",
"meth",
"in",
"inspect",
".",
"getmembers",
"(",
"self",
",",
"predicate",
"=",
"inspe... | Store infomation about Workbench and its commands | [
"Store",
"infomation",
"about",
"Workbench",
"and",
"its",
"commands"
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/server/workbench_server.py#L729-L745 | train | 43,216 |
SuperCowPowers/workbench | workbench_apps/workbench_cli/workbench_shell.py | WorkbenchShell.tags | def tags(self):
'''Display tag information for all samples in database'''
tags = self.workbench.get_all_tags()
if not tags:
return
tag_df = pd.DataFrame(tags)
tag_df = self.vectorize(tag_df, 'tags')
print '\n%sSamples in Database%s' % (color.LightPurple, color.Normal)
self.top_corr(tag_df) | python | def tags(self):
'''Display tag information for all samples in database'''
tags = self.workbench.get_all_tags()
if not tags:
return
tag_df = pd.DataFrame(tags)
tag_df = self.vectorize(tag_df, 'tags')
print '\n%sSamples in Database%s' % (color.LightPurple, color.Normal)
self.top_corr(tag_df) | [
"def",
"tags",
"(",
"self",
")",
":",
"tags",
"=",
"self",
".",
"workbench",
".",
"get_all_tags",
"(",
")",
"if",
"not",
"tags",
":",
"return",
"tag_df",
"=",
"pd",
".",
"DataFrame",
"(",
"tags",
")",
"tag_df",
"=",
"self",
".",
"vectorize",
"(",
"... | Display tag information for all samples in database | [
"Display",
"tag",
"information",
"for",
"all",
"samples",
"in",
"database"
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench_apps/workbench_cli/workbench_shell.py#L169-L177 | train | 43,217 |
SuperCowPowers/workbench | workbench_apps/workbench_cli/workbench_shell.py | WorkbenchShell.vectorize | def vectorize(self, df, column_name):
"""Vectorize a column in the dataframe"""
vec_df = df[column_name].str.join(sep='-').str.get_dummies(sep='-')
return vec_df | python | def vectorize(self, df, column_name):
"""Vectorize a column in the dataframe"""
vec_df = df[column_name].str.join(sep='-').str.get_dummies(sep='-')
return vec_df | [
"def",
"vectorize",
"(",
"self",
",",
"df",
",",
"column_name",
")",
":",
"vec_df",
"=",
"df",
"[",
"column_name",
"]",
".",
"str",
".",
"join",
"(",
"sep",
"=",
"'-'",
")",
".",
"str",
".",
"get_dummies",
"(",
"sep",
"=",
"'-'",
")",
"return",
"... | Vectorize a column in the dataframe | [
"Vectorize",
"a",
"column",
"in",
"the",
"dataframe"
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench_apps/workbench_cli/workbench_shell.py#L193-L196 | train | 43,218 |
SuperCowPowers/workbench | workbench_apps/workbench_cli/workbench_shell.py | WorkbenchShell.flatten | def flatten(self, df, column_name):
"""Flatten a column in the dataframe that contains lists"""
_exp_list = [[md5, x] for md5, value_list in zip(df['md5'], df[column_name]) for x in value_list]
return pd.DataFrame(_exp_list, columns=['md5',column_name]) | python | def flatten(self, df, column_name):
"""Flatten a column in the dataframe that contains lists"""
_exp_list = [[md5, x] for md5, value_list in zip(df['md5'], df[column_name]) for x in value_list]
return pd.DataFrame(_exp_list, columns=['md5',column_name]) | [
"def",
"flatten",
"(",
"self",
",",
"df",
",",
"column_name",
")",
":",
"_exp_list",
"=",
"[",
"[",
"md5",
",",
"x",
"]",
"for",
"md5",
",",
"value_list",
"in",
"zip",
"(",
"df",
"[",
"'md5'",
"]",
",",
"df",
"[",
"column_name",
"]",
")",
"for",
... | Flatten a column in the dataframe that contains lists | [
"Flatten",
"a",
"column",
"in",
"the",
"dataframe",
"that",
"contains",
"lists"
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench_apps/workbench_cli/workbench_shell.py#L198-L201 | train | 43,219 |
SuperCowPowers/workbench | workbench_apps/workbench_cli/workbench_shell.py | WorkbenchShell.top_corr | def top_corr(self, df):
"""Give aggregation counts and correlations"""
tag_freq = df.sum()
tag_freq.sort(ascending=False)
corr = df.corr().fillna(1)
corr_dict = corr.to_dict()
for tag, count in tag_freq.iteritems():
print ' %s%s: %s%s%s (' % (color.Green, tag, color.LightBlue, count, color.Normal),
tag_corrs = sorted(corr_dict[tag].iteritems(), key=operator.itemgetter(1), reverse=True)
for corr_tag, value in tag_corrs[:5]:
if corr_tag != tag and (value > .2):
print '%s%s:%s%.1f' % (color.Green, corr_tag, color.LightBlue, value),
print '%s)' % color.Normal | python | def top_corr(self, df):
"""Give aggregation counts and correlations"""
tag_freq = df.sum()
tag_freq.sort(ascending=False)
corr = df.corr().fillna(1)
corr_dict = corr.to_dict()
for tag, count in tag_freq.iteritems():
print ' %s%s: %s%s%s (' % (color.Green, tag, color.LightBlue, count, color.Normal),
tag_corrs = sorted(corr_dict[tag].iteritems(), key=operator.itemgetter(1), reverse=True)
for corr_tag, value in tag_corrs[:5]:
if corr_tag != tag and (value > .2):
print '%s%s:%s%.1f' % (color.Green, corr_tag, color.LightBlue, value),
print '%s)' % color.Normal | [
"def",
"top_corr",
"(",
"self",
",",
"df",
")",
":",
"tag_freq",
"=",
"df",
".",
"sum",
"(",
")",
"tag_freq",
".",
"sort",
"(",
"ascending",
"=",
"False",
")",
"corr",
"=",
"df",
".",
"corr",
"(",
")",
".",
"fillna",
"(",
"1",
")",
"corr_dict",
... | Give aggregation counts and correlations | [
"Give",
"aggregation",
"counts",
"and",
"correlations"
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench_apps/workbench_cli/workbench_shell.py#L203-L216 | train | 43,220 |
SuperCowPowers/workbench | workbench_apps/workbench_cli/workbench_shell.py | WorkbenchShell.run | def run(self):
''' Running the workbench CLI '''
# Announce versions
self.versions()
# Sample/Tag info and Help
self.tags()
print '\n%s' % self.workbench.help('cli')
# Now that we have the Workbench connection spun up, we register some stuff
# with the embedded IPython interpreter and than spin it up
# cfg = IPython.config.loader.Config()
cfg = Config()
cfg.InteractiveShellEmbed.autocall = 2
cfg.InteractiveShellEmbed.colors = 'Linux'
cfg.InteractiveShellEmbed.color_info = True
cfg.InteractiveShellEmbed.autoindent = True
cfg.InteractiveShellEmbed.deep_reload = True
cfg.PromptManager.in_template = (
r'{color.LightPurple}{short_md5}{color.Yellow}{prompt_deco}{color.LightBlue} Workbench{color.Green}[\#]> ')
# cfg.PromptManager.out_template = ''
# Create the IPython shell
self.ipshell = IPython.terminal.embed.InteractiveShellEmbed(
config=cfg, banner1='', exit_msg='\nWorkbench has SuperCowPowers...')
# Register our transformer, the shell will use this for 'shortcut' commands
auto_quoter = auto_quote_xform.AutoQuoteTransformer(self.ipshell, self.ipshell.prefilter_manager)
auto_quoter.register_command_set(self.command_set)
# Setting up some Pandas options
pd.set_option('display.width', 140)
pd.set_option('max_colwidth', 15)
# Start up the shell with our set of workbench commands
self.ipshell(local_ns=self.command_dict) | python | def run(self):
''' Running the workbench CLI '''
# Announce versions
self.versions()
# Sample/Tag info and Help
self.tags()
print '\n%s' % self.workbench.help('cli')
# Now that we have the Workbench connection spun up, we register some stuff
# with the embedded IPython interpreter and than spin it up
# cfg = IPython.config.loader.Config()
cfg = Config()
cfg.InteractiveShellEmbed.autocall = 2
cfg.InteractiveShellEmbed.colors = 'Linux'
cfg.InteractiveShellEmbed.color_info = True
cfg.InteractiveShellEmbed.autoindent = True
cfg.InteractiveShellEmbed.deep_reload = True
cfg.PromptManager.in_template = (
r'{color.LightPurple}{short_md5}{color.Yellow}{prompt_deco}{color.LightBlue} Workbench{color.Green}[\#]> ')
# cfg.PromptManager.out_template = ''
# Create the IPython shell
self.ipshell = IPython.terminal.embed.InteractiveShellEmbed(
config=cfg, banner1='', exit_msg='\nWorkbench has SuperCowPowers...')
# Register our transformer, the shell will use this for 'shortcut' commands
auto_quoter = auto_quote_xform.AutoQuoteTransformer(self.ipshell, self.ipshell.prefilter_manager)
auto_quoter.register_command_set(self.command_set)
# Setting up some Pandas options
pd.set_option('display.width', 140)
pd.set_option('max_colwidth', 15)
# Start up the shell with our set of workbench commands
self.ipshell(local_ns=self.command_dict) | [
"def",
"run",
"(",
"self",
")",
":",
"# Announce versions",
"self",
".",
"versions",
"(",
")",
"# Sample/Tag info and Help",
"self",
".",
"tags",
"(",
")",
"print",
"'\\n%s'",
"%",
"self",
".",
"workbench",
".",
"help",
"(",
"'cli'",
")",
"# Now that we have... | Running the workbench CLI | [
"Running",
"the",
"workbench",
"CLI"
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench_apps/workbench_cli/workbench_shell.py#L238-L274 | train | 43,221 |
SuperCowPowers/workbench | workbench_apps/workbench_cli/workbench_shell.py | WorkbenchShell._connect | def _connect(self, server_info):
"""Connect to the workbench server"""
# First we do a temp connect with a short heartbeat
_tmp_connect = zerorpc.Client(timeout=300, heartbeat=2)
_tmp_connect.connect('tcp://'+server_info['server']+':'+server_info['port'])
try:
_tmp_connect._zerorpc_name()
_tmp_connect.close()
del _tmp_connect
except zerorpc.exceptions.LostRemote:
print '%sError: Could not connect to Workbench Server at %s:%s%s' % \
(color.Red, server_info['server'], server_info['port'], color.Normal)
sys.exit(1)
# Okay do the real connection
if self.workbench:
self.workbench.close()
self.workbench = zerorpc.Client(timeout=300, heartbeat=60)
self.workbench.connect('tcp://'+server_info['server']+':'+server_info['port'])
print '\n%s<<< Connected: %s:%s >>>%s' % (color.Green, server_info['server'], server_info['port'], color.Normal) | python | def _connect(self, server_info):
"""Connect to the workbench server"""
# First we do a temp connect with a short heartbeat
_tmp_connect = zerorpc.Client(timeout=300, heartbeat=2)
_tmp_connect.connect('tcp://'+server_info['server']+':'+server_info['port'])
try:
_tmp_connect._zerorpc_name()
_tmp_connect.close()
del _tmp_connect
except zerorpc.exceptions.LostRemote:
print '%sError: Could not connect to Workbench Server at %s:%s%s' % \
(color.Red, server_info['server'], server_info['port'], color.Normal)
sys.exit(1)
# Okay do the real connection
if self.workbench:
self.workbench.close()
self.workbench = zerorpc.Client(timeout=300, heartbeat=60)
self.workbench.connect('tcp://'+server_info['server']+':'+server_info['port'])
print '\n%s<<< Connected: %s:%s >>>%s' % (color.Green, server_info['server'], server_info['port'], color.Normal) | [
"def",
"_connect",
"(",
"self",
",",
"server_info",
")",
":",
"# First we do a temp connect with a short heartbeat",
"_tmp_connect",
"=",
"zerorpc",
".",
"Client",
"(",
"timeout",
"=",
"300",
",",
"heartbeat",
"=",
"2",
")",
"_tmp_connect",
".",
"connect",
"(",
... | Connect to the workbench server | [
"Connect",
"to",
"the",
"workbench",
"server"
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench_apps/workbench_cli/workbench_shell.py#L276-L296 | train | 43,222 |
SuperCowPowers/workbench | workbench_apps/workbench_cli/workbench_shell.py | WorkbenchShell._work_request | def _work_request(self, worker, md5=None):
"""Wrapper for a work_request to workbench"""
# I'm sure there's a better way to do this
if not md5 and not self.session.md5:
return 'Must call worker with an md5 argument...'
elif not md5:
md5 = self.session.md5
# Is the md5 a sample_set?
if self.workbench.is_sample_set(md5):
return self.workbench.set_work_request(worker, md5)
# Make the work_request with worker and md5 args
try:
return self.workbench.work_request(worker, md5)
except zerorpc.exceptions.RemoteError as e:
return repr_to_str_decorator.r_to_s(self._data_not_found)(e) | python | def _work_request(self, worker, md5=None):
"""Wrapper for a work_request to workbench"""
# I'm sure there's a better way to do this
if not md5 and not self.session.md5:
return 'Must call worker with an md5 argument...'
elif not md5:
md5 = self.session.md5
# Is the md5 a sample_set?
if self.workbench.is_sample_set(md5):
return self.workbench.set_work_request(worker, md5)
# Make the work_request with worker and md5 args
try:
return self.workbench.work_request(worker, md5)
except zerorpc.exceptions.RemoteError as e:
return repr_to_str_decorator.r_to_s(self._data_not_found)(e) | [
"def",
"_work_request",
"(",
"self",
",",
"worker",
",",
"md5",
"=",
"None",
")",
":",
"# I'm sure there's a better way to do this",
"if",
"not",
"md5",
"and",
"not",
"self",
".",
"session",
".",
"md5",
":",
"return",
"'Must call worker with an md5 argument...'",
... | Wrapper for a work_request to workbench | [
"Wrapper",
"for",
"a",
"work_request",
"to",
"workbench"
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench_apps/workbench_cli/workbench_shell.py#L307-L324 | train | 43,223 |
SuperCowPowers/workbench | workbench_apps/workbench_cli/workbench_shell.py | WorkbenchShell._register_info | def _register_info(self):
"""Register local methods in the Workbench Information system"""
# Stores information on Workbench commands and signatures
for name, meth in inspect.getmembers(self, predicate=inspect.isroutine):
if not name.startswith('_') and name != 'run':
info = {'command': name, 'sig': str(funcsigs.signature(meth)), 'docstring': meth.__doc__}
self.workbench.store_info(info, name, 'command')
# Register help information
self.workbench.store_info({'help': self.help.help_cli()}, 'cli', 'help')
self.workbench.store_info({'help': self.help.help_cli_basic()}, 'cli_basic', 'help')
self.workbench.store_info({'help': self.help.help_cli_search()}, 'search', 'help')
self.workbench.store_info({'help': self.help.help_dataframe()}, 'dataframe', 'help')
self.workbench.store_info({'help': self.help.help_dataframe_memory()}, 'dataframe_memory', 'help')
self.workbench.store_info({'help': self.help.help_dataframe_pe()}, 'dataframe_pe', 'help') | python | def _register_info(self):
"""Register local methods in the Workbench Information system"""
# Stores information on Workbench commands and signatures
for name, meth in inspect.getmembers(self, predicate=inspect.isroutine):
if not name.startswith('_') and name != 'run':
info = {'command': name, 'sig': str(funcsigs.signature(meth)), 'docstring': meth.__doc__}
self.workbench.store_info(info, name, 'command')
# Register help information
self.workbench.store_info({'help': self.help.help_cli()}, 'cli', 'help')
self.workbench.store_info({'help': self.help.help_cli_basic()}, 'cli_basic', 'help')
self.workbench.store_info({'help': self.help.help_cli_search()}, 'search', 'help')
self.workbench.store_info({'help': self.help.help_dataframe()}, 'dataframe', 'help')
self.workbench.store_info({'help': self.help.help_dataframe_memory()}, 'dataframe_memory', 'help')
self.workbench.store_info({'help': self.help.help_dataframe_pe()}, 'dataframe_pe', 'help') | [
"def",
"_register_info",
"(",
"self",
")",
":",
"# Stores information on Workbench commands and signatures",
"for",
"name",
",",
"meth",
"in",
"inspect",
".",
"getmembers",
"(",
"self",
",",
"predicate",
"=",
"inspect",
".",
"isroutine",
")",
":",
"if",
"not",
"... | Register local methods in the Workbench Information system | [
"Register",
"local",
"methods",
"in",
"the",
"Workbench",
"Information",
"system"
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench_apps/workbench_cli/workbench_shell.py#L390-L404 | train | 43,224 |
SuperCowPowers/workbench | workbench_apps/workbench_cli/auto_quote_xform.py | AutoQuoteTransformer.transform | def transform(self, line, _continue_prompt):
"""Shortcut Workbench commands by using 'auto-quotes'"""
# Capture the original line
orig_line = line
# Get tokens from all the currently active namespace
ns_token_set = set([token for nspace in self.shell.all_ns_refs for token in nspace])
# Build up token set and info out of the incoming line
token_list = re.split(' |;|,|(|)|\'|"', line)
token_list = [item for item in token_list if item != None and item != '']
num_tokens = len(token_list)
first_token = token_list[0]
token_set = set(token_list)
# Very conservative logic (but possibly flawed)
# 1) Lines with any of these symbols ; , ' " ( ) aren't touched
# 2) Need to have more than one token
# 3) First token in line must be in the workbench command set
# 4) If first token is 'help' than all other tokens are quoted
# 5) Otherwise only tokens that are not in any of the namespace are quoted
# Fixme: Horse shit temp hack for load_sample
# 0) If load_sample do special processing
if first_token == 'load_sample':
# If the second arg isn't in namespace quote it
if token_list[1] not in ns_token_set:
line = line.replace(token_list[1], '"'+token_list[1]+'",')
return line
# Fixme: Horse shit temp hack for pivot
# 0) If pivot do special processing
if first_token == 'pivot':
# Quote all other tokens
for token in token_list:
if token not in ns_token_set:
line = line.replace(token, '"' + token + '",')
return line
# 1) Lines with any of these symbols ; , ' " ( ) aren't touched
skip_symbols = [';', ',', '\'', '"', '(', ')']
if any([sym in line for sym in skip_symbols]):
return line
# 2) Need to have more than one token
# 3) First token in line must be in the workbench command set
if num_tokens > 1 and first_token in self.command_set:
# 4) If first token is 'help' than all other tokens are quoted
if first_token == 'help':
token_set.remove('help')
for token in token_set:
line = line.replace(token, '"'+token+'"')
# 5) Otherwise only tokens that are not in any of the namespace are quoted
else: # Not help
for token in token_set:
if token not in ns_token_set:
line = line.replace(token, '"'+token+'"')
# Return the processed line
return line | python | def transform(self, line, _continue_prompt):
"""Shortcut Workbench commands by using 'auto-quotes'"""
# Capture the original line
orig_line = line
# Get tokens from all the currently active namespace
ns_token_set = set([token for nspace in self.shell.all_ns_refs for token in nspace])
# Build up token set and info out of the incoming line
token_list = re.split(' |;|,|(|)|\'|"', line)
token_list = [item for item in token_list if item != None and item != '']
num_tokens = len(token_list)
first_token = token_list[0]
token_set = set(token_list)
# Very conservative logic (but possibly flawed)
# 1) Lines with any of these symbols ; , ' " ( ) aren't touched
# 2) Need to have more than one token
# 3) First token in line must be in the workbench command set
# 4) If first token is 'help' than all other tokens are quoted
# 5) Otherwise only tokens that are not in any of the namespace are quoted
# Fixme: Horse shit temp hack for load_sample
# 0) If load_sample do special processing
if first_token == 'load_sample':
# If the second arg isn't in namespace quote it
if token_list[1] not in ns_token_set:
line = line.replace(token_list[1], '"'+token_list[1]+'",')
return line
# Fixme: Horse shit temp hack for pivot
# 0) If pivot do special processing
if first_token == 'pivot':
# Quote all other tokens
for token in token_list:
if token not in ns_token_set:
line = line.replace(token, '"' + token + '",')
return line
# 1) Lines with any of these symbols ; , ' " ( ) aren't touched
skip_symbols = [';', ',', '\'', '"', '(', ')']
if any([sym in line for sym in skip_symbols]):
return line
# 2) Need to have more than one token
# 3) First token in line must be in the workbench command set
if num_tokens > 1 and first_token in self.command_set:
# 4) If first token is 'help' than all other tokens are quoted
if first_token == 'help':
token_set.remove('help')
for token in token_set:
line = line.replace(token, '"'+token+'"')
# 5) Otherwise only tokens that are not in any of the namespace are quoted
else: # Not help
for token in token_set:
if token not in ns_token_set:
line = line.replace(token, '"'+token+'"')
# Return the processed line
return line | [
"def",
"transform",
"(",
"self",
",",
"line",
",",
"_continue_prompt",
")",
":",
"# Capture the original line",
"orig_line",
"=",
"line",
"# Get tokens from all the currently active namespace",
"ns_token_set",
"=",
"set",
"(",
"[",
"token",
"for",
"nspace",
"in",
"sel... | Shortcut Workbench commands by using 'auto-quotes | [
"Shortcut",
"Workbench",
"commands",
"by",
"using",
"auto",
"-",
"quotes"
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench_apps/workbench_cli/auto_quote_xform.py#L16-L78 | train | 43,225 |
yfpeng/bioc | bioc/biocxml/decoder.py | BioCXMLDecoder.decodes | def decodes(self, s: str) -> BioCCollection:
"""
Deserialize ``s`` to a BioC collection object.
Args:
s: a "str" instance containing a BioC collection
Returns:
an object of BioCollection
"""
tree = etree.parse(io.BytesIO(bytes(s, encoding='UTF-8')))
collection = self.__parse_collection(tree.getroot())
collection.encoding = tree.docinfo.encoding
collection.standalone = tree.docinfo.standalone
collection.version = tree.docinfo.xml_version
return collection | python | def decodes(self, s: str) -> BioCCollection:
"""
Deserialize ``s`` to a BioC collection object.
Args:
s: a "str" instance containing a BioC collection
Returns:
an object of BioCollection
"""
tree = etree.parse(io.BytesIO(bytes(s, encoding='UTF-8')))
collection = self.__parse_collection(tree.getroot())
collection.encoding = tree.docinfo.encoding
collection.standalone = tree.docinfo.standalone
collection.version = tree.docinfo.xml_version
return collection | [
"def",
"decodes",
"(",
"self",
",",
"s",
":",
"str",
")",
"->",
"BioCCollection",
":",
"tree",
"=",
"etree",
".",
"parse",
"(",
"io",
".",
"BytesIO",
"(",
"bytes",
"(",
"s",
",",
"encoding",
"=",
"'UTF-8'",
")",
")",
")",
"collection",
"=",
"self",... | Deserialize ``s`` to a BioC collection object.
Args:
s: a "str" instance containing a BioC collection
Returns:
an object of BioCollection | [
"Deserialize",
"s",
"to",
"a",
"BioC",
"collection",
"object",
"."
] | 47ddaa010960d9ba673aefe068e7bbaf39f0fff4 | https://github.com/yfpeng/bioc/blob/47ddaa010960d9ba673aefe068e7bbaf39f0fff4/bioc/biocxml/decoder.py#L22-L37 | train | 43,226 |
yfpeng/bioc | bioc/biocxml/decoder.py | BioCXMLDecoder.decode | def decode(self, fp: TextIO) -> BioCCollection:
"""
Deserialize ``fp`` to a BioC collection object.
Args:
fp: a ``.read()``-supporting file-like object containing a BioC collection
Returns:
an object of BioCollection
"""
# utf8_parser = etree.XMLParser(encoding='utf-8')
tree = etree.parse(fp)
collection = self.__parse_collection(tree.getroot())
collection.encoding = tree.docinfo.encoding
collection.standalone = tree.docinfo.standalone
collection.version = tree.docinfo.xml_version
return collection | python | def decode(self, fp: TextIO) -> BioCCollection:
"""
Deserialize ``fp`` to a BioC collection object.
Args:
fp: a ``.read()``-supporting file-like object containing a BioC collection
Returns:
an object of BioCollection
"""
# utf8_parser = etree.XMLParser(encoding='utf-8')
tree = etree.parse(fp)
collection = self.__parse_collection(tree.getroot())
collection.encoding = tree.docinfo.encoding
collection.standalone = tree.docinfo.standalone
collection.version = tree.docinfo.xml_version
return collection | [
"def",
"decode",
"(",
"self",
",",
"fp",
":",
"TextIO",
")",
"->",
"BioCCollection",
":",
"# utf8_parser = etree.XMLParser(encoding='utf-8')",
"tree",
"=",
"etree",
".",
"parse",
"(",
"fp",
")",
"collection",
"=",
"self",
".",
"__parse_collection",
"(",
"tree",
... | Deserialize ``fp`` to a BioC collection object.
Args:
fp: a ``.read()``-supporting file-like object containing a BioC collection
Returns:
an object of BioCollection | [
"Deserialize",
"fp",
"to",
"a",
"BioC",
"collection",
"object",
"."
] | 47ddaa010960d9ba673aefe068e7bbaf39f0fff4 | https://github.com/yfpeng/bioc/blob/47ddaa010960d9ba673aefe068e7bbaf39f0fff4/bioc/biocxml/decoder.py#L39-L55 | train | 43,227 |
SuperCowPowers/workbench | workbench/workers/rekall_adapter/rekall_adapter.py | RekallAdapter.process_row | def process_row(cls, data, column_map):
"""Process the row data from Rekall"""
row = {}
for key,value in data.iteritems():
if not value:
value = '-'
elif isinstance(value, list):
value = value[1]
elif isinstance(value, dict):
if 'type_name' in value:
if 'UnixTimeStamp' in value['type_name']:
value = datetime.datetime.utcfromtimestamp(value['epoch'])
if value == datetime.datetime(1970, 1, 1, 0, 0):
value = '-'
# Assume the value is somehow well formed when we get here
row[column_map[key]] = value
return row | python | def process_row(cls, data, column_map):
"""Process the row data from Rekall"""
row = {}
for key,value in data.iteritems():
if not value:
value = '-'
elif isinstance(value, list):
value = value[1]
elif isinstance(value, dict):
if 'type_name' in value:
if 'UnixTimeStamp' in value['type_name']:
value = datetime.datetime.utcfromtimestamp(value['epoch'])
if value == datetime.datetime(1970, 1, 1, 0, 0):
value = '-'
# Assume the value is somehow well formed when we get here
row[column_map[key]] = value
return row | [
"def",
"process_row",
"(",
"cls",
",",
"data",
",",
"column_map",
")",
":",
"row",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"data",
".",
"iteritems",
"(",
")",
":",
"if",
"not",
"value",
":",
"value",
"=",
"'-'",
"elif",
"isinstance",
"(",
... | Process the row data from Rekall | [
"Process",
"the",
"row",
"data",
"from",
"Rekall"
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/workers/rekall_adapter/rekall_adapter.py#L59-L76 | train | 43,228 |
SuperCowPowers/workbench | workbench/workers/rekall_adapter/rekall_adapter.py | WorkbenchRenderer.format | def format(self, formatstring, *args):
"""Presentation Information from the Plugin"""
# Make a new section
if self.incoming_section:
self.SendMessage(['s', {'name': args}])
self.incoming_section = False | python | def format(self, formatstring, *args):
"""Presentation Information from the Plugin"""
# Make a new section
if self.incoming_section:
self.SendMessage(['s', {'name': args}])
self.incoming_section = False | [
"def",
"format",
"(",
"self",
",",
"formatstring",
",",
"*",
"args",
")",
":",
"# Make a new section",
"if",
"self",
".",
"incoming_section",
":",
"self",
".",
"SendMessage",
"(",
"[",
"'s'",
",",
"{",
"'name'",
":",
"args",
"}",
"]",
")",
"self",
".",... | Presentation Information from the Plugin | [
"Presentation",
"Information",
"from",
"the",
"Plugin"
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/workers/rekall_adapter/rekall_adapter.py#L122-L128 | train | 43,229 |
SuperCowPowers/workbench | workbench/workers/rekall_adapter/rekall_adapter.py | WorkbenchRenderer.SendMessage | def SendMessage(self, statement):
"""Here we're actually capturing messages and putting them into our output"""
# The way messages are 'encapsulated' by Rekall is questionable, 99% of the
# time it's way better to have a dictionary...shrug...
message_type = statement[0]
message_data = statement[1]
self.output.append({'type': message_type, 'data': message_data}) | python | def SendMessage(self, statement):
"""Here we're actually capturing messages and putting them into our output"""
# The way messages are 'encapsulated' by Rekall is questionable, 99% of the
# time it's way better to have a dictionary...shrug...
message_type = statement[0]
message_data = statement[1]
self.output.append({'type': message_type, 'data': message_data}) | [
"def",
"SendMessage",
"(",
"self",
",",
"statement",
")",
":",
"# The way messages are 'encapsulated' by Rekall is questionable, 99% of the",
"# time it's way better to have a dictionary...shrug...",
"message_type",
"=",
"statement",
"[",
"0",
"]",
"message_data",
"=",
"statement... | Here we're actually capturing messages and putting them into our output | [
"Here",
"we",
"re",
"actually",
"capturing",
"messages",
"and",
"putting",
"them",
"into",
"our",
"output"
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/workers/rekall_adapter/rekall_adapter.py#L138-L145 | train | 43,230 |
SuperCowPowers/workbench | workbench/workers/rekall_adapter/rekall_adapter.py | WorkbenchRenderer.open | def open(self, directory=None, filename=None, mode="rb"):
"""Opens a file for writing or reading."""
path = os.path.join(directory, filename)
return open(path, mode) | python | def open(self, directory=None, filename=None, mode="rb"):
"""Opens a file for writing or reading."""
path = os.path.join(directory, filename)
return open(path, mode) | [
"def",
"open",
"(",
"self",
",",
"directory",
"=",
"None",
",",
"filename",
"=",
"None",
",",
"mode",
"=",
"\"rb\"",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"filename",
")",
"return",
"open",
"(",
"path",
",",
... | Opens a file for writing or reading. | [
"Opens",
"a",
"file",
"for",
"writing",
"or",
"reading",
"."
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/workers/rekall_adapter/rekall_adapter.py#L147-L150 | train | 43,231 |
SuperCowPowers/workbench | workbench_apps/workbench_cli/file_streamer.py | FileStreamer._file_chunks | def _file_chunks(self, data, chunk_size):
""" Yield compressed chunks from a data array"""
for i in xrange(0, len(data), chunk_size):
yield self.compressor(data[i:i+chunk_size]) | python | def _file_chunks(self, data, chunk_size):
""" Yield compressed chunks from a data array"""
for i in xrange(0, len(data), chunk_size):
yield self.compressor(data[i:i+chunk_size]) | [
"def",
"_file_chunks",
"(",
"self",
",",
"data",
",",
"chunk_size",
")",
":",
"for",
"i",
"in",
"xrange",
"(",
"0",
",",
"len",
"(",
"data",
")",
",",
"chunk_size",
")",
":",
"yield",
"self",
".",
"compressor",
"(",
"data",
"[",
"i",
":",
"i",
"+... | Yield compressed chunks from a data array | [
"Yield",
"compressed",
"chunks",
"from",
"a",
"data",
"array"
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench_apps/workbench_cli/file_streamer.py#L24-L27 | train | 43,232 |
SuperCowPowers/workbench | workbench_apps/workbench_cli/file_streamer.py | FileStreamer.stream_to_workbench | def stream_to_workbench(self, raw_bytes, filename, type_tag, tags):
"""Split up a large file into chunks and send to Workbench"""
md5_list = []
sent_bytes = 0
total_bytes = len(raw_bytes)
for chunk in self._file_chunks(raw_bytes, self.chunk_size):
md5_list.append(self.workbench.store_sample(chunk, filename, self.compress_ident))
sent_bytes += self.chunk_size
self.progress(sent_bytes, total_bytes)
# Now we just ask Workbench to combine these
full_md5 = self.workbench.combine_samples(md5_list, filename, type_tag)
# Add the tags
self.workbench.add_tags(full_md5, tags)
# Return the md5 of the finalized sample
return full_md5 | python | def stream_to_workbench(self, raw_bytes, filename, type_tag, tags):
"""Split up a large file into chunks and send to Workbench"""
md5_list = []
sent_bytes = 0
total_bytes = len(raw_bytes)
for chunk in self._file_chunks(raw_bytes, self.chunk_size):
md5_list.append(self.workbench.store_sample(chunk, filename, self.compress_ident))
sent_bytes += self.chunk_size
self.progress(sent_bytes, total_bytes)
# Now we just ask Workbench to combine these
full_md5 = self.workbench.combine_samples(md5_list, filename, type_tag)
# Add the tags
self.workbench.add_tags(full_md5, tags)
# Return the md5 of the finalized sample
return full_md5 | [
"def",
"stream_to_workbench",
"(",
"self",
",",
"raw_bytes",
",",
"filename",
",",
"type_tag",
",",
"tags",
")",
":",
"md5_list",
"=",
"[",
"]",
"sent_bytes",
"=",
"0",
"total_bytes",
"=",
"len",
"(",
"raw_bytes",
")",
"for",
"chunk",
"in",
"self",
".",
... | Split up a large file into chunks and send to Workbench | [
"Split",
"up",
"a",
"large",
"file",
"into",
"chunks",
"and",
"send",
"to",
"Workbench"
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench_apps/workbench_cli/file_streamer.py#L29-L46 | train | 43,233 |
yfpeng/bioc | bioc/biocjson/encoder.py | dumps | def dumps(obj, **kwargs) -> str:
"""
Serialize a BioC ``obj`` to a JSON formatted ``str``.
"""
return json.dumps(obj, cls=BioCJSONEncoder, **kwargs) | python | def dumps(obj, **kwargs) -> str:
"""
Serialize a BioC ``obj`` to a JSON formatted ``str``.
"""
return json.dumps(obj, cls=BioCJSONEncoder, **kwargs) | [
"def",
"dumps",
"(",
"obj",
",",
"*",
"*",
"kwargs",
")",
"->",
"str",
":",
"return",
"json",
".",
"dumps",
"(",
"obj",
",",
"cls",
"=",
"BioCJSONEncoder",
",",
"*",
"*",
"kwargs",
")"
] | Serialize a BioC ``obj`` to a JSON formatted ``str``. | [
"Serialize",
"a",
"BioC",
"obj",
"to",
"a",
"JSON",
"formatted",
"str",
"."
] | 47ddaa010960d9ba673aefe068e7bbaf39f0fff4 | https://github.com/yfpeng/bioc/blob/47ddaa010960d9ba673aefe068e7bbaf39f0fff4/bioc/biocjson/encoder.py#L14-L18 | train | 43,234 |
yfpeng/bioc | bioc/biocjson/encoder.py | BioCJsonIterWriter.write | def write(self, obj: BioCDocument or BioCPassage or BioCSentence):
"""
Encode and write a single object.
Args:
obj: an instance of BioCDocument, BioCPassage, or BioCSentence
Returns:
"""
if self.level == DOCUMENT and not isinstance(obj, BioCDocument):
raise ValueError
if self.level == PASSAGE and not isinstance(obj, BioCPassage):
raise ValueError
if self.level == SENTENCE and not isinstance(obj, BioCSentence):
raise ValueError
self.writer.write(BioCJSONEncoder().default(obj)) | python | def write(self, obj: BioCDocument or BioCPassage or BioCSentence):
"""
Encode and write a single object.
Args:
obj: an instance of BioCDocument, BioCPassage, or BioCSentence
Returns:
"""
if self.level == DOCUMENT and not isinstance(obj, BioCDocument):
raise ValueError
if self.level == PASSAGE and not isinstance(obj, BioCPassage):
raise ValueError
if self.level == SENTENCE and not isinstance(obj, BioCSentence):
raise ValueError
self.writer.write(BioCJSONEncoder().default(obj)) | [
"def",
"write",
"(",
"self",
",",
"obj",
":",
"BioCDocument",
"or",
"BioCPassage",
"or",
"BioCSentence",
")",
":",
"if",
"self",
".",
"level",
"==",
"DOCUMENT",
"and",
"not",
"isinstance",
"(",
"obj",
",",
"BioCDocument",
")",
":",
"raise",
"ValueError",
... | Encode and write a single object.
Args:
obj: an instance of BioCDocument, BioCPassage, or BioCSentence
Returns: | [
"Encode",
"and",
"write",
"a",
"single",
"object",
"."
] | 47ddaa010960d9ba673aefe068e7bbaf39f0fff4 | https://github.com/yfpeng/bioc/blob/47ddaa010960d9ba673aefe068e7bbaf39f0fff4/bioc/biocjson/encoder.py#L106-L122 | train | 43,235 |
SuperCowPowers/workbench | workbench/workers/view_memory_deep.py | ViewMemoryDeep.execute | def execute(self, input_data):
''' Execute the ViewMemoryDeep worker '''
# Aggregate the output from all the memory workers, clearly this could be kewler
output = input_data['view_memory']
output['tables'] = {}
for data in [input_data[key] for key in ViewMemoryDeep.dependencies]:
for name,table in data['tables'].iteritems():
output['tables'].update({name: table})
return output | python | def execute(self, input_data):
''' Execute the ViewMemoryDeep worker '''
# Aggregate the output from all the memory workers, clearly this could be kewler
output = input_data['view_memory']
output['tables'] = {}
for data in [input_data[key] for key in ViewMemoryDeep.dependencies]:
for name,table in data['tables'].iteritems():
output['tables'].update({name: table})
return output | [
"def",
"execute",
"(",
"self",
",",
"input_data",
")",
":",
"# Aggregate the output from all the memory workers, clearly this could be kewler",
"output",
"=",
"input_data",
"[",
"'view_memory'",
"]",
"output",
"[",
"'tables'",
"]",
"=",
"{",
"}",
"for",
"data",
"in",
... | Execute the ViewMemoryDeep worker | [
"Execute",
"the",
"ViewMemoryDeep",
"worker"
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/workers/view_memory_deep.py#L11-L20 | train | 43,236 |
SuperCowPowers/workbench | workbench/workers/view_memory.py | ViewMemory.execute | def execute(self, input_data):
''' Execute the ViewMemory worker '''
# Aggregate the output from all the memory workers into concise summary info
output = {'meta': input_data['mem_meta']['tables']['info']}
output['connscan'] = list(set([item['Remote Address'] for item in input_data['mem_connscan']['tables']['connscan']]))
pslist_md5s = {self.file_to_pid(item['filename']): item['md5'] for item in input_data['mem_procdump']['tables']['dumped_files']}
output['pslist'] = ['PPID: %d PID: %d Name: %s - %s' % (item['PPID'], item['PID'], item['Name'], pslist_md5s[item['PID']])
for item in input_data['mem_pslist']['tables']['pslist']]
return output | python | def execute(self, input_data):
''' Execute the ViewMemory worker '''
# Aggregate the output from all the memory workers into concise summary info
output = {'meta': input_data['mem_meta']['tables']['info']}
output['connscan'] = list(set([item['Remote Address'] for item in input_data['mem_connscan']['tables']['connscan']]))
pslist_md5s = {self.file_to_pid(item['filename']): item['md5'] for item in input_data['mem_procdump']['tables']['dumped_files']}
output['pslist'] = ['PPID: %d PID: %d Name: %s - %s' % (item['PPID'], item['PID'], item['Name'], pslist_md5s[item['PID']])
for item in input_data['mem_pslist']['tables']['pslist']]
return output | [
"def",
"execute",
"(",
"self",
",",
"input_data",
")",
":",
"# Aggregate the output from all the memory workers into concise summary info",
"output",
"=",
"{",
"'meta'",
":",
"input_data",
"[",
"'mem_meta'",
"]",
"[",
"'tables'",
"]",
"[",
"'info'",
"]",
"}",
"outpu... | Execute the ViewMemory worker | [
"Execute",
"the",
"ViewMemory",
"worker"
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/workers/view_memory.py#L12-L21 | train | 43,237 |
IBM/ibm-cos-sdk-python-s3transfer | ibm_s3transfer/aspera/manager.py | AsperaConfig.multi_session | def multi_session(self):
''' convert the multi_session param a number '''
_val = 0
if "multi_session" in self._dict:
_val = self._dict["multi_session"]
if str(_val).lower() == 'all':
_val = -1
return int(_val) | python | def multi_session(self):
''' convert the multi_session param a number '''
_val = 0
if "multi_session" in self._dict:
_val = self._dict["multi_session"]
if str(_val).lower() == 'all':
_val = -1
return int(_val) | [
"def",
"multi_session",
"(",
"self",
")",
":",
"_val",
"=",
"0",
"if",
"\"multi_session\"",
"in",
"self",
".",
"_dict",
":",
"_val",
"=",
"self",
".",
"_dict",
"[",
"\"multi_session\"",
"]",
"if",
"str",
"(",
"_val",
")",
".",
"lower",
"(",
")",
"=="... | convert the multi_session param a number | [
"convert",
"the",
"multi_session",
"param",
"a",
"number"
] | 24ba53137213e26e6b8fc2c3ec1e8198d507d22b | https://github.com/IBM/ibm-cos-sdk-python-s3transfer/blob/24ba53137213e26e6b8fc2c3ec1e8198d507d22b/ibm_s3transfer/aspera/manager.py#L168-L176 | train | 43,238 |
IBM/ibm-cos-sdk-python-s3transfer | ibm_s3transfer/aspera/manager.py | AsperaTransferManager._raw_aspera_metadata | def _raw_aspera_metadata(self, bucket):
''' get the Aspera connection details on Aspera enabled buckets '''
response = self._client.get_bucket_aspera(Bucket=bucket)
# Parse metadata from response
aspera_access_key = response['AccessKey']['Id']
aspera_secret_key = response['AccessKey']['Secret']
ats_endpoint = response['ATSEndpoint']
return aspera_access_key, aspera_secret_key, ats_endpoint | python | def _raw_aspera_metadata(self, bucket):
''' get the Aspera connection details on Aspera enabled buckets '''
response = self._client.get_bucket_aspera(Bucket=bucket)
# Parse metadata from response
aspera_access_key = response['AccessKey']['Id']
aspera_secret_key = response['AccessKey']['Secret']
ats_endpoint = response['ATSEndpoint']
return aspera_access_key, aspera_secret_key, ats_endpoint | [
"def",
"_raw_aspera_metadata",
"(",
"self",
",",
"bucket",
")",
":",
"response",
"=",
"self",
".",
"_client",
".",
"get_bucket_aspera",
"(",
"Bucket",
"=",
"bucket",
")",
"# Parse metadata from response",
"aspera_access_key",
"=",
"response",
"[",
"'AccessKey'",
"... | get the Aspera connection details on Aspera enabled buckets | [
"get",
"the",
"Aspera",
"connection",
"details",
"on",
"Aspera",
"enabled",
"buckets"
] | 24ba53137213e26e6b8fc2c3ec1e8198d507d22b | https://github.com/IBM/ibm-cos-sdk-python-s3transfer/blob/24ba53137213e26e6b8fc2c3ec1e8198d507d22b/ibm_s3transfer/aspera/manager.py#L245-L254 | train | 43,239 |
IBM/ibm-cos-sdk-python-s3transfer | ibm_s3transfer/aspera/manager.py | AsperaTransferManager._fetch_transfer_spec | def _fetch_transfer_spec(self, node_action, token, bucket_name, paths):
''' make hhtp call to Aspera to fetch back trasnfer spec '''
aspera_access_key, aspera_secret_key, ats_endpoint = self._get_aspera_metadata(bucket_name)
_headers = {'accept': "application/json",
'Content-Type': "application/json"}
credentials = {'type': 'token',
'token': {'delegated_refresh_token': token}}
_url = ats_endpoint
_headers['X-Aspera-Storage-Credentials'] = json.dumps(credentials)
_data = {'transfer_requests': [
{'transfer_request': {'paths': paths, 'tags': {'aspera': {
'node': {'storage_credentials': credentials}}}}}]}
_session = requests.Session()
_response = _session.post(url=_url + "/files/" + node_action,
auth=(aspera_access_key, aspera_secret_key),
headers=_headers, json=_data, verify=self._config.verify_ssl)
return _response | python | def _fetch_transfer_spec(self, node_action, token, bucket_name, paths):
''' make hhtp call to Aspera to fetch back trasnfer spec '''
aspera_access_key, aspera_secret_key, ats_endpoint = self._get_aspera_metadata(bucket_name)
_headers = {'accept': "application/json",
'Content-Type': "application/json"}
credentials = {'type': 'token',
'token': {'delegated_refresh_token': token}}
_url = ats_endpoint
_headers['X-Aspera-Storage-Credentials'] = json.dumps(credentials)
_data = {'transfer_requests': [
{'transfer_request': {'paths': paths, 'tags': {'aspera': {
'node': {'storage_credentials': credentials}}}}}]}
_session = requests.Session()
_response = _session.post(url=_url + "/files/" + node_action,
auth=(aspera_access_key, aspera_secret_key),
headers=_headers, json=_data, verify=self._config.verify_ssl)
return _response | [
"def",
"_fetch_transfer_spec",
"(",
"self",
",",
"node_action",
",",
"token",
",",
"bucket_name",
",",
"paths",
")",
":",
"aspera_access_key",
",",
"aspera_secret_key",
",",
"ats_endpoint",
"=",
"self",
".",
"_get_aspera_metadata",
"(",
"bucket_name",
")",
"_heade... | make hhtp call to Aspera to fetch back trasnfer spec | [
"make",
"hhtp",
"call",
"to",
"Aspera",
"to",
"fetch",
"back",
"trasnfer",
"spec"
] | 24ba53137213e26e6b8fc2c3ec1e8198d507d22b | https://github.com/IBM/ibm-cos-sdk-python-s3transfer/blob/24ba53137213e26e6b8fc2c3ec1e8198d507d22b/ibm_s3transfer/aspera/manager.py#L256-L276 | train | 43,240 |
IBM/ibm-cos-sdk-python-s3transfer | ibm_s3transfer/aspera/manager.py | AsperaTransferManager._create_transfer_spec | def _create_transfer_spec(self, call_args):
''' pass the transfer details to aspera and receive back a
populated transfer spec complete with access token '''
_paths = []
for _file_pair in call_args.file_pair_list:
_path = OrderedDict()
if call_args.direction == enumAsperaDirection.SEND:
_action = "upload_setup"
_path['source'] = _file_pair.fileobj
_path['destination'] = _file_pair.key
else:
_action = "download_setup"
_path['source'] = _file_pair.key
_path['destination'] = _file_pair.fileobj
_paths.append(_path)
# Add credentials before the transfer spec is requested.
delegated_token = self._delegated_token_manager.get_token()
_response = self._fetch_transfer_spec(_action, delegated_token, call_args.bucket, _paths)
tspec_dict = json.loads(_response.content)['transfer_specs'][0]['transfer_spec']
tspec_dict["destination_root"] = "/"
if (call_args.transfer_config):
tspec_dict.update(call_args.transfer_config.dict)
if call_args.transfer_config.is_multi_session_all:
tspec_dict['multi_session'] = 0
_remote_host = tspec_dict['remote_host'].split('.')
# now we append '-all' to the remote host
_remote_host[0] += "-all"
tspec_dict['remote_host'] = ".".join(_remote_host)
logger.info("New remote_host(%s)" % tspec_dict['remote_host'])
call_args.transfer_spec = json.dumps(tspec_dict)
return True | python | def _create_transfer_spec(self, call_args):
''' pass the transfer details to aspera and receive back a
populated transfer spec complete with access token '''
_paths = []
for _file_pair in call_args.file_pair_list:
_path = OrderedDict()
if call_args.direction == enumAsperaDirection.SEND:
_action = "upload_setup"
_path['source'] = _file_pair.fileobj
_path['destination'] = _file_pair.key
else:
_action = "download_setup"
_path['source'] = _file_pair.key
_path['destination'] = _file_pair.fileobj
_paths.append(_path)
# Add credentials before the transfer spec is requested.
delegated_token = self._delegated_token_manager.get_token()
_response = self._fetch_transfer_spec(_action, delegated_token, call_args.bucket, _paths)
tspec_dict = json.loads(_response.content)['transfer_specs'][0]['transfer_spec']
tspec_dict["destination_root"] = "/"
if (call_args.transfer_config):
tspec_dict.update(call_args.transfer_config.dict)
if call_args.transfer_config.is_multi_session_all:
tspec_dict['multi_session'] = 0
_remote_host = tspec_dict['remote_host'].split('.')
# now we append '-all' to the remote host
_remote_host[0] += "-all"
tspec_dict['remote_host'] = ".".join(_remote_host)
logger.info("New remote_host(%s)" % tspec_dict['remote_host'])
call_args.transfer_spec = json.dumps(tspec_dict)
return True | [
"def",
"_create_transfer_spec",
"(",
"self",
",",
"call_args",
")",
":",
"_paths",
"=",
"[",
"]",
"for",
"_file_pair",
"in",
"call_args",
".",
"file_pair_list",
":",
"_path",
"=",
"OrderedDict",
"(",
")",
"if",
"call_args",
".",
"direction",
"==",
"enumAsper... | pass the transfer details to aspera and receive back a
populated transfer spec complete with access token | [
"pass",
"the",
"transfer",
"details",
"to",
"aspera",
"and",
"receive",
"back",
"a",
"populated",
"transfer",
"spec",
"complete",
"with",
"access",
"token"
] | 24ba53137213e26e6b8fc2c3ec1e8198d507d22b | https://github.com/IBM/ibm-cos-sdk-python-s3transfer/blob/24ba53137213e26e6b8fc2c3ec1e8198d507d22b/ibm_s3transfer/aspera/manager.py#L278-L314 | train | 43,241 |
IBM/ibm-cos-sdk-python-s3transfer | ibm_s3transfer/aspera/manager.py | AsperaTransferManager.upload_directory | def upload_directory(self, directory, bucket, key, transfer_config=None, subscribers=None):
''' upload a directory using Aspera '''
check_io_access(directory, os.R_OK)
return self._queue_task(bucket, [FilePair(key, directory)], transfer_config,
subscribers, enumAsperaDirection.SEND) | python | def upload_directory(self, directory, bucket, key, transfer_config=None, subscribers=None):
''' upload a directory using Aspera '''
check_io_access(directory, os.R_OK)
return self._queue_task(bucket, [FilePair(key, directory)], transfer_config,
subscribers, enumAsperaDirection.SEND) | [
"def",
"upload_directory",
"(",
"self",
",",
"directory",
",",
"bucket",
",",
"key",
",",
"transfer_config",
"=",
"None",
",",
"subscribers",
"=",
"None",
")",
":",
"check_io_access",
"(",
"directory",
",",
"os",
".",
"R_OK",
")",
"return",
"self",
".",
... | upload a directory using Aspera | [
"upload",
"a",
"directory",
"using",
"Aspera"
] | 24ba53137213e26e6b8fc2c3ec1e8198d507d22b | https://github.com/IBM/ibm-cos-sdk-python-s3transfer/blob/24ba53137213e26e6b8fc2c3ec1e8198d507d22b/ibm_s3transfer/aspera/manager.py#L316-L320 | train | 43,242 |
IBM/ibm-cos-sdk-python-s3transfer | ibm_s3transfer/aspera/manager.py | AsperaTransferManager.download_directory | def download_directory(self, bucket, key, directory, transfer_config=None, subscribers=None):
''' download a directory using Aspera '''
check_io_access(directory, os.W_OK)
return self._queue_task(bucket, [FilePair(key, directory)], transfer_config,
subscribers, enumAsperaDirection.RECEIVE) | python | def download_directory(self, bucket, key, directory, transfer_config=None, subscribers=None):
''' download a directory using Aspera '''
check_io_access(directory, os.W_OK)
return self._queue_task(bucket, [FilePair(key, directory)], transfer_config,
subscribers, enumAsperaDirection.RECEIVE) | [
"def",
"download_directory",
"(",
"self",
",",
"bucket",
",",
"key",
",",
"directory",
",",
"transfer_config",
"=",
"None",
",",
"subscribers",
"=",
"None",
")",
":",
"check_io_access",
"(",
"directory",
",",
"os",
".",
"W_OK",
")",
"return",
"self",
".",
... | download a directory using Aspera | [
"download",
"a",
"directory",
"using",
"Aspera"
] | 24ba53137213e26e6b8fc2c3ec1e8198d507d22b | https://github.com/IBM/ibm-cos-sdk-python-s3transfer/blob/24ba53137213e26e6b8fc2c3ec1e8198d507d22b/ibm_s3transfer/aspera/manager.py#L322-L326 | train | 43,243 |
IBM/ibm-cos-sdk-python-s3transfer | ibm_s3transfer/aspera/manager.py | AsperaTransferManager.upload | def upload(self, fileobj, bucket, key, transfer_config=None, subscribers=None):
''' upload a file using Aspera '''
check_io_access(fileobj, os.R_OK, True)
return self._queue_task(bucket, [FilePair(key, fileobj)], transfer_config,
subscribers, enumAsperaDirection.SEND) | python | def upload(self, fileobj, bucket, key, transfer_config=None, subscribers=None):
''' upload a file using Aspera '''
check_io_access(fileobj, os.R_OK, True)
return self._queue_task(bucket, [FilePair(key, fileobj)], transfer_config,
subscribers, enumAsperaDirection.SEND) | [
"def",
"upload",
"(",
"self",
",",
"fileobj",
",",
"bucket",
",",
"key",
",",
"transfer_config",
"=",
"None",
",",
"subscribers",
"=",
"None",
")",
":",
"check_io_access",
"(",
"fileobj",
",",
"os",
".",
"R_OK",
",",
"True",
")",
"return",
"self",
".",... | upload a file using Aspera | [
"upload",
"a",
"file",
"using",
"Aspera"
] | 24ba53137213e26e6b8fc2c3ec1e8198d507d22b | https://github.com/IBM/ibm-cos-sdk-python-s3transfer/blob/24ba53137213e26e6b8fc2c3ec1e8198d507d22b/ibm_s3transfer/aspera/manager.py#L328-L332 | train | 43,244 |
IBM/ibm-cos-sdk-python-s3transfer | ibm_s3transfer/aspera/manager.py | AsperaTransferManager.download | def download(self, bucket, key, fileobj, transfer_config=None, subscribers=None):
''' download a file using Aspera '''
check_io_access(os.path.dirname(fileobj), os.W_OK)
return self._queue_task(bucket, [FilePair(key, fileobj)], transfer_config,
subscribers, enumAsperaDirection.RECEIVE) | python | def download(self, bucket, key, fileobj, transfer_config=None, subscribers=None):
''' download a file using Aspera '''
check_io_access(os.path.dirname(fileobj), os.W_OK)
return self._queue_task(bucket, [FilePair(key, fileobj)], transfer_config,
subscribers, enumAsperaDirection.RECEIVE) | [
"def",
"download",
"(",
"self",
",",
"bucket",
",",
"key",
",",
"fileobj",
",",
"transfer_config",
"=",
"None",
",",
"subscribers",
"=",
"None",
")",
":",
"check_io_access",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"fileobj",
")",
",",
"os",
".",
... | download a file using Aspera | [
"download",
"a",
"file",
"using",
"Aspera"
] | 24ba53137213e26e6b8fc2c3ec1e8198d507d22b | https://github.com/IBM/ibm-cos-sdk-python-s3transfer/blob/24ba53137213e26e6b8fc2c3ec1e8198d507d22b/ibm_s3transfer/aspera/manager.py#L334-L338 | train | 43,245 |
IBM/ibm-cos-sdk-python-s3transfer | ibm_s3transfer/aspera/manager.py | AsperaTransferManager.set_log_details | def set_log_details(aspera_log_path=None,
sdk_log_level=logging.NOTSET):
''' set the aspera log path - used by th Ascp process
set the internal aspera sdk activity - for debug purposes '''
if aspera_log_path:
check_io_access(aspera_log_path, os.W_OK)
AsperaTransferCoordinator.set_log_location(aspera_log_path)
if sdk_log_level != logging.NOTSET:
if logger:
if not len(logger.handlers):
handler = logging.StreamHandler()
_fmt = '%(asctime)s %(levelname)s %(message)s'
handler.setFormatter(logging.Formatter(_fmt))
logger.addHandler(handler)
logger.setLevel(sdk_log_level) | python | def set_log_details(aspera_log_path=None,
sdk_log_level=logging.NOTSET):
''' set the aspera log path - used by th Ascp process
set the internal aspera sdk activity - for debug purposes '''
if aspera_log_path:
check_io_access(aspera_log_path, os.W_OK)
AsperaTransferCoordinator.set_log_location(aspera_log_path)
if sdk_log_level != logging.NOTSET:
if logger:
if not len(logger.handlers):
handler = logging.StreamHandler()
_fmt = '%(asctime)s %(levelname)s %(message)s'
handler.setFormatter(logging.Formatter(_fmt))
logger.addHandler(handler)
logger.setLevel(sdk_log_level) | [
"def",
"set_log_details",
"(",
"aspera_log_path",
"=",
"None",
",",
"sdk_log_level",
"=",
"logging",
".",
"NOTSET",
")",
":",
"if",
"aspera_log_path",
":",
"check_io_access",
"(",
"aspera_log_path",
",",
"os",
".",
"W_OK",
")",
"AsperaTransferCoordinator",
".",
... | set the aspera log path - used by th Ascp process
set the internal aspera sdk activity - for debug purposes | [
"set",
"the",
"aspera",
"log",
"path",
"-",
"used",
"by",
"th",
"Ascp",
"process",
"set",
"the",
"internal",
"aspera",
"sdk",
"activity",
"-",
"for",
"debug",
"purposes"
] | 24ba53137213e26e6b8fc2c3ec1e8198d507d22b | https://github.com/IBM/ibm-cos-sdk-python-s3transfer/blob/24ba53137213e26e6b8fc2c3ec1e8198d507d22b/ibm_s3transfer/aspera/manager.py#L341-L356 | train | 43,246 |
IBM/ibm-cos-sdk-python-s3transfer | ibm_s3transfer/aspera/manager.py | AsperaTransferManager._validate_args | def _validate_args(self, args):
''' validate the user arguments '''
assert(args.bucket)
if args.subscribers:
for _subscriber in args.subscribers:
assert(isinstance(_subscriber, AsperaBaseSubscriber))
if (args.transfer_config):
assert(isinstance(args.transfer_config, AsperaConfig))
# number of sessions requested cant be greater than max ascps
if args.transfer_config.multi_session > self._config.ascp_max_concurrent:
raise ValueError("Max sessions is %d" % self._config.ascp_max_concurrent)
for _pair in args.file_pair_list:
if not _pair.key or not _pair.fileobj:
raise ValueError("Invalid file pair") | python | def _validate_args(self, args):
''' validate the user arguments '''
assert(args.bucket)
if args.subscribers:
for _subscriber in args.subscribers:
assert(isinstance(_subscriber, AsperaBaseSubscriber))
if (args.transfer_config):
assert(isinstance(args.transfer_config, AsperaConfig))
# number of sessions requested cant be greater than max ascps
if args.transfer_config.multi_session > self._config.ascp_max_concurrent:
raise ValueError("Max sessions is %d" % self._config.ascp_max_concurrent)
for _pair in args.file_pair_list:
if not _pair.key or not _pair.fileobj:
raise ValueError("Invalid file pair") | [
"def",
"_validate_args",
"(",
"self",
",",
"args",
")",
":",
"assert",
"(",
"args",
".",
"bucket",
")",
"if",
"args",
".",
"subscribers",
":",
"for",
"_subscriber",
"in",
"args",
".",
"subscribers",
":",
"assert",
"(",
"isinstance",
"(",
"_subscriber",
"... | validate the user arguments | [
"validate",
"the",
"user",
"arguments"
] | 24ba53137213e26e6b8fc2c3ec1e8198d507d22b | https://github.com/IBM/ibm-cos-sdk-python-s3transfer/blob/24ba53137213e26e6b8fc2c3ec1e8198d507d22b/ibm_s3transfer/aspera/manager.py#L358-L375 | train | 43,247 |
IBM/ibm-cos-sdk-python-s3transfer | ibm_s3transfer/aspera/manager.py | AsperaTransferManager._shutdown | def _shutdown(self, cancel, cancel_msg, exc_type=CancelledError):
''' Internal shutdown used by 'shutdown' method above '''
if cancel:
# Cancel all in-flight transfers if requested, before waiting
# for them to complete.
self._coordinator_controller.cancel(cancel_msg, exc_type)
try:
# Wait until there are no more in-progress transfers. This is
# wrapped in a try statement because this can be interrupted
# with a KeyboardInterrupt that needs to be caught.
self._coordinator_controller.wait()
except KeyboardInterrupt:
# If not errors were raised in the try block, the cancel should
# have no coordinators it needs to run cancel on. If there was
# an error raised in the try statement we want to cancel all of
# the inflight transfers before shutting down to speed that
# process up.
self._coordinator_controller.cancel('KeyboardInterrupt()')
raise
finally:
self._coordinator_controller.cleanup() | python | def _shutdown(self, cancel, cancel_msg, exc_type=CancelledError):
''' Internal shutdown used by 'shutdown' method above '''
if cancel:
# Cancel all in-flight transfers if requested, before waiting
# for them to complete.
self._coordinator_controller.cancel(cancel_msg, exc_type)
try:
# Wait until there are no more in-progress transfers. This is
# wrapped in a try statement because this can be interrupted
# with a KeyboardInterrupt that needs to be caught.
self._coordinator_controller.wait()
except KeyboardInterrupt:
# If not errors were raised in the try block, the cancel should
# have no coordinators it needs to run cancel on. If there was
# an error raised in the try statement we want to cancel all of
# the inflight transfers before shutting down to speed that
# process up.
self._coordinator_controller.cancel('KeyboardInterrupt()')
raise
finally:
self._coordinator_controller.cleanup() | [
"def",
"_shutdown",
"(",
"self",
",",
"cancel",
",",
"cancel_msg",
",",
"exc_type",
"=",
"CancelledError",
")",
":",
"if",
"cancel",
":",
"# Cancel all in-flight transfers if requested, before waiting",
"# for them to complete.",
"self",
".",
"_coordinator_controller",
".... | Internal shutdown used by 'shutdown' method above | [
"Internal",
"shutdown",
"used",
"by",
"shutdown",
"method",
"above"
] | 24ba53137213e26e6b8fc2c3ec1e8198d507d22b | https://github.com/IBM/ibm-cos-sdk-python-s3transfer/blob/24ba53137213e26e6b8fc2c3ec1e8198d507d22b/ibm_s3transfer/aspera/manager.py#L431-L451 | train | 43,248 |
IBM/ibm-cos-sdk-python-s3transfer | ibm_s3transfer/aspera/manager.py | AsperaTransferCoordinatorController.cleanup | def cleanup(self):
''' Stop backgroud thread and cleanup resources '''
self._processing_stop = True
self._wakeup_processing_thread()
self._processing_stopped_event.wait(3) | python | def cleanup(self):
''' Stop backgroud thread and cleanup resources '''
self._processing_stop = True
self._wakeup_processing_thread()
self._processing_stopped_event.wait(3) | [
"def",
"cleanup",
"(",
"self",
")",
":",
"self",
".",
"_processing_stop",
"=",
"True",
"self",
".",
"_wakeup_processing_thread",
"(",
")",
"self",
".",
"_processing_stopped_event",
".",
"wait",
"(",
"3",
")"
] | Stop backgroud thread and cleanup resources | [
"Stop",
"backgroud",
"thread",
"and",
"cleanup",
"resources"
] | 24ba53137213e26e6b8fc2c3ec1e8198d507d22b | https://github.com/IBM/ibm-cos-sdk-python-s3transfer/blob/24ba53137213e26e6b8fc2c3ec1e8198d507d22b/ibm_s3transfer/aspera/manager.py#L475-L479 | train | 43,249 |
IBM/ibm-cos-sdk-python-s3transfer | ibm_s3transfer/aspera/manager.py | AsperaTransferCoordinatorController.tracked_coordinator_count | def tracked_coordinator_count(self, count_ascps=False):
''' count the number of cooridnators currently being processed
or count the number of ascps currently being used '''
with self._lock:
_count = 0
if count_ascps:
for _coordinator in self._tracked_transfer_coordinators:
_count += _coordinator.session_count
else:
_count = len(self._tracked_transfer_coordinators)
return _count | python | def tracked_coordinator_count(self, count_ascps=False):
''' count the number of cooridnators currently being processed
or count the number of ascps currently being used '''
with self._lock:
_count = 0
if count_ascps:
for _coordinator in self._tracked_transfer_coordinators:
_count += _coordinator.session_count
else:
_count = len(self._tracked_transfer_coordinators)
return _count | [
"def",
"tracked_coordinator_count",
"(",
"self",
",",
"count_ascps",
"=",
"False",
")",
":",
"with",
"self",
".",
"_lock",
":",
"_count",
"=",
"0",
"if",
"count_ascps",
":",
"for",
"_coordinator",
"in",
"self",
".",
"_tracked_transfer_coordinators",
":",
"_cou... | count the number of cooridnators currently being processed
or count the number of ascps currently being used | [
"count",
"the",
"number",
"of",
"cooridnators",
"currently",
"being",
"processed",
"or",
"count",
"the",
"number",
"of",
"ascps",
"currently",
"being",
"used"
] | 24ba53137213e26e6b8fc2c3ec1e8198d507d22b | https://github.com/IBM/ibm-cos-sdk-python-s3transfer/blob/24ba53137213e26e6b8fc2c3ec1e8198d507d22b/ibm_s3transfer/aspera/manager.py#L481-L491 | train | 43,250 |
IBM/ibm-cos-sdk-python-s3transfer | ibm_s3transfer/aspera/manager.py | AsperaTransferCoordinatorController._queue_task | def _queue_task(self, args):
''' add transfer to waiting queue if possible
then notify the background thread to process it '''
if self._cancel_called:
raise AsperaTransferQueueError("Cancel already called")
elif self._wait_called:
raise AsperaTransferQueueError("Cant queue items during wait")
elif self.waiting_coordinator_count() >= self._config.max_submission_queue_size:
raise AsperaTransferQueueError("Max queued items reached")
else:
_coordinator = AsperaTransferCoordinator(args)
_components = {'meta': TransferMeta(args, transfer_id=args.transfer_id),
'coordinator': _coordinator}
_transfer_future = AsperaTransferFuture(**_components)
_coordinator.add_subscribers(args.subscribers, future=_transfer_future)
_coordinator.add_done_callback(self.remove_aspera_coordinator,
transfer_coordinator=_coordinator)
self.append_waiting_queue(_coordinator)
if not self._processing_thread:
self._processing_thread = threading.Thread(target=self._process_waiting_queue)
self._processing_thread.daemon = True
self._processing_thread.start()
self._wakeup_processing_thread()
return _transfer_future | python | def _queue_task(self, args):
''' add transfer to waiting queue if possible
then notify the background thread to process it '''
if self._cancel_called:
raise AsperaTransferQueueError("Cancel already called")
elif self._wait_called:
raise AsperaTransferQueueError("Cant queue items during wait")
elif self.waiting_coordinator_count() >= self._config.max_submission_queue_size:
raise AsperaTransferQueueError("Max queued items reached")
else:
_coordinator = AsperaTransferCoordinator(args)
_components = {'meta': TransferMeta(args, transfer_id=args.transfer_id),
'coordinator': _coordinator}
_transfer_future = AsperaTransferFuture(**_components)
_coordinator.add_subscribers(args.subscribers, future=_transfer_future)
_coordinator.add_done_callback(self.remove_aspera_coordinator,
transfer_coordinator=_coordinator)
self.append_waiting_queue(_coordinator)
if not self._processing_thread:
self._processing_thread = threading.Thread(target=self._process_waiting_queue)
self._processing_thread.daemon = True
self._processing_thread.start()
self._wakeup_processing_thread()
return _transfer_future | [
"def",
"_queue_task",
"(",
"self",
",",
"args",
")",
":",
"if",
"self",
".",
"_cancel_called",
":",
"raise",
"AsperaTransferQueueError",
"(",
"\"Cancel already called\"",
")",
"elif",
"self",
".",
"_wait_called",
":",
"raise",
"AsperaTransferQueueError",
"(",
"\"C... | add transfer to waiting queue if possible
then notify the background thread to process it | [
"add",
"transfer",
"to",
"waiting",
"queue",
"if",
"possible",
"then",
"notify",
"the",
"background",
"thread",
"to",
"process",
"it"
] | 24ba53137213e26e6b8fc2c3ec1e8198d507d22b | https://github.com/IBM/ibm-cos-sdk-python-s3transfer/blob/24ba53137213e26e6b8fc2c3ec1e8198d507d22b/ibm_s3transfer/aspera/manager.py#L503-L530 | train | 43,251 |
IBM/ibm-cos-sdk-python-s3transfer | ibm_s3transfer/aspera/manager.py | AsperaTransferCoordinatorController.remove_aspera_coordinator | def remove_aspera_coordinator(self, transfer_coordinator):
''' remove entry from the waiting waiting
or remove item from processig queue and add to processed quque
notify background thread as it may be able to process watiign requests
'''
# usually called on processing completion - but can be called for a cancel
if self._in_waiting_queue(transfer_coordinator):
logger.info("Remove from waiting queue count=%d" % self.waiting_coordinator_count())
with self._lockw:
self._waiting_transfer_coordinators.remove(transfer_coordinator)
else:
logger.info("Remove from processing queue count=%d" % self.tracked_coordinator_count())
try:
self.remove_transfer_coordinator(transfer_coordinator)
self.append_processed_queue(transfer_coordinator)
except Exception:
pass
self._wakeup_processing_thread() | python | def remove_aspera_coordinator(self, transfer_coordinator):
''' remove entry from the waiting waiting
or remove item from processig queue and add to processed quque
notify background thread as it may be able to process watiign requests
'''
# usually called on processing completion - but can be called for a cancel
if self._in_waiting_queue(transfer_coordinator):
logger.info("Remove from waiting queue count=%d" % self.waiting_coordinator_count())
with self._lockw:
self._waiting_transfer_coordinators.remove(transfer_coordinator)
else:
logger.info("Remove from processing queue count=%d" % self.tracked_coordinator_count())
try:
self.remove_transfer_coordinator(transfer_coordinator)
self.append_processed_queue(transfer_coordinator)
except Exception:
pass
self._wakeup_processing_thread() | [
"def",
"remove_aspera_coordinator",
"(",
"self",
",",
"transfer_coordinator",
")",
":",
"# usually called on processing completion - but can be called for a cancel",
"if",
"self",
".",
"_in_waiting_queue",
"(",
"transfer_coordinator",
")",
":",
"logger",
".",
"info",
"(",
"... | remove entry from the waiting waiting
or remove item from processig queue and add to processed quque
notify background thread as it may be able to process watiign requests | [
"remove",
"entry",
"from",
"the",
"waiting",
"waiting",
"or",
"remove",
"item",
"from",
"processig",
"queue",
"and",
"add",
"to",
"processed",
"quque",
"notify",
"background",
"thread",
"as",
"it",
"may",
"be",
"able",
"to",
"process",
"watiign",
"requests"
] | 24ba53137213e26e6b8fc2c3ec1e8198d507d22b | https://github.com/IBM/ibm-cos-sdk-python-s3transfer/blob/24ba53137213e26e6b8fc2c3ec1e8198d507d22b/ibm_s3transfer/aspera/manager.py#L532-L550 | train | 43,252 |
IBM/ibm-cos-sdk-python-s3transfer | ibm_s3transfer/aspera/manager.py | AsperaTransferCoordinatorController.append_waiting_queue | def append_waiting_queue(self, transfer_coordinator):
''' append item to waiting queue '''
logger.debug("Add to waiting queue count=%d" % self.waiting_coordinator_count())
with self._lockw:
self._waiting_transfer_coordinators.append(transfer_coordinator) | python | def append_waiting_queue(self, transfer_coordinator):
''' append item to waiting queue '''
logger.debug("Add to waiting queue count=%d" % self.waiting_coordinator_count())
with self._lockw:
self._waiting_transfer_coordinators.append(transfer_coordinator) | [
"def",
"append_waiting_queue",
"(",
"self",
",",
"transfer_coordinator",
")",
":",
"logger",
".",
"debug",
"(",
"\"Add to waiting queue count=%d\"",
"%",
"self",
".",
"waiting_coordinator_count",
"(",
")",
")",
"with",
"self",
".",
"_lockw",
":",
"self",
".",
"_... | append item to waiting queue | [
"append",
"item",
"to",
"waiting",
"queue"
] | 24ba53137213e26e6b8fc2c3ec1e8198d507d22b | https://github.com/IBM/ibm-cos-sdk-python-s3transfer/blob/24ba53137213e26e6b8fc2c3ec1e8198d507d22b/ibm_s3transfer/aspera/manager.py#L552-L556 | train | 43,253 |
IBM/ibm-cos-sdk-python-s3transfer | ibm_s3transfer/aspera/manager.py | AsperaTransferCoordinatorController.free_processed_queue | def free_processed_queue(self):
''' call the Aspera sdk to freeup resources '''
with self._lock:
if len(self._processed_coordinators) > 0:
for _coordinator in self._processed_coordinators:
_coordinator.free_resources()
self._processed_coordinators = [] | python | def free_processed_queue(self):
''' call the Aspera sdk to freeup resources '''
with self._lock:
if len(self._processed_coordinators) > 0:
for _coordinator in self._processed_coordinators:
_coordinator.free_resources()
self._processed_coordinators = [] | [
"def",
"free_processed_queue",
"(",
"self",
")",
":",
"with",
"self",
".",
"_lock",
":",
"if",
"len",
"(",
"self",
".",
"_processed_coordinators",
")",
">",
"0",
":",
"for",
"_coordinator",
"in",
"self",
".",
"_processed_coordinators",
":",
"_coordinator",
"... | call the Aspera sdk to freeup resources | [
"call",
"the",
"Aspera",
"sdk",
"to",
"freeup",
"resources"
] | 24ba53137213e26e6b8fc2c3ec1e8198d507d22b | https://github.com/IBM/ibm-cos-sdk-python-s3transfer/blob/24ba53137213e26e6b8fc2c3ec1e8198d507d22b/ibm_s3transfer/aspera/manager.py#L567-L573 | train | 43,254 |
IBM/ibm-cos-sdk-python-s3transfer | ibm_s3transfer/aspera/manager.py | AsperaTransferCoordinatorController.is_stop | def is_stop(self):
''' has either of the stop processing flags been set '''
if len(self._processed_coordinators) > 0:
self.free_processed_queue()
return self._cancel_called or self._processing_stop | python | def is_stop(self):
''' has either of the stop processing flags been set '''
if len(self._processed_coordinators) > 0:
self.free_processed_queue()
return self._cancel_called or self._processing_stop | [
"def",
"is_stop",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"_processed_coordinators",
")",
">",
"0",
":",
"self",
".",
"free_processed_queue",
"(",
")",
"return",
"self",
".",
"_cancel_called",
"or",
"self",
".",
"_processing_stop"
] | has either of the stop processing flags been set | [
"has",
"either",
"of",
"the",
"stop",
"processing",
"flags",
"been",
"set"
] | 24ba53137213e26e6b8fc2c3ec1e8198d507d22b | https://github.com/IBM/ibm-cos-sdk-python-s3transfer/blob/24ba53137213e26e6b8fc2c3ec1e8198d507d22b/ibm_s3transfer/aspera/manager.py#L575-L579 | train | 43,255 |
IBM/ibm-cos-sdk-python-s3transfer | ibm_s3transfer/aspera/manager.py | AsperaTransferCoordinatorController._process_waiting_queue | def _process_waiting_queue(self):
''' thread to processes the waiting queue
fetches transfer spec
then calls start transfer
ensures that max ascp is not exceeded '''
logger.info("Queue processing thread started")
while not self.is_stop():
self._processing_event.wait(3)
self._processing_event.clear()
if self.is_stop():
break
while self.waiting_coordinator_count() > 0:
if self.is_stop():
break
_used_slots = self.tracked_coordinator_count(True)
_free_slots = self._config.ascp_max_concurrent - _used_slots
if _free_slots <= 0:
break
with self._lockw:
# check are there enough free slots
_req_slots = self._waiting_transfer_coordinators[0].session_count
if _req_slots > _free_slots:
break
_coordinator = self._waiting_transfer_coordinators.popleft()
self.add_transfer_coordinator(_coordinator)
if not _coordinator.set_transfer_spec():
self.remove_aspera_coordinator(_coordinator)
else:
logger.info("ASCP process queue - Max(%d) InUse(%d) Free(%d) New(%d)" %
(self._config.ascp_max_concurrent,
_used_slots,
_free_slots,
_req_slots))
_coordinator.start_transfer()
logger.info("Queue processing thread stopped")
self._processing_stopped_event.set() | python | def _process_waiting_queue(self):
''' thread to processes the waiting queue
fetches transfer spec
then calls start transfer
ensures that max ascp is not exceeded '''
logger.info("Queue processing thread started")
while not self.is_stop():
self._processing_event.wait(3)
self._processing_event.clear()
if self.is_stop():
break
while self.waiting_coordinator_count() > 0:
if self.is_stop():
break
_used_slots = self.tracked_coordinator_count(True)
_free_slots = self._config.ascp_max_concurrent - _used_slots
if _free_slots <= 0:
break
with self._lockw:
# check are there enough free slots
_req_slots = self._waiting_transfer_coordinators[0].session_count
if _req_slots > _free_slots:
break
_coordinator = self._waiting_transfer_coordinators.popleft()
self.add_transfer_coordinator(_coordinator)
if not _coordinator.set_transfer_spec():
self.remove_aspera_coordinator(_coordinator)
else:
logger.info("ASCP process queue - Max(%d) InUse(%d) Free(%d) New(%d)" %
(self._config.ascp_max_concurrent,
_used_slots,
_free_slots,
_req_slots))
_coordinator.start_transfer()
logger.info("Queue processing thread stopped")
self._processing_stopped_event.set() | [
"def",
"_process_waiting_queue",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"\"Queue processing thread started\"",
")",
"while",
"not",
"self",
".",
"is_stop",
"(",
")",
":",
"self",
".",
"_processing_event",
".",
"wait",
"(",
"3",
")",
"self",
".",
... | thread to processes the waiting queue
fetches transfer spec
then calls start transfer
ensures that max ascp is not exceeded | [
"thread",
"to",
"processes",
"the",
"waiting",
"queue",
"fetches",
"transfer",
"spec",
"then",
"calls",
"start",
"transfer",
"ensures",
"that",
"max",
"ascp",
"is",
"not",
"exceeded"
] | 24ba53137213e26e6b8fc2c3ec1e8198d507d22b | https://github.com/IBM/ibm-cos-sdk-python-s3transfer/blob/24ba53137213e26e6b8fc2c3ec1e8198d507d22b/ibm_s3transfer/aspera/manager.py#L581-L620 | train | 43,256 |
IBM/ibm-cos-sdk-python-s3transfer | ibm_s3transfer/aspera/manager.py | AsperaTransferCoordinatorController.clear_waiting_coordinators | def clear_waiting_coordinators(self, cancel=False):
''' remove all entries from waiting queue or cancell all in waiting queue '''
with self._lockw:
if cancel:
for _coordinator in self._waiting_transfer_coordinators:
_coordinator.notify_cancelled("Clear Waiting Queue", False)
self._waiting_transfer_coordinators.clear() | python | def clear_waiting_coordinators(self, cancel=False):
''' remove all entries from waiting queue or cancell all in waiting queue '''
with self._lockw:
if cancel:
for _coordinator in self._waiting_transfer_coordinators:
_coordinator.notify_cancelled("Clear Waiting Queue", False)
self._waiting_transfer_coordinators.clear() | [
"def",
"clear_waiting_coordinators",
"(",
"self",
",",
"cancel",
"=",
"False",
")",
":",
"with",
"self",
".",
"_lockw",
":",
"if",
"cancel",
":",
"for",
"_coordinator",
"in",
"self",
".",
"_waiting_transfer_coordinators",
":",
"_coordinator",
".",
"notify_cancel... | remove all entries from waiting queue or cancell all in waiting queue | [
"remove",
"all",
"entries",
"from",
"waiting",
"queue",
"or",
"cancell",
"all",
"in",
"waiting",
"queue"
] | 24ba53137213e26e6b8fc2c3ec1e8198d507d22b | https://github.com/IBM/ibm-cos-sdk-python-s3transfer/blob/24ba53137213e26e6b8fc2c3ec1e8198d507d22b/ibm_s3transfer/aspera/manager.py#L622-L628 | train | 43,257 |
IBM/ibm-cos-sdk-python-s3transfer | ibm_s3transfer/aspera/manager.py | AsperaTransferCoordinatorController.cancel | def cancel(self, *args, **kwargs):
""" Cancel all queue items - then attempt to cancel all in progress items """
self._cancel_called = True
self.clear_waiting_coordinators(cancel=True)
super(AsperaTransferCoordinatorController, self).cancel(*args, **kwargs) | python | def cancel(self, *args, **kwargs):
""" Cancel all queue items - then attempt to cancel all in progress items """
self._cancel_called = True
self.clear_waiting_coordinators(cancel=True)
super(AsperaTransferCoordinatorController, self).cancel(*args, **kwargs) | [
"def",
"cancel",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_cancel_called",
"=",
"True",
"self",
".",
"clear_waiting_coordinators",
"(",
"cancel",
"=",
"True",
")",
"super",
"(",
"AsperaTransferCoordinatorController",
",... | Cancel all queue items - then attempt to cancel all in progress items | [
"Cancel",
"all",
"queue",
"items",
"-",
"then",
"attempt",
"to",
"cancel",
"all",
"in",
"progress",
"items"
] | 24ba53137213e26e6b8fc2c3ec1e8198d507d22b | https://github.com/IBM/ibm-cos-sdk-python-s3transfer/blob/24ba53137213e26e6b8fc2c3ec1e8198d507d22b/ibm_s3transfer/aspera/manager.py#L630-L634 | train | 43,258 |
IBM/ibm-cos-sdk-python-s3transfer | ibm_s3transfer/aspera/manager.py | AsperaTransferCoordinatorController.wait | def wait(self):
""" Wait until all in progress and queued items are processed """
self._wait_called = True
while self.tracked_coordinator_count() > 0 or \
self.waiting_coordinator_count() > 0:
time.sleep(1)
super(AsperaTransferCoordinatorController, self).wait()
self._wait_called = False | python | def wait(self):
""" Wait until all in progress and queued items are processed """
self._wait_called = True
while self.tracked_coordinator_count() > 0 or \
self.waiting_coordinator_count() > 0:
time.sleep(1)
super(AsperaTransferCoordinatorController, self).wait()
self._wait_called = False | [
"def",
"wait",
"(",
"self",
")",
":",
"self",
".",
"_wait_called",
"=",
"True",
"while",
"self",
".",
"tracked_coordinator_count",
"(",
")",
">",
"0",
"or",
"self",
".",
"waiting_coordinator_count",
"(",
")",
">",
"0",
":",
"time",
".",
"sleep",
"(",
"... | Wait until all in progress and queued items are processed | [
"Wait",
"until",
"all",
"in",
"progress",
"and",
"queued",
"items",
"are",
"processed"
] | 24ba53137213e26e6b8fc2c3ec1e8198d507d22b | https://github.com/IBM/ibm-cos-sdk-python-s3transfer/blob/24ba53137213e26e6b8fc2c3ec1e8198d507d22b/ibm_s3transfer/aspera/manager.py#L636-L643 | train | 43,259 |
SuperCowPowers/workbench | workbench/workers/view_zip.py | ViewZip.execute | def execute(self, input_data):
''' Execute the ViewZip worker '''
# Just a small check to make sure we haven't been called on the wrong file type
if (input_data['meta']['type_tag'] != 'zip'):
return {'error': self.__class__.__name__+': called on '+input_data['meta']['type_tag']}
view = {}
view['payload_md5s'] = input_data['unzip']['payload_md5s']
view['yara_sigs'] = input_data['yara_sigs']['matches'].keys()
view.update(input_data['meta'])
# Okay this view is going to also give the meta data about the payloads
view['payload_meta'] = [self.workbench.work_request('meta', md5) for md5 in input_data['unzip']['payload_md5s']]
return view | python | def execute(self, input_data):
''' Execute the ViewZip worker '''
# Just a small check to make sure we haven't been called on the wrong file type
if (input_data['meta']['type_tag'] != 'zip'):
return {'error': self.__class__.__name__+': called on '+input_data['meta']['type_tag']}
view = {}
view['payload_md5s'] = input_data['unzip']['payload_md5s']
view['yara_sigs'] = input_data['yara_sigs']['matches'].keys()
view.update(input_data['meta'])
# Okay this view is going to also give the meta data about the payloads
view['payload_meta'] = [self.workbench.work_request('meta', md5) for md5 in input_data['unzip']['payload_md5s']]
return view | [
"def",
"execute",
"(",
"self",
",",
"input_data",
")",
":",
"# Just a small check to make sure we haven't been called on the wrong file type",
"if",
"(",
"input_data",
"[",
"'meta'",
"]",
"[",
"'type_tag'",
"]",
"!=",
"'zip'",
")",
":",
"return",
"{",
"'error'",
":"... | Execute the ViewZip worker | [
"Execute",
"the",
"ViewZip",
"worker"
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/workers/view_zip.py#L15-L29 | train | 43,260 |
IBM/ibm-cos-sdk-python-s3transfer | ibm_s3transfer/aspera/futures.py | AsperaTransferFuture.set_exception | def set_exception(self, exception):
"""Sets the exception on the future."""
if not self.is_done():
raise TransferNotDoneError(
'set_exception can only be called once the transfer is '
'complete.')
self._coordinator.set_exception(exception, override=True) | python | def set_exception(self, exception):
"""Sets the exception on the future."""
if not self.is_done():
raise TransferNotDoneError(
'set_exception can only be called once the transfer is '
'complete.')
self._coordinator.set_exception(exception, override=True) | [
"def",
"set_exception",
"(",
"self",
",",
"exception",
")",
":",
"if",
"not",
"self",
".",
"is_done",
"(",
")",
":",
"raise",
"TransferNotDoneError",
"(",
"'set_exception can only be called once the transfer is '",
"'complete.'",
")",
"self",
".",
"_coordinator",
".... | Sets the exception on the future. | [
"Sets",
"the",
"exception",
"on",
"the",
"future",
"."
] | 24ba53137213e26e6b8fc2c3ec1e8198d507d22b | https://github.com/IBM/ibm-cos-sdk-python-s3transfer/blob/24ba53137213e26e6b8fc2c3ec1e8198d507d22b/ibm_s3transfer/aspera/futures.py#L126-L132 | train | 43,261 |
IBM/ibm-cos-sdk-python-s3transfer | ibm_s3transfer/aspera/futures.py | AsperaTransferListener.transferReporter | def transferReporter(self, xferId, message):
''' the callback method used by the Aspera sdk during transfer
to notify progress, error or successful completion
'''
if self.is_stopped():
return True
_asp_message = AsperaMessage(message)
if not _asp_message.is_msg_type(
[enumAsperaMsgType.INIT,
enumAsperaMsgType.DONE,
enumAsperaMsgType.ERROR,
enumAsperaMsgType.FILEERROR,
enumAsperaMsgType.STATS]):
return
_session_id = _asp_message.get_session_id()
_msg = self.debug_id(xferId, _session_id) + " : " + _asp_message._msg_type
logger.info(_msg)
with self._session_lock:
if _asp_message.is_msg_type([enumAsperaMsgType.INIT]):
assert(_session_id not in self._sessions)
_session = AsperaSession(_session_id)
self._sessions[_session_id] = _session
self.notify_init()
else:
_session = self._sessions[_session_id]
if _asp_message.is_msg_type([enumAsperaMsgType.DONE]):
if _session.set_bytes_transferred(_asp_message.get_bytes_transferred()):
self.notify_progress()
_session.set_success()
self.notify_done()
elif _asp_message.is_msg_type([enumAsperaMsgType.ERROR, enumAsperaMsgType.FILEERROR]):
_session.set_error(_asp_message.get_error_descr())
self.notify_done(error=True)
elif _asp_message.is_msg_type([enumAsperaMsgType.STATS]):
if _session.set_bytes_transferred(_asp_message.get_bytes_transferred()):
self.notify_progress() | python | def transferReporter(self, xferId, message):
''' the callback method used by the Aspera sdk during transfer
to notify progress, error or successful completion
'''
if self.is_stopped():
return True
_asp_message = AsperaMessage(message)
if not _asp_message.is_msg_type(
[enumAsperaMsgType.INIT,
enumAsperaMsgType.DONE,
enumAsperaMsgType.ERROR,
enumAsperaMsgType.FILEERROR,
enumAsperaMsgType.STATS]):
return
_session_id = _asp_message.get_session_id()
_msg = self.debug_id(xferId, _session_id) + " : " + _asp_message._msg_type
logger.info(_msg)
with self._session_lock:
if _asp_message.is_msg_type([enumAsperaMsgType.INIT]):
assert(_session_id not in self._sessions)
_session = AsperaSession(_session_id)
self._sessions[_session_id] = _session
self.notify_init()
else:
_session = self._sessions[_session_id]
if _asp_message.is_msg_type([enumAsperaMsgType.DONE]):
if _session.set_bytes_transferred(_asp_message.get_bytes_transferred()):
self.notify_progress()
_session.set_success()
self.notify_done()
elif _asp_message.is_msg_type([enumAsperaMsgType.ERROR, enumAsperaMsgType.FILEERROR]):
_session.set_error(_asp_message.get_error_descr())
self.notify_done(error=True)
elif _asp_message.is_msg_type([enumAsperaMsgType.STATS]):
if _session.set_bytes_transferred(_asp_message.get_bytes_transferred()):
self.notify_progress() | [
"def",
"transferReporter",
"(",
"self",
",",
"xferId",
",",
"message",
")",
":",
"if",
"self",
".",
"is_stopped",
"(",
")",
":",
"return",
"True",
"_asp_message",
"=",
"AsperaMessage",
"(",
"message",
")",
"if",
"not",
"_asp_message",
".",
"is_msg_type",
"... | the callback method used by the Aspera sdk during transfer
to notify progress, error or successful completion | [
"the",
"callback",
"method",
"used",
"by",
"the",
"Aspera",
"sdk",
"during",
"transfer",
"to",
"notify",
"progress",
"error",
"or",
"successful",
"completion"
] | 24ba53137213e26e6b8fc2c3ec1e8198d507d22b | https://github.com/IBM/ibm-cos-sdk-python-s3transfer/blob/24ba53137213e26e6b8fc2c3ec1e8198d507d22b/ibm_s3transfer/aspera/futures.py#L160-L201 | train | 43,262 |
IBM/ibm-cos-sdk-python-s3transfer | ibm_s3transfer/aspera/futures.py | AsperaTransferListener.start_transfer | def start_transfer(self):
''' pass the transfer spec to the Aspera sdk and start the transfer '''
try:
if not self.is_done():
faspmanager2.startTransfer(self.get_transfer_id(),
None,
self.get_transfer_spec(),
self)
except Exception as ex:
self.notify_exception(ex) | python | def start_transfer(self):
''' pass the transfer spec to the Aspera sdk and start the transfer '''
try:
if not self.is_done():
faspmanager2.startTransfer(self.get_transfer_id(),
None,
self.get_transfer_spec(),
self)
except Exception as ex:
self.notify_exception(ex) | [
"def",
"start_transfer",
"(",
"self",
")",
":",
"try",
":",
"if",
"not",
"self",
".",
"is_done",
"(",
")",
":",
"faspmanager2",
".",
"startTransfer",
"(",
"self",
".",
"get_transfer_id",
"(",
")",
",",
"None",
",",
"self",
".",
"get_transfer_spec",
"(",
... | pass the transfer spec to the Aspera sdk and start the transfer | [
"pass",
"the",
"transfer",
"spec",
"to",
"the",
"Aspera",
"sdk",
"and",
"start",
"the",
"transfer"
] | 24ba53137213e26e6b8fc2c3ec1e8198d507d22b | https://github.com/IBM/ibm-cos-sdk-python-s3transfer/blob/24ba53137213e26e6b8fc2c3ec1e8198d507d22b/ibm_s3transfer/aspera/futures.py#L203-L212 | train | 43,263 |
IBM/ibm-cos-sdk-python-s3transfer | ibm_s3transfer/aspera/futures.py | AsperaTransferListener.is_running | def is_running(self, is_stopped):
''' check whether a transfer is currently running '''
if is_stopped and self.is_stopped():
return False
return faspmanager2.isRunning(self.get_transfer_id()) | python | def is_running(self, is_stopped):
''' check whether a transfer is currently running '''
if is_stopped and self.is_stopped():
return False
return faspmanager2.isRunning(self.get_transfer_id()) | [
"def",
"is_running",
"(",
"self",
",",
"is_stopped",
")",
":",
"if",
"is_stopped",
"and",
"self",
".",
"is_stopped",
"(",
")",
":",
"return",
"False",
"return",
"faspmanager2",
".",
"isRunning",
"(",
"self",
".",
"get_transfer_id",
"(",
")",
")"
] | check whether a transfer is currently running | [
"check",
"whether",
"a",
"transfer",
"is",
"currently",
"running"
] | 24ba53137213e26e6b8fc2c3ec1e8198d507d22b | https://github.com/IBM/ibm-cos-sdk-python-s3transfer/blob/24ba53137213e26e6b8fc2c3ec1e8198d507d22b/ibm_s3transfer/aspera/futures.py#L227-L232 | train | 43,264 |
IBM/ibm-cos-sdk-python-s3transfer | ibm_s3transfer/aspera/futures.py | AsperaTransferListener.is_stopped | def is_stopped(self, is_stopping=True):
''' check whether a transfer is stopped or is being stopped '''
if is_stopping:
return self._is_stopped or self._is_stopping
return self._is_stopped | python | def is_stopped(self, is_stopping=True):
''' check whether a transfer is stopped or is being stopped '''
if is_stopping:
return self._is_stopped or self._is_stopping
return self._is_stopped | [
"def",
"is_stopped",
"(",
"self",
",",
"is_stopping",
"=",
"True",
")",
":",
"if",
"is_stopping",
":",
"return",
"self",
".",
"_is_stopped",
"or",
"self",
".",
"_is_stopping",
"return",
"self",
".",
"_is_stopped"
] | check whether a transfer is stopped or is being stopped | [
"check",
"whether",
"a",
"transfer",
"is",
"stopped",
"or",
"is",
"being",
"stopped"
] | 24ba53137213e26e6b8fc2c3ec1e8198d507d22b | https://github.com/IBM/ibm-cos-sdk-python-s3transfer/blob/24ba53137213e26e6b8fc2c3ec1e8198d507d22b/ibm_s3transfer/aspera/futures.py#L234-L238 | train | 43,265 |
IBM/ibm-cos-sdk-python-s3transfer | ibm_s3transfer/aspera/futures.py | AsperaTransferListener.free_resources | def free_resources(self):
''' call stop to free up resources '''
if not self.is_stopped():
logger.info("Freeing resources: %s" % self.get_transfer_id())
self.stop(True) | python | def free_resources(self):
''' call stop to free up resources '''
if not self.is_stopped():
logger.info("Freeing resources: %s" % self.get_transfer_id())
self.stop(True) | [
"def",
"free_resources",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_stopped",
"(",
")",
":",
"logger",
".",
"info",
"(",
"\"Freeing resources: %s\"",
"%",
"self",
".",
"get_transfer_id",
"(",
")",
")",
"self",
".",
"stop",
"(",
"True",
")"
] | call stop to free up resources | [
"call",
"stop",
"to",
"free",
"up",
"resources"
] | 24ba53137213e26e6b8fc2c3ec1e8198d507d22b | https://github.com/IBM/ibm-cos-sdk-python-s3transfer/blob/24ba53137213e26e6b8fc2c3ec1e8198d507d22b/ibm_s3transfer/aspera/futures.py#L276-L280 | train | 43,266 |
IBM/ibm-cos-sdk-python-s3transfer | ibm_s3transfer/aspera/futures.py | AsperaMessage.extract_message_value | def extract_message_value(self, name):
''' search message to find and extract a named value '''
name += ":"
assert(self._message)
_start = self._message.find(name)
if _start >= 0:
_start += len(name) + 1
_end = self._message.find("\n", _start)
_value = self._message[_start:_end]
return _value.strip()
return None | python | def extract_message_value(self, name):
''' search message to find and extract a named value '''
name += ":"
assert(self._message)
_start = self._message.find(name)
if _start >= 0:
_start += len(name) + 1
_end = self._message.find("\n", _start)
_value = self._message[_start:_end]
return _value.strip()
return None | [
"def",
"extract_message_value",
"(",
"self",
",",
"name",
")",
":",
"name",
"+=",
"\":\"",
"assert",
"(",
"self",
".",
"_message",
")",
"_start",
"=",
"self",
".",
"_message",
".",
"find",
"(",
"name",
")",
"if",
"_start",
">=",
"0",
":",
"_start",
"... | search message to find and extract a named value | [
"search",
"message",
"to",
"find",
"and",
"extract",
"a",
"named",
"value"
] | 24ba53137213e26e6b8fc2c3ec1e8198d507d22b | https://github.com/IBM/ibm-cos-sdk-python-s3transfer/blob/24ba53137213e26e6b8fc2c3ec1e8198d507d22b/ibm_s3transfer/aspera/futures.py#L302-L313 | train | 43,267 |
IBM/ibm-cos-sdk-python-s3transfer | ibm_s3transfer/aspera/futures.py | AsperaSession.set_bytes_transferred | def set_bytes_transferred(self, bytes_transferred):
''' set the number of bytes transferred - if it has changed return True '''
_changed = False
if bytes_transferred:
_changed = (self._bytes_transferred != int(bytes_transferred))
if _changed:
self._bytes_transferred = int(bytes_transferred)
logger.debug("(%s) BytesTransferred: %d" % (
self.session_id, self._bytes_transferred))
if AsperaSession.PROGRESS_MSGS_SEND_ALL:
return True
return _changed | python | def set_bytes_transferred(self, bytes_transferred):
''' set the number of bytes transferred - if it has changed return True '''
_changed = False
if bytes_transferred:
_changed = (self._bytes_transferred != int(bytes_transferred))
if _changed:
self._bytes_transferred = int(bytes_transferred)
logger.debug("(%s) BytesTransferred: %d" % (
self.session_id, self._bytes_transferred))
if AsperaSession.PROGRESS_MSGS_SEND_ALL:
return True
return _changed | [
"def",
"set_bytes_transferred",
"(",
"self",
",",
"bytes_transferred",
")",
":",
"_changed",
"=",
"False",
"if",
"bytes_transferred",
":",
"_changed",
"=",
"(",
"self",
".",
"_bytes_transferred",
"!=",
"int",
"(",
"bytes_transferred",
")",
")",
"if",
"_changed",... | set the number of bytes transferred - if it has changed return True | [
"set",
"the",
"number",
"of",
"bytes",
"transferred",
"-",
"if",
"it",
"has",
"changed",
"return",
"True"
] | 24ba53137213e26e6b8fc2c3ec1e8198d507d22b | https://github.com/IBM/ibm-cos-sdk-python-s3transfer/blob/24ba53137213e26e6b8fc2c3ec1e8198d507d22b/ibm_s3transfer/aspera/futures.py#L361-L372 | train | 43,268 |
IBM/ibm-cos-sdk-python-s3transfer | ibm_s3transfer/aspera/futures.py | AsperaSession.set_exception | def set_exception(self, exception):
''' set the exception message and set the status to failed '''
logger.error("%s : %s" % (exception.__class__.__name__, str(exception)))
self._set_status(enumAsperaControllerStatus.FAILED, exception) | python | def set_exception(self, exception):
''' set the exception message and set the status to failed '''
logger.error("%s : %s" % (exception.__class__.__name__, str(exception)))
self._set_status(enumAsperaControllerStatus.FAILED, exception) | [
"def",
"set_exception",
"(",
"self",
",",
"exception",
")",
":",
"logger",
".",
"error",
"(",
"\"%s : %s\"",
"%",
"(",
"exception",
".",
"__class__",
".",
"__name__",
",",
"str",
"(",
"exception",
")",
")",
")",
"self",
".",
"_set_status",
"(",
"enumAspe... | set the exception message and set the status to failed | [
"set",
"the",
"exception",
"message",
"and",
"set",
"the",
"status",
"to",
"failed"
] | 24ba53137213e26e6b8fc2c3ec1e8198d507d22b | https://github.com/IBM/ibm-cos-sdk-python-s3transfer/blob/24ba53137213e26e6b8fc2c3ec1e8198d507d22b/ibm_s3transfer/aspera/futures.py#L383-L386 | train | 43,269 |
IBM/ibm-cos-sdk-python-s3transfer | ibm_s3transfer/aspera/futures.py | AsperaSession.wait | def wait(self):
''' wait for the done event to be set - no timeout'''
self._done_event.wait(MAXINT)
return self._status, self._exception | python | def wait(self):
''' wait for the done event to be set - no timeout'''
self._done_event.wait(MAXINT)
return self._status, self._exception | [
"def",
"wait",
"(",
"self",
")",
":",
"self",
".",
"_done_event",
".",
"wait",
"(",
"MAXINT",
")",
"return",
"self",
".",
"_status",
",",
"self",
".",
"_exception"
] | wait for the done event to be set - no timeout | [
"wait",
"for",
"the",
"done",
"event",
"to",
"be",
"set",
"-",
"no",
"timeout"
] | 24ba53137213e26e6b8fc2c3ec1e8198d507d22b | https://github.com/IBM/ibm-cos-sdk-python-s3transfer/blob/24ba53137213e26e6b8fc2c3ec1e8198d507d22b/ibm_s3transfer/aspera/futures.py#L416-L419 | train | 43,270 |
IBM/ibm-cos-sdk-python-s3transfer | ibm_s3transfer/aspera/futures.py | AsperaTransferCoordinator.result | def result(self, raise_exception=True):
"""Waits until TransferFuture is done and returns the result
If the TransferFuture succeeded, it will return the result. If the
TransferFuture failed, it will raise the exception associated to the
failure.
"""
_status = None
_exception = None
self._done_event.wait(MAXINT) # first wait for session global
if self.is_failed(): # global exception set
_exception = self._exception
_status = enumAsperaControllerStatus.FAILED
else:
for _session in self._sessions.values():
_status_tmp, _exception_tmp = _session.wait()
if _exception_tmp and not _exception:
_exception = _exception_tmp
_status = _status_tmp
# Once done waiting, raise an exception if present or return the final status
if _exception and raise_exception:
raise _exception
return _status | python | def result(self, raise_exception=True):
"""Waits until TransferFuture is done and returns the result
If the TransferFuture succeeded, it will return the result. If the
TransferFuture failed, it will raise the exception associated to the
failure.
"""
_status = None
_exception = None
self._done_event.wait(MAXINT) # first wait for session global
if self.is_failed(): # global exception set
_exception = self._exception
_status = enumAsperaControllerStatus.FAILED
else:
for _session in self._sessions.values():
_status_tmp, _exception_tmp = _session.wait()
if _exception_tmp and not _exception:
_exception = _exception_tmp
_status = _status_tmp
# Once done waiting, raise an exception if present or return the final status
if _exception and raise_exception:
raise _exception
return _status | [
"def",
"result",
"(",
"self",
",",
"raise_exception",
"=",
"True",
")",
":",
"_status",
"=",
"None",
"_exception",
"=",
"None",
"self",
".",
"_done_event",
".",
"wait",
"(",
"MAXINT",
")",
"# first wait for session global",
"if",
"self",
".",
"is_failed",
"(... | Waits until TransferFuture is done and returns the result
If the TransferFuture succeeded, it will return the result. If the
TransferFuture failed, it will raise the exception associated to the
failure. | [
"Waits",
"until",
"TransferFuture",
"is",
"done",
"and",
"returns",
"the",
"result"
] | 24ba53137213e26e6b8fc2c3ec1e8198d507d22b | https://github.com/IBM/ibm-cos-sdk-python-s3transfer/blob/24ba53137213e26e6b8fc2c3ec1e8198d507d22b/ibm_s3transfer/aspera/futures.py#L471-L495 | train | 43,271 |
IBM/ibm-cos-sdk-python-s3transfer | ibm_s3transfer/aspera/futures.py | AsperaTransferCoordinator.notify_init | def notify_init(self):
''' run the queed callback for just the first session only '''
_session_count = len(self._sessions)
self._update_session_count(1, _session_count)
if _session_count == 1:
self._run_queued_callbacks() | python | def notify_init(self):
''' run the queed callback for just the first session only '''
_session_count = len(self._sessions)
self._update_session_count(1, _session_count)
if _session_count == 1:
self._run_queued_callbacks() | [
"def",
"notify_init",
"(",
"self",
")",
":",
"_session_count",
"=",
"len",
"(",
"self",
".",
"_sessions",
")",
"self",
".",
"_update_session_count",
"(",
"1",
",",
"_session_count",
")",
"if",
"_session_count",
"==",
"1",
":",
"self",
".",
"_run_queued_callb... | run the queed callback for just the first session only | [
"run",
"the",
"queed",
"callback",
"for",
"just",
"the",
"first",
"session",
"only"
] | 24ba53137213e26e6b8fc2c3ec1e8198d507d22b | https://github.com/IBM/ibm-cos-sdk-python-s3transfer/blob/24ba53137213e26e6b8fc2c3ec1e8198d507d22b/ibm_s3transfer/aspera/futures.py#L501-L506 | train | 43,272 |
IBM/ibm-cos-sdk-python-s3transfer | ibm_s3transfer/aspera/futures.py | AsperaTransferCoordinator.notify_done | def notify_done(self, error=False, run_done_callbacks=True):
''' if error clear all sessions otherwise check to see if all other sessions are complete
then run the done callbacks
'''
if error:
for _session in self._sessions.values():
_session.set_done()
self._session_count = 0
else:
self._update_session_count(-1)
for _session in self._sessions.values():
if not _session.is_done():
return
if run_done_callbacks:
self._run_done_callbacks()
self._done_event.set() | python | def notify_done(self, error=False, run_done_callbacks=True):
''' if error clear all sessions otherwise check to see if all other sessions are complete
then run the done callbacks
'''
if error:
for _session in self._sessions.values():
_session.set_done()
self._session_count = 0
else:
self._update_session_count(-1)
for _session in self._sessions.values():
if not _session.is_done():
return
if run_done_callbacks:
self._run_done_callbacks()
self._done_event.set() | [
"def",
"notify_done",
"(",
"self",
",",
"error",
"=",
"False",
",",
"run_done_callbacks",
"=",
"True",
")",
":",
"if",
"error",
":",
"for",
"_session",
"in",
"self",
".",
"_sessions",
".",
"values",
"(",
")",
":",
"_session",
".",
"set_done",
"(",
")",... | if error clear all sessions otherwise check to see if all other sessions are complete
then run the done callbacks | [
"if",
"error",
"clear",
"all",
"sessions",
"otherwise",
"check",
"to",
"see",
"if",
"all",
"other",
"sessions",
"are",
"complete",
"then",
"run",
"the",
"done",
"callbacks"
] | 24ba53137213e26e6b8fc2c3ec1e8198d507d22b | https://github.com/IBM/ibm-cos-sdk-python-s3transfer/blob/24ba53137213e26e6b8fc2c3ec1e8198d507d22b/ibm_s3transfer/aspera/futures.py#L508-L524 | train | 43,273 |
IBM/ibm-cos-sdk-python-s3transfer | ibm_s3transfer/aspera/futures.py | AsperaTransferCoordinator.notify_progress | def notify_progress(self):
''' only call the progress callback if total has changed
or PROGRESS_MSGS_SEND_ALL is set '''
_total = 0
for _session in self._sessions.values():
_total += _session.bytes_transferred
if AsperaSession.PROGRESS_MSGS_SEND_ALL:
self._run_progress_callbacks(_total)
else:
# dont call progress callback unless total has changed
if self._total_bytes_transferred != _total:
self._total_bytes_transferred = _total
self._run_progress_callbacks(_total) | python | def notify_progress(self):
''' only call the progress callback if total has changed
or PROGRESS_MSGS_SEND_ALL is set '''
_total = 0
for _session in self._sessions.values():
_total += _session.bytes_transferred
if AsperaSession.PROGRESS_MSGS_SEND_ALL:
self._run_progress_callbacks(_total)
else:
# dont call progress callback unless total has changed
if self._total_bytes_transferred != _total:
self._total_bytes_transferred = _total
self._run_progress_callbacks(_total) | [
"def",
"notify_progress",
"(",
"self",
")",
":",
"_total",
"=",
"0",
"for",
"_session",
"in",
"self",
".",
"_sessions",
".",
"values",
"(",
")",
":",
"_total",
"+=",
"_session",
".",
"bytes_transferred",
"if",
"AsperaSession",
".",
"PROGRESS_MSGS_SEND_ALL",
... | only call the progress callback if total has changed
or PROGRESS_MSGS_SEND_ALL is set | [
"only",
"call",
"the",
"progress",
"callback",
"if",
"total",
"has",
"changed",
"or",
"PROGRESS_MSGS_SEND_ALL",
"is",
"set"
] | 24ba53137213e26e6b8fc2c3ec1e8198d507d22b | https://github.com/IBM/ibm-cos-sdk-python-s3transfer/blob/24ba53137213e26e6b8fc2c3ec1e8198d507d22b/ibm_s3transfer/aspera/futures.py#L526-L539 | train | 43,274 |
IBM/ibm-cos-sdk-python-s3transfer | ibm_s3transfer/aspera/futures.py | AsperaTransferCoordinator.notify_exception | def notify_exception(self, exception, run_done_callbacks=True):
''' set the exception message, stop transfer if running and set the done event '''
logger.error("%s : %s" % (exception.__class__.__name__, str(exception)))
self._exception = exception
if self.is_running(True):
# wait for a short 5 seconds for it to finish
for _cnt in range(0, 5):
if not self._cancel():
time.sleep(1)
else:
break
self.notify_done(error=True, run_done_callbacks=run_done_callbacks) | python | def notify_exception(self, exception, run_done_callbacks=True):
''' set the exception message, stop transfer if running and set the done event '''
logger.error("%s : %s" % (exception.__class__.__name__, str(exception)))
self._exception = exception
if self.is_running(True):
# wait for a short 5 seconds for it to finish
for _cnt in range(0, 5):
if not self._cancel():
time.sleep(1)
else:
break
self.notify_done(error=True, run_done_callbacks=run_done_callbacks) | [
"def",
"notify_exception",
"(",
"self",
",",
"exception",
",",
"run_done_callbacks",
"=",
"True",
")",
":",
"logger",
".",
"error",
"(",
"\"%s : %s\"",
"%",
"(",
"exception",
".",
"__class__",
".",
"__name__",
",",
"str",
"(",
"exception",
")",
")",
")",
... | set the exception message, stop transfer if running and set the done event | [
"set",
"the",
"exception",
"message",
"stop",
"transfer",
"if",
"running",
"and",
"set",
"the",
"done",
"event"
] | 24ba53137213e26e6b8fc2c3ec1e8198d507d22b | https://github.com/IBM/ibm-cos-sdk-python-s3transfer/blob/24ba53137213e26e6b8fc2c3ec1e8198d507d22b/ibm_s3transfer/aspera/futures.py#L541-L553 | train | 43,275 |
IBM/ibm-cos-sdk-python-s3transfer | ibm_s3transfer/aspera/futures.py | AsperaTransferCoordinator.is_success | def is_success(self):
''' check all sessions to see if they have completed successfully '''
for _session in self._sessions.values():
if not _session.is_success():
return False
return True | python | def is_success(self):
''' check all sessions to see if they have completed successfully '''
for _session in self._sessions.values():
if not _session.is_success():
return False
return True | [
"def",
"is_success",
"(",
"self",
")",
":",
"for",
"_session",
"in",
"self",
".",
"_sessions",
".",
"values",
"(",
")",
":",
"if",
"not",
"_session",
".",
"is_success",
"(",
")",
":",
"return",
"False",
"return",
"True"
] | check all sessions to see if they have completed successfully | [
"check",
"all",
"sessions",
"to",
"see",
"if",
"they",
"have",
"completed",
"successfully"
] | 24ba53137213e26e6b8fc2c3ec1e8198d507d22b | https://github.com/IBM/ibm-cos-sdk-python-s3transfer/blob/24ba53137213e26e6b8fc2c3ec1e8198d507d22b/ibm_s3transfer/aspera/futures.py#L555-L560 | train | 43,276 |
IBM/ibm-cos-sdk-python-s3transfer | ibm_s3transfer/aspera/futures.py | AsperaTransferCoordinator.set_transfer_spec | def set_transfer_spec(self):
''' run the function to set the transfer spec on error set associated exception '''
_ret = False
try:
self._args.transfer_spec_func(self._args)
_ret = True
except Exception as ex:
self.notify_exception(AsperaTransferSpecError(ex), False)
return _ret | python | def set_transfer_spec(self):
''' run the function to set the transfer spec on error set associated exception '''
_ret = False
try:
self._args.transfer_spec_func(self._args)
_ret = True
except Exception as ex:
self.notify_exception(AsperaTransferSpecError(ex), False)
return _ret | [
"def",
"set_transfer_spec",
"(",
"self",
")",
":",
"_ret",
"=",
"False",
"try",
":",
"self",
".",
"_args",
".",
"transfer_spec_func",
"(",
"self",
".",
"_args",
")",
"_ret",
"=",
"True",
"except",
"Exception",
"as",
"ex",
":",
"self",
".",
"notify_except... | run the function to set the transfer spec on error set associated exception | [
"run",
"the",
"function",
"to",
"set",
"the",
"transfer",
"spec",
"on",
"error",
"set",
"associated",
"exception"
] | 24ba53137213e26e6b8fc2c3ec1e8198d507d22b | https://github.com/IBM/ibm-cos-sdk-python-s3transfer/blob/24ba53137213e26e6b8fc2c3ec1e8198d507d22b/ibm_s3transfer/aspera/futures.py#L584-L592 | train | 43,277 |
IBM/ibm-cos-sdk-python-s3transfer | ibm_s3transfer/aspera/futures.py | AsperaTransferCoordinator.add_done_callback | def add_done_callback(self, function, **kwargs):
"""Add a done callback to be invoked when transfer is complete """
with self._callbacks_lock:
_function = functools.partial(function, **kwargs)
self._done_callbacks.append(_function) | python | def add_done_callback(self, function, **kwargs):
"""Add a done callback to be invoked when transfer is complete """
with self._callbacks_lock:
_function = functools.partial(function, **kwargs)
self._done_callbacks.append(_function) | [
"def",
"add_done_callback",
"(",
"self",
",",
"function",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"self",
".",
"_callbacks_lock",
":",
"_function",
"=",
"functools",
".",
"partial",
"(",
"function",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"_done_ca... | Add a done callback to be invoked when transfer is complete | [
"Add",
"a",
"done",
"callback",
"to",
"be",
"invoked",
"when",
"transfer",
"is",
"complete"
] | 24ba53137213e26e6b8fc2c3ec1e8198d507d22b | https://github.com/IBM/ibm-cos-sdk-python-s3transfer/blob/24ba53137213e26e6b8fc2c3ec1e8198d507d22b/ibm_s3transfer/aspera/futures.py#L617-L621 | train | 43,278 |
IBM/ibm-cos-sdk-python-s3transfer | ibm_s3transfer/aspera/futures.py | AsperaTransferCoordinator.add_subscribers | def add_subscribers(self, subscribers, **kwargs):
""" Add a callbacks to be invoked during transfer """
if subscribers:
with self._callbacks_lock:
self._add_subscribers_for_type(
'done', subscribers, self._done_callbacks, **kwargs)
self._add_subscribers_for_type(
'queued', subscribers, self._queued_callbacks, **kwargs)
self._add_subscribers_for_type(
'progress', subscribers, self._progress_callbacks, **kwargs) | python | def add_subscribers(self, subscribers, **kwargs):
""" Add a callbacks to be invoked during transfer """
if subscribers:
with self._callbacks_lock:
self._add_subscribers_for_type(
'done', subscribers, self._done_callbacks, **kwargs)
self._add_subscribers_for_type(
'queued', subscribers, self._queued_callbacks, **kwargs)
self._add_subscribers_for_type(
'progress', subscribers, self._progress_callbacks, **kwargs) | [
"def",
"add_subscribers",
"(",
"self",
",",
"subscribers",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"subscribers",
":",
"with",
"self",
".",
"_callbacks_lock",
":",
"self",
".",
"_add_subscribers_for_type",
"(",
"'done'",
",",
"subscribers",
",",
"self",
"."... | Add a callbacks to be invoked during transfer | [
"Add",
"a",
"callbacks",
"to",
"be",
"invoked",
"during",
"transfer"
] | 24ba53137213e26e6b8fc2c3ec1e8198d507d22b | https://github.com/IBM/ibm-cos-sdk-python-s3transfer/blob/24ba53137213e26e6b8fc2c3ec1e8198d507d22b/ibm_s3transfer/aspera/futures.py#L623-L632 | train | 43,279 |
IBM/ibm-cos-sdk-python-s3transfer | ibm_s3transfer/aspera/futures.py | AsperaTransferCoordinator._run_progress_callbacks | def _run_progress_callbacks(self, bytes_transferred):
''' pass the number of bytes process to progress callbacks '''
if bytes_transferred:
for callback in self._progress_callbacks:
try:
callback(bytes_transferred=bytes_transferred)
except Exception as ex:
logger.error("Exception: %s" % str(ex)) | python | def _run_progress_callbacks(self, bytes_transferred):
''' pass the number of bytes process to progress callbacks '''
if bytes_transferred:
for callback in self._progress_callbacks:
try:
callback(bytes_transferred=bytes_transferred)
except Exception as ex:
logger.error("Exception: %s" % str(ex)) | [
"def",
"_run_progress_callbacks",
"(",
"self",
",",
"bytes_transferred",
")",
":",
"if",
"bytes_transferred",
":",
"for",
"callback",
"in",
"self",
".",
"_progress_callbacks",
":",
"try",
":",
"callback",
"(",
"bytes_transferred",
"=",
"bytes_transferred",
")",
"e... | pass the number of bytes process to progress callbacks | [
"pass",
"the",
"number",
"of",
"bytes",
"process",
"to",
"progress",
"callbacks"
] | 24ba53137213e26e6b8fc2c3ec1e8198d507d22b | https://github.com/IBM/ibm-cos-sdk-python-s3transfer/blob/24ba53137213e26e6b8fc2c3ec1e8198d507d22b/ibm_s3transfer/aspera/futures.py#L642-L649 | train | 43,280 |
IBM/ibm-cos-sdk-python-s3transfer | ibm_s3transfer/aspera/futures.py | AsperaTransferCoordinator._run_done_callbacks | def _run_done_callbacks(self):
''' Run the callbacks and remove the callbacks from the internal
List so they do not get run again if done is notified more than once.
'''
with self._callbacks_lock:
for callback in self._done_callbacks:
try:
callback()
# We do not want a callback interrupting the process, especially
# in the failure cleanups. So log and catch, the excpetion.
except Exception as ex:
logger.error("Exception: %s" % str(ex))
logger.error("Exception raised in %s." % callback, exc_info=True)
self._done_callbacks = [] | python | def _run_done_callbacks(self):
''' Run the callbacks and remove the callbacks from the internal
List so they do not get run again if done is notified more than once.
'''
with self._callbacks_lock:
for callback in self._done_callbacks:
try:
callback()
# We do not want a callback interrupting the process, especially
# in the failure cleanups. So log and catch, the excpetion.
except Exception as ex:
logger.error("Exception: %s" % str(ex))
logger.error("Exception raised in %s." % callback, exc_info=True)
self._done_callbacks = [] | [
"def",
"_run_done_callbacks",
"(",
"self",
")",
":",
"with",
"self",
".",
"_callbacks_lock",
":",
"for",
"callback",
"in",
"self",
".",
"_done_callbacks",
":",
"try",
":",
"callback",
"(",
")",
"# We do not want a callback interrupting the process, especially",
"# in ... | Run the callbacks and remove the callbacks from the internal
List so they do not get run again if done is notified more than once. | [
"Run",
"the",
"callbacks",
"and",
"remove",
"the",
"callbacks",
"from",
"the",
"internal",
"List",
"so",
"they",
"do",
"not",
"get",
"run",
"again",
"if",
"done",
"is",
"notified",
"more",
"than",
"once",
"."
] | 24ba53137213e26e6b8fc2c3ec1e8198d507d22b | https://github.com/IBM/ibm-cos-sdk-python-s3transfer/blob/24ba53137213e26e6b8fc2c3ec1e8198d507d22b/ibm_s3transfer/aspera/futures.py#L651-L665 | train | 43,281 |
yfpeng/bioc | bioc/bioc.py | BioCAnnotation.total_span | def total_span(self) -> BioCLocation:
"""The total span of this annotation. Discontinued locations will be merged."""
if not self.locations:
raise ValueError('BioCAnnotation must have at least one location')
start = min(l.offset for l in self.locations)
end = max(l.end for l in self.locations)
return BioCLocation(start, end - start) | python | def total_span(self) -> BioCLocation:
"""The total span of this annotation. Discontinued locations will be merged."""
if not self.locations:
raise ValueError('BioCAnnotation must have at least one location')
start = min(l.offset for l in self.locations)
end = max(l.end for l in self.locations)
return BioCLocation(start, end - start) | [
"def",
"total_span",
"(",
"self",
")",
"->",
"BioCLocation",
":",
"if",
"not",
"self",
".",
"locations",
":",
"raise",
"ValueError",
"(",
"'BioCAnnotation must have at least one location'",
")",
"start",
"=",
"min",
"(",
"l",
".",
"offset",
"for",
"l",
"in",
... | The total span of this annotation. Discontinued locations will be merged. | [
"The",
"total",
"span",
"of",
"this",
"annotation",
".",
"Discontinued",
"locations",
"will",
"be",
"merged",
"."
] | 47ddaa010960d9ba673aefe068e7bbaf39f0fff4 | https://github.com/yfpeng/bioc/blob/47ddaa010960d9ba673aefe068e7bbaf39f0fff4/bioc/bioc.py#L128-L134 | train | 43,282 |
yfpeng/bioc | bioc/bioc.py | BioCRelation.get_node | def get_node(self, role: str, default=None) -> BioCNode:
"""
Get the first node with role
Args:
role: role
default: node returned instead of raising StopIteration
Returns:
the first node with role
"""
return next((node for node in self.nodes if node.role == role), default) | python | def get_node(self, role: str, default=None) -> BioCNode:
"""
Get the first node with role
Args:
role: role
default: node returned instead of raising StopIteration
Returns:
the first node with role
"""
return next((node for node in self.nodes if node.role == role), default) | [
"def",
"get_node",
"(",
"self",
",",
"role",
":",
"str",
",",
"default",
"=",
"None",
")",
"->",
"BioCNode",
":",
"return",
"next",
"(",
"(",
"node",
"for",
"node",
"in",
"self",
".",
"nodes",
"if",
"node",
".",
"role",
"==",
"role",
")",
",",
"d... | Get the first node with role
Args:
role: role
default: node returned instead of raising StopIteration
Returns:
the first node with role | [
"Get",
"the",
"first",
"node",
"with",
"role"
] | 47ddaa010960d9ba673aefe068e7bbaf39f0fff4 | https://github.com/yfpeng/bioc/blob/47ddaa010960d9ba673aefe068e7bbaf39f0fff4/bioc/bioc.py#L174-L185 | train | 43,283 |
yfpeng/bioc | bioc/bioc.py | BioCPassage.get_sentence | def get_sentence(self, offset: int) -> BioCSentence or None:
"""
Gets sentence with specified offset
Args:
offset: sentence offset
Return:
the sentence with specified offset
"""
for sentence in self.sentences:
if sentence.offset == offset:
return sentence
return None | python | def get_sentence(self, offset: int) -> BioCSentence or None:
"""
Gets sentence with specified offset
Args:
offset: sentence offset
Return:
the sentence with specified offset
"""
for sentence in self.sentences:
if sentence.offset == offset:
return sentence
return None | [
"def",
"get_sentence",
"(",
"self",
",",
"offset",
":",
"int",
")",
"->",
"BioCSentence",
"or",
"None",
":",
"for",
"sentence",
"in",
"self",
".",
"sentences",
":",
"if",
"sentence",
".",
"offset",
"==",
"offset",
":",
"return",
"sentence",
"return",
"No... | Gets sentence with specified offset
Args:
offset: sentence offset
Return:
the sentence with specified offset | [
"Gets",
"sentence",
"with",
"specified",
"offset"
] | 47ddaa010960d9ba673aefe068e7bbaf39f0fff4 | https://github.com/yfpeng/bioc/blob/47ddaa010960d9ba673aefe068e7bbaf39f0fff4/bioc/bioc.py#L294-L307 | train | 43,284 |
yfpeng/bioc | bioc/bioc.py | BioCDocument.of | def of(cls, *passages: BioCPassage):
"""
Returns a collection passages
"""
if len(passages) <= 0:
raise ValueError("There has to be at least one passage.")
c = BioCDocument()
for passage in passages:
if passage is None:
raise ValueError('Passage is None')
c.add_passage(passage)
return c | python | def of(cls, *passages: BioCPassage):
"""
Returns a collection passages
"""
if len(passages) <= 0:
raise ValueError("There has to be at least one passage.")
c = BioCDocument()
for passage in passages:
if passage is None:
raise ValueError('Passage is None')
c.add_passage(passage)
return c | [
"def",
"of",
"(",
"cls",
",",
"*",
"passages",
":",
"BioCPassage",
")",
":",
"if",
"len",
"(",
"passages",
")",
"<=",
"0",
":",
"raise",
"ValueError",
"(",
"\"There has to be at least one passage.\"",
")",
"c",
"=",
"BioCDocument",
"(",
")",
"for",
"passag... | Returns a collection passages | [
"Returns",
"a",
"collection",
"passages"
] | 47ddaa010960d9ba673aefe068e7bbaf39f0fff4 | https://github.com/yfpeng/bioc/blob/47ddaa010960d9ba673aefe068e7bbaf39f0fff4/bioc/bioc.py#L361-L372 | train | 43,285 |
yfpeng/bioc | bioc/bioc.py | BioCCollection.of | def of(cls, *documents: BioCDocument):
"""
Returns a collection documents
"""
if len(documents) <= 0:
raise ValueError("There has to be at least one document.")
c = BioCCollection()
for document in documents:
if document is None:
raise ValueError('Document is None')
c.add_document(document)
return c | python | def of(cls, *documents: BioCDocument):
"""
Returns a collection documents
"""
if len(documents) <= 0:
raise ValueError("There has to be at least one document.")
c = BioCCollection()
for document in documents:
if document is None:
raise ValueError('Document is None')
c.add_document(document)
return c | [
"def",
"of",
"(",
"cls",
",",
"*",
"documents",
":",
"BioCDocument",
")",
":",
"if",
"len",
"(",
"documents",
")",
"<=",
"0",
":",
"raise",
"ValueError",
"(",
"\"There has to be at least one document.\"",
")",
"c",
"=",
"BioCCollection",
"(",
")",
"for",
"... | Returns a collection documents | [
"Returns",
"a",
"collection",
"documents"
] | 47ddaa010960d9ba673aefe068e7bbaf39f0fff4 | https://github.com/yfpeng/bioc/blob/47ddaa010960d9ba673aefe068e7bbaf39f0fff4/bioc/bioc.py#L420-L431 | train | 43,286 |
SuperCowPowers/workbench | workbench/clients/pe_sim_graph.py | add_it | def add_it(workbench, file_list, labels):
"""Add the given file_list to workbench as samples, also add them as nodes.
Args:
workbench: Instance of Workbench Client.
file_list: list of files.
labels: labels for the nodes.
Returns:
A list of md5s.
"""
md5s = []
for filename in file_list:
if filename != '.DS_Store':
with open(filename, 'rb') as pe_file:
base_name = os.path.basename(filename)
md5 = workbench.store_sample(pe_file.read(), base_name, 'exe')
workbench.add_node(md5, md5[:6], labels)
md5s.append(md5)
return md5s | python | def add_it(workbench, file_list, labels):
"""Add the given file_list to workbench as samples, also add them as nodes.
Args:
workbench: Instance of Workbench Client.
file_list: list of files.
labels: labels for the nodes.
Returns:
A list of md5s.
"""
md5s = []
for filename in file_list:
if filename != '.DS_Store':
with open(filename, 'rb') as pe_file:
base_name = os.path.basename(filename)
md5 = workbench.store_sample(pe_file.read(), base_name, 'exe')
workbench.add_node(md5, md5[:6], labels)
md5s.append(md5)
return md5s | [
"def",
"add_it",
"(",
"workbench",
",",
"file_list",
",",
"labels",
")",
":",
"md5s",
"=",
"[",
"]",
"for",
"filename",
"in",
"file_list",
":",
"if",
"filename",
"!=",
"'.DS_Store'",
":",
"with",
"open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"pe_fil... | Add the given file_list to workbench as samples, also add them as nodes.
Args:
workbench: Instance of Workbench Client.
file_list: list of files.
labels: labels for the nodes.
Returns:
A list of md5s. | [
"Add",
"the",
"given",
"file_list",
"to",
"workbench",
"as",
"samples",
"also",
"add",
"them",
"as",
"nodes",
"."
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/clients/pe_sim_graph.py#L7-L27 | train | 43,287 |
SuperCowPowers/workbench | workbench/clients/pe_sim_graph.py | jaccard_sims | def jaccard_sims(feature_list):
"""Compute Jaccard similarities between all the observations in the feature list.
Args:
feature_list: a list of dictionaries, each having structure as
{ 'md5' : String, 'features': list of Strings }
Returns:
list of dictionaries with structure as
{'source': md5 String, 'target': md5 String, 'sim': Jaccard similarity Number}
"""
sim_info_list = []
for feature_info in feature_list:
md5_source = feature_info['md5']
features_source = feature_info['features']
for feature_info in feature_list:
md5_target = feature_info['md5']
features_target = feature_info['features']
if md5_source == md5_target:
continue
sim = jaccard_sim(features_source, features_target)
if sim > .5:
sim_info_list.append({'source': md5_source, 'target': md5_target, 'sim': sim})
return sim_info_list | python | def jaccard_sims(feature_list):
"""Compute Jaccard similarities between all the observations in the feature list.
Args:
feature_list: a list of dictionaries, each having structure as
{ 'md5' : String, 'features': list of Strings }
Returns:
list of dictionaries with structure as
{'source': md5 String, 'target': md5 String, 'sim': Jaccard similarity Number}
"""
sim_info_list = []
for feature_info in feature_list:
md5_source = feature_info['md5']
features_source = feature_info['features']
for feature_info in feature_list:
md5_target = feature_info['md5']
features_target = feature_info['features']
if md5_source == md5_target:
continue
sim = jaccard_sim(features_source, features_target)
if sim > .5:
sim_info_list.append({'source': md5_source, 'target': md5_target, 'sim': sim})
return sim_info_list | [
"def",
"jaccard_sims",
"(",
"feature_list",
")",
":",
"sim_info_list",
"=",
"[",
"]",
"for",
"feature_info",
"in",
"feature_list",
":",
"md5_source",
"=",
"feature_info",
"[",
"'md5'",
"]",
"features_source",
"=",
"feature_info",
"[",
"'features'",
"]",
"for",
... | Compute Jaccard similarities between all the observations in the feature list.
Args:
feature_list: a list of dictionaries, each having structure as
{ 'md5' : String, 'features': list of Strings }
Returns:
list of dictionaries with structure as
{'source': md5 String, 'target': md5 String, 'sim': Jaccard similarity Number} | [
"Compute",
"Jaccard",
"similarities",
"between",
"all",
"the",
"observations",
"in",
"the",
"feature",
"list",
"."
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/clients/pe_sim_graph.py#L30-L55 | train | 43,288 |
SuperCowPowers/workbench | workbench/clients/pe_sim_graph.py | jaccard_sim | def jaccard_sim(features1, features2):
"""Compute similarity between two sets using Jaccard similarity.
Args:
features1: list of PE Symbols.
features2: list of PE Symbols.
Returns:
Returns an int.
"""
set1 = set(features1)
set2 = set(features2)
try:
return len(set1.intersection(set2))/float(max(len(set1), len(set2)))
except ZeroDivisionError:
return 0 | python | def jaccard_sim(features1, features2):
"""Compute similarity between two sets using Jaccard similarity.
Args:
features1: list of PE Symbols.
features2: list of PE Symbols.
Returns:
Returns an int.
"""
set1 = set(features1)
set2 = set(features2)
try:
return len(set1.intersection(set2))/float(max(len(set1), len(set2)))
except ZeroDivisionError:
return 0 | [
"def",
"jaccard_sim",
"(",
"features1",
",",
"features2",
")",
":",
"set1",
"=",
"set",
"(",
"features1",
")",
"set2",
"=",
"set",
"(",
"features2",
")",
"try",
":",
"return",
"len",
"(",
"set1",
".",
"intersection",
"(",
"set2",
")",
")",
"/",
"floa... | Compute similarity between two sets using Jaccard similarity.
Args:
features1: list of PE Symbols.
features2: list of PE Symbols.
Returns:
Returns an int. | [
"Compute",
"similarity",
"between",
"two",
"sets",
"using",
"Jaccard",
"similarity",
"."
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/clients/pe_sim_graph.py#L58-L73 | train | 43,289 |
SuperCowPowers/workbench | workbench/clients/pe_sim_graph.py | run | def run():
"""This client generates a similarity graph from features in PE Files."""
# Grab server args
args = client_helper.grab_server_args()
# Start up workbench connection
workbench = zerorpc.Client(timeout=300, heartbeat=60)
workbench.connect('tcp://'+args['server']+':'+args['port'])
# Test out PEFile -> pe_deep_sim -> pe_jaccard_sim -> graph
data_path = os.path.join(os.path.dirname(os.path.realpath(__file__)),'../data/pe/bad')
bad_files = [os.path.join(data_path, child) for child in os.listdir(data_path)][:5]
data_path = os.path.join(os.path.dirname(os.path.realpath(__file__)),'../data/pe/good')
good_files = [os.path.join(data_path, child) for child in os.listdir(data_path)][:5]
# Clear any graph in the Neo4j database
workbench.clear_graph_db()
# First throw them into workbench and add them as nodes into the graph
all_md5s = add_it(workbench, bad_files, ['exe', 'bad']) + add_it(workbench, good_files, ['exe', 'good'])
# Make a sample set
sample_set = workbench.store_sample_set(all_md5s)
# Compute pe_features on all files of type pe, just pull back the sparse features
import_gen = workbench.set_work_request('pe_features', sample_set, ['md5', 'sparse_features.imported_symbols'])
imports = [{'md5': r['md5'], 'features': r['imported_symbols']} for r in import_gen]
# Compute pe_features on all files of type pe, just pull back the sparse features
warning_gen = workbench.set_work_request('pe_features', sample_set, ['md5', 'sparse_features.pe_warning_strings'])
warnings = [{'md5': r['md5'], 'features': r['pe_warning_strings']} for r in warning_gen]
# Compute strings on all files of type pe, just pull back the string_list
string_gen = workbench.set_work_request('strings', sample_set, ['md5', 'string_list'])
strings = [{'md5': r['md5'], 'features': r['string_list']} for r in string_gen]
# Compute pe_peid on all files of type pe, just pull back the match_list
# Fixme: commenting this out until we figure out why peid is SO slow
'''
peid_gen = workbench.set_work_request('pe_peid', sample_set, ['md5', 'match_list']})
peids = [{'md5': r['md5'], 'features': r['match_list']} for r in peid_gen]
'''
# Compute the Jaccard Index between imported systems and store as relationships
sims = jaccard_sims(imports)
for sim_info in sims:
workbench.add_rel(sim_info['source'], sim_info['target'], 'imports')
# Compute the Jaccard Index between warnings and store as relationships
sims = jaccard_sims(warnings)
for sim_info in sims:
workbench.add_rel(sim_info['source'], sim_info['target'], 'warnings')
# Compute the Jaccard Index between strings and store as relationships
sims = jaccard_sims(strings)
for sim_info in sims:
workbench.add_rel(sim_info['source'], sim_info['target'], 'strings')
# Compute the Jaccard Index between peids and store as relationships
# Fixme: commenting this out until we figure out why peid is SO slow
'''
sims = jaccard_sims(peids)
for sim_info in sims:
workbench.add_rel(sim_info['source'], sim_info['target'], 'peids')
'''
# Compute pe_deep_sim on all files of type pe
results = workbench.set_work_request('pe_deep_sim', sample_set)
# Store the ssdeep sims as relationships
for result in list(results):
for sim_info in result['sim_list']:
workbench.add_rel(result['md5'], sim_info['md5'], 'ssdeep')
# Let them know where they can get there graph
print 'All done: go to http://localhost:7474/browser and execute this query: "%s"' % \
('match (n)-[r]-() return n,r') | python | def run():
"""This client generates a similarity graph from features in PE Files."""
# Grab server args
args = client_helper.grab_server_args()
# Start up workbench connection
workbench = zerorpc.Client(timeout=300, heartbeat=60)
workbench.connect('tcp://'+args['server']+':'+args['port'])
# Test out PEFile -> pe_deep_sim -> pe_jaccard_sim -> graph
data_path = os.path.join(os.path.dirname(os.path.realpath(__file__)),'../data/pe/bad')
bad_files = [os.path.join(data_path, child) for child in os.listdir(data_path)][:5]
data_path = os.path.join(os.path.dirname(os.path.realpath(__file__)),'../data/pe/good')
good_files = [os.path.join(data_path, child) for child in os.listdir(data_path)][:5]
# Clear any graph in the Neo4j database
workbench.clear_graph_db()
# First throw them into workbench and add them as nodes into the graph
all_md5s = add_it(workbench, bad_files, ['exe', 'bad']) + add_it(workbench, good_files, ['exe', 'good'])
# Make a sample set
sample_set = workbench.store_sample_set(all_md5s)
# Compute pe_features on all files of type pe, just pull back the sparse features
import_gen = workbench.set_work_request('pe_features', sample_set, ['md5', 'sparse_features.imported_symbols'])
imports = [{'md5': r['md5'], 'features': r['imported_symbols']} for r in import_gen]
# Compute pe_features on all files of type pe, just pull back the sparse features
warning_gen = workbench.set_work_request('pe_features', sample_set, ['md5', 'sparse_features.pe_warning_strings'])
warnings = [{'md5': r['md5'], 'features': r['pe_warning_strings']} for r in warning_gen]
# Compute strings on all files of type pe, just pull back the string_list
string_gen = workbench.set_work_request('strings', sample_set, ['md5', 'string_list'])
strings = [{'md5': r['md5'], 'features': r['string_list']} for r in string_gen]
# Compute pe_peid on all files of type pe, just pull back the match_list
# Fixme: commenting this out until we figure out why peid is SO slow
'''
peid_gen = workbench.set_work_request('pe_peid', sample_set, ['md5', 'match_list']})
peids = [{'md5': r['md5'], 'features': r['match_list']} for r in peid_gen]
'''
# Compute the Jaccard Index between imported systems and store as relationships
sims = jaccard_sims(imports)
for sim_info in sims:
workbench.add_rel(sim_info['source'], sim_info['target'], 'imports')
# Compute the Jaccard Index between warnings and store as relationships
sims = jaccard_sims(warnings)
for sim_info in sims:
workbench.add_rel(sim_info['source'], sim_info['target'], 'warnings')
# Compute the Jaccard Index between strings and store as relationships
sims = jaccard_sims(strings)
for sim_info in sims:
workbench.add_rel(sim_info['source'], sim_info['target'], 'strings')
# Compute the Jaccard Index between peids and store as relationships
# Fixme: commenting this out until we figure out why peid is SO slow
'''
sims = jaccard_sims(peids)
for sim_info in sims:
workbench.add_rel(sim_info['source'], sim_info['target'], 'peids')
'''
# Compute pe_deep_sim on all files of type pe
results = workbench.set_work_request('pe_deep_sim', sample_set)
# Store the ssdeep sims as relationships
for result in list(results):
for sim_info in result['sim_list']:
workbench.add_rel(result['md5'], sim_info['md5'], 'ssdeep')
# Let them know where they can get there graph
print 'All done: go to http://localhost:7474/browser and execute this query: "%s"' % \
('match (n)-[r]-() return n,r') | [
"def",
"run",
"(",
")",
":",
"# Grab server args",
"args",
"=",
"client_helper",
".",
"grab_server_args",
"(",
")",
"# Start up workbench connection",
"workbench",
"=",
"zerorpc",
".",
"Client",
"(",
"timeout",
"=",
"300",
",",
"heartbeat",
"=",
"60",
")",
"wo... | This client generates a similarity graph from features in PE Files. | [
"This",
"client",
"generates",
"a",
"similarity",
"graph",
"from",
"features",
"in",
"PE",
"Files",
"."
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/clients/pe_sim_graph.py#L76-L153 | train | 43,290 |
yfpeng/bioc | bioc/utils.py | pad_char | def pad_char(text: str, width: int, char: str = '\n') -> str:
"""Pads a text until length width."""
dis = width - len(text)
if dis < 0:
raise ValueError
if dis > 0:
text += char * dis
return text | python | def pad_char(text: str, width: int, char: str = '\n') -> str:
"""Pads a text until length width."""
dis = width - len(text)
if dis < 0:
raise ValueError
if dis > 0:
text += char * dis
return text | [
"def",
"pad_char",
"(",
"text",
":",
"str",
",",
"width",
":",
"int",
",",
"char",
":",
"str",
"=",
"'\\n'",
")",
"->",
"str",
":",
"dis",
"=",
"width",
"-",
"len",
"(",
"text",
")",
"if",
"dis",
"<",
"0",
":",
"raise",
"ValueError",
"if",
"dis... | Pads a text until length width. | [
"Pads",
"a",
"text",
"until",
"length",
"width",
"."
] | 47ddaa010960d9ba673aefe068e7bbaf39f0fff4 | https://github.com/yfpeng/bioc/blob/47ddaa010960d9ba673aefe068e7bbaf39f0fff4/bioc/utils.py#L11-L18 | train | 43,291 |
yfpeng/bioc | bioc/utils.py | pretty_print | def pretty_print(source, dest):
"""
Pretty print the XML file
"""
parser = etree.XMLParser(remove_blank_text=True)
if not isinstance(source, str):
source = str(source)
tree = etree.parse(source, parser)
docinfo = tree.docinfo
with open(dest, 'wb') as fp:
fp.write(etree.tostring(tree, pretty_print=True,
encoding=docinfo.encoding, standalone=docinfo.standalone)) | python | def pretty_print(source, dest):
"""
Pretty print the XML file
"""
parser = etree.XMLParser(remove_blank_text=True)
if not isinstance(source, str):
source = str(source)
tree = etree.parse(source, parser)
docinfo = tree.docinfo
with open(dest, 'wb') as fp:
fp.write(etree.tostring(tree, pretty_print=True,
encoding=docinfo.encoding, standalone=docinfo.standalone)) | [
"def",
"pretty_print",
"(",
"source",
",",
"dest",
")",
":",
"parser",
"=",
"etree",
".",
"XMLParser",
"(",
"remove_blank_text",
"=",
"True",
")",
"if",
"not",
"isinstance",
"(",
"source",
",",
"str",
")",
":",
"source",
"=",
"str",
"(",
"source",
")",... | Pretty print the XML file | [
"Pretty",
"print",
"the",
"XML",
"file"
] | 47ddaa010960d9ba673aefe068e7bbaf39f0fff4 | https://github.com/yfpeng/bioc/blob/47ddaa010960d9ba673aefe068e7bbaf39f0fff4/bioc/utils.py#L60-L71 | train | 43,292 |
yfpeng/bioc | bioc/utils.py | shorten_text | def shorten_text(text: str):
"""Return a short repr of text if it is longer than 40"""
if len(text) <= 40:
text = text
else:
text = text[:17] + ' ... ' + text[-17:]
return repr(text) | python | def shorten_text(text: str):
"""Return a short repr of text if it is longer than 40"""
if len(text) <= 40:
text = text
else:
text = text[:17] + ' ... ' + text[-17:]
return repr(text) | [
"def",
"shorten_text",
"(",
"text",
":",
"str",
")",
":",
"if",
"len",
"(",
"text",
")",
"<=",
"40",
":",
"text",
"=",
"text",
"else",
":",
"text",
"=",
"text",
"[",
":",
"17",
"]",
"+",
"' ... '",
"+",
"text",
"[",
"-",
"17",
":",
"]",
"retu... | Return a short repr of text if it is longer than 40 | [
"Return",
"a",
"short",
"repr",
"of",
"text",
"if",
"it",
"is",
"longer",
"than",
"40"
] | 47ddaa010960d9ba673aefe068e7bbaf39f0fff4 | https://github.com/yfpeng/bioc/blob/47ddaa010960d9ba673aefe068e7bbaf39f0fff4/bioc/utils.py#L74-L80 | train | 43,293 |
SuperCowPowers/workbench | workbench/workers/meta.py | MetaData.execute | def execute(self, input_data):
''' This worker computes meta data for any file type. '''
raw_bytes = input_data['sample']['raw_bytes']
self.meta['md5'] = hashlib.md5(raw_bytes).hexdigest()
self.meta['tags'] = input_data['tags']['tags']
self.meta['type_tag'] = input_data['sample']['type_tag']
with magic.Magic() as mag:
self.meta['file_type'] = mag.id_buffer(raw_bytes[:1024])
with magic.Magic(flags=magic.MAGIC_MIME_TYPE) as mag:
self.meta['mime_type'] = mag.id_buffer(raw_bytes[:1024])
with magic.Magic(flags=magic.MAGIC_MIME_ENCODING) as mag:
try:
self.meta['encoding'] = mag.id_buffer(raw_bytes[:1024])
except magic.MagicError:
self.meta['encoding'] = 'unknown'
self.meta['file_size'] = len(raw_bytes)
self.meta['filename'] = input_data['sample']['filename']
self.meta['import_time'] = input_data['sample']['import_time']
self.meta['customer'] = input_data['sample']['customer']
self.meta['length'] = input_data['sample']['length']
return self.meta | python | def execute(self, input_data):
''' This worker computes meta data for any file type. '''
raw_bytes = input_data['sample']['raw_bytes']
self.meta['md5'] = hashlib.md5(raw_bytes).hexdigest()
self.meta['tags'] = input_data['tags']['tags']
self.meta['type_tag'] = input_data['sample']['type_tag']
with magic.Magic() as mag:
self.meta['file_type'] = mag.id_buffer(raw_bytes[:1024])
with magic.Magic(flags=magic.MAGIC_MIME_TYPE) as mag:
self.meta['mime_type'] = mag.id_buffer(raw_bytes[:1024])
with magic.Magic(flags=magic.MAGIC_MIME_ENCODING) as mag:
try:
self.meta['encoding'] = mag.id_buffer(raw_bytes[:1024])
except magic.MagicError:
self.meta['encoding'] = 'unknown'
self.meta['file_size'] = len(raw_bytes)
self.meta['filename'] = input_data['sample']['filename']
self.meta['import_time'] = input_data['sample']['import_time']
self.meta['customer'] = input_data['sample']['customer']
self.meta['length'] = input_data['sample']['length']
return self.meta | [
"def",
"execute",
"(",
"self",
",",
"input_data",
")",
":",
"raw_bytes",
"=",
"input_data",
"[",
"'sample'",
"]",
"[",
"'raw_bytes'",
"]",
"self",
".",
"meta",
"[",
"'md5'",
"]",
"=",
"hashlib",
".",
"md5",
"(",
"raw_bytes",
")",
".",
"hexdigest",
"(",... | This worker computes meta data for any file type. | [
"This",
"worker",
"computes",
"meta",
"data",
"for",
"any",
"file",
"type",
"."
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/workers/meta.py#L15-L36 | train | 43,294 |
SuperCowPowers/workbench | workbench/workers/strings.py | Strings.execute | def execute(self, input_data):
''' Execute the Strings worker '''
raw_bytes = input_data['sample']['raw_bytes']
strings = self.find_strings.findall(raw_bytes)
return {'string_list': strings} | python | def execute(self, input_data):
''' Execute the Strings worker '''
raw_bytes = input_data['sample']['raw_bytes']
strings = self.find_strings.findall(raw_bytes)
return {'string_list': strings} | [
"def",
"execute",
"(",
"self",
",",
"input_data",
")",
":",
"raw_bytes",
"=",
"input_data",
"[",
"'sample'",
"]",
"[",
"'raw_bytes'",
"]",
"strings",
"=",
"self",
".",
"find_strings",
".",
"findall",
"(",
"raw_bytes",
")",
"return",
"{",
"'string_list'",
"... | Execute the Strings worker | [
"Execute",
"the",
"Strings",
"worker"
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/workers/strings.py#L14-L18 | train | 43,295 |
SuperCowPowers/workbench | workbench/workers/pe_indicators.py | PEIndicators.execute | def execute(self, input_data):
''' Execute the PEIndicators worker '''
raw_bytes = input_data['sample']['raw_bytes']
# Analyze the output of pefile for any anomalous conditions.
# Have the PE File module process the file
try:
self.pefile_handle = pefile.PE(data=raw_bytes, fast_load=False)
except (AttributeError, pefile.PEFormatError), error:
return {'error': str(error), 'indicator_list': [{'Error': 'PE module failed!'}]}
indicators = []
indicators += [{'description': warn, 'severity': 2, 'category': 'PE_WARN'}
for warn in self.pefile_handle.get_warnings()]
# Automatically invoke any method of this class that starts with 'check'
check_methods = self._get_check_methods()
for check_method in check_methods:
hit_data = check_method()
if hit_data:
indicators.append(hit_data)
return {'indicator_list': indicators} | python | def execute(self, input_data):
''' Execute the PEIndicators worker '''
raw_bytes = input_data['sample']['raw_bytes']
# Analyze the output of pefile for any anomalous conditions.
# Have the PE File module process the file
try:
self.pefile_handle = pefile.PE(data=raw_bytes, fast_load=False)
except (AttributeError, pefile.PEFormatError), error:
return {'error': str(error), 'indicator_list': [{'Error': 'PE module failed!'}]}
indicators = []
indicators += [{'description': warn, 'severity': 2, 'category': 'PE_WARN'}
for warn in self.pefile_handle.get_warnings()]
# Automatically invoke any method of this class that starts with 'check'
check_methods = self._get_check_methods()
for check_method in check_methods:
hit_data = check_method()
if hit_data:
indicators.append(hit_data)
return {'indicator_list': indicators} | [
"def",
"execute",
"(",
"self",
",",
"input_data",
")",
":",
"raw_bytes",
"=",
"input_data",
"[",
"'sample'",
"]",
"[",
"'raw_bytes'",
"]",
"# Analyze the output of pefile for any anomalous conditions.",
"# Have the PE File module process the file",
"try",
":",
"self",
"."... | Execute the PEIndicators worker | [
"Execute",
"the",
"PEIndicators",
"worker"
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/workers/pe_indicators.py#L45-L67 | train | 43,296 |
SuperCowPowers/workbench | workbench/workers/pe_indicators.py | PEIndicators.check_checksum_mismatch | def check_checksum_mismatch(self):
''' Checking for a checksum that doesn't match the generated checksum '''
if self.pefile_handle.OPTIONAL_HEADER:
if self.pefile_handle.OPTIONAL_HEADER.CheckSum != self.pefile_handle.generate_checksum():
return {'description': 'Reported Checksum does not match actual checksum',
'severity': 2, 'category': 'MALFORMED'}
return None | python | def check_checksum_mismatch(self):
''' Checking for a checksum that doesn't match the generated checksum '''
if self.pefile_handle.OPTIONAL_HEADER:
if self.pefile_handle.OPTIONAL_HEADER.CheckSum != self.pefile_handle.generate_checksum():
return {'description': 'Reported Checksum does not match actual checksum',
'severity': 2, 'category': 'MALFORMED'}
return None | [
"def",
"check_checksum_mismatch",
"(",
"self",
")",
":",
"if",
"self",
".",
"pefile_handle",
".",
"OPTIONAL_HEADER",
":",
"if",
"self",
".",
"pefile_handle",
".",
"OPTIONAL_HEADER",
".",
"CheckSum",
"!=",
"self",
".",
"pefile_handle",
".",
"generate_checksum",
"... | Checking for a checksum that doesn't match the generated checksum | [
"Checking",
"for",
"a",
"checksum",
"that",
"doesn",
"t",
"match",
"the",
"generated",
"checksum"
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/workers/pe_indicators.py#L94-L100 | train | 43,297 |
SuperCowPowers/workbench | workbench/workers/pe_indicators.py | PEIndicators.check_nonstandard_section_name | def check_nonstandard_section_name(self):
''' Checking for an non-standard section name '''
std_sections = ['.text', '.bss', '.rdata', '.data', '.rsrc', '.edata', '.idata',
'.pdata', '.debug', '.reloc', '.stab', '.stabstr', '.tls',
'.crt', '.gnu_deb', '.eh_fram', '.exptbl', '.rodata']
for i in range(200):
std_sections.append('/'+str(i))
non_std_sections = []
for section in self.pefile_handle.sections:
name = convert_to_ascii_null_term(section.Name).lower()
if (name not in std_sections):
non_std_sections.append(name)
if non_std_sections:
return{'description': 'Section(s) with a non-standard name, tamper indication',
'severity': 3, 'category': 'MALFORMED', 'attributes': non_std_sections}
return None | python | def check_nonstandard_section_name(self):
''' Checking for an non-standard section name '''
std_sections = ['.text', '.bss', '.rdata', '.data', '.rsrc', '.edata', '.idata',
'.pdata', '.debug', '.reloc', '.stab', '.stabstr', '.tls',
'.crt', '.gnu_deb', '.eh_fram', '.exptbl', '.rodata']
for i in range(200):
std_sections.append('/'+str(i))
non_std_sections = []
for section in self.pefile_handle.sections:
name = convert_to_ascii_null_term(section.Name).lower()
if (name not in std_sections):
non_std_sections.append(name)
if non_std_sections:
return{'description': 'Section(s) with a non-standard name, tamper indication',
'severity': 3, 'category': 'MALFORMED', 'attributes': non_std_sections}
return None | [
"def",
"check_nonstandard_section_name",
"(",
"self",
")",
":",
"std_sections",
"=",
"[",
"'.text'",
",",
"'.bss'",
",",
"'.rdata'",
",",
"'.data'",
",",
"'.rsrc'",
",",
"'.edata'",
",",
"'.idata'",
",",
"'.pdata'",
",",
"'.debug'",
",",
"'.reloc'",
",",
"'.... | Checking for an non-standard section name | [
"Checking",
"for",
"an",
"non",
"-",
"standard",
"section",
"name"
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/workers/pe_indicators.py#L110-L126 | train | 43,298 |
SuperCowPowers/workbench | workbench/workers/pe_indicators.py | PEIndicators.check_image_size_incorrect | def check_image_size_incorrect(self):
''' Checking if the reported image size matches the actual image size '''
last_virtual_address = 0
last_virtual_size = 0
section_alignment = self.pefile_handle.OPTIONAL_HEADER.SectionAlignment
total_image_size = self.pefile_handle.OPTIONAL_HEADER.SizeOfImage
for section in self.pefile_handle.sections:
if section.VirtualAddress > last_virtual_address:
last_virtual_address = section.VirtualAddress
last_virtual_size = section.Misc_VirtualSize
# Just pad the size to be equal to the alignment and check for mismatch
last_virtual_size += section_alignment - (last_virtual_size % section_alignment)
if (last_virtual_address + last_virtual_size) != total_image_size:
return {'description': 'Image size does not match reported size',
'severity': 3, 'category': 'MALFORMED'}
return None | python | def check_image_size_incorrect(self):
''' Checking if the reported image size matches the actual image size '''
last_virtual_address = 0
last_virtual_size = 0
section_alignment = self.pefile_handle.OPTIONAL_HEADER.SectionAlignment
total_image_size = self.pefile_handle.OPTIONAL_HEADER.SizeOfImage
for section in self.pefile_handle.sections:
if section.VirtualAddress > last_virtual_address:
last_virtual_address = section.VirtualAddress
last_virtual_size = section.Misc_VirtualSize
# Just pad the size to be equal to the alignment and check for mismatch
last_virtual_size += section_alignment - (last_virtual_size % section_alignment)
if (last_virtual_address + last_virtual_size) != total_image_size:
return {'description': 'Image size does not match reported size',
'severity': 3, 'category': 'MALFORMED'}
return None | [
"def",
"check_image_size_incorrect",
"(",
"self",
")",
":",
"last_virtual_address",
"=",
"0",
"last_virtual_size",
"=",
"0",
"section_alignment",
"=",
"self",
".",
"pefile_handle",
".",
"OPTIONAL_HEADER",
".",
"SectionAlignment",
"total_image_size",
"=",
"self",
".",
... | Checking if the reported image size matches the actual image size | [
"Checking",
"if",
"the",
"reported",
"image",
"size",
"matches",
"the",
"actual",
"image",
"size"
] | 710232756dd717f734253315e3d0b33c9628dafb | https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/workers/pe_indicators.py#L128-L147 | train | 43,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.