output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
run the queed callback for just the first session only
How would you explain what the following Python 3 function does 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_c...
As a Python code composer, you craft elegant and concise scripts.
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() ...
Create a Python 3 function to notify all the active session that all other users have done
You are a Python code analyst, evaluating scripts for potential improvements.
only call the progress callback if total has changed or PROGRESS_MSGS_SEND_ALL is set
Explain what the following Python 3 code does 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 Aspe...
As a Python code analyst, you investigate and solve complex coding mysteries
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): # ...
Can you implement a function in Python 3 that sets the exception message stop transfer if running and set the done event
You are a Python code analyst, evaluating scripts for potential improvements.
check all sessions to see if they have completed successfully
Here you have a function in Python 3, explain what it does 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
You are a Python code architect, reviewing and designing scalable and efficient code
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(AsperaTransferSpecErr...
Can you implement a function in Python 3 that runs the function to set the transfer spec on error set associated exception
As a Python code analyst, you investigate and solve complex coding mysteries
add a done or queued progress callback to the appropriate list of callbacks for a specific type of event
Given the following Python 3 function, write the documentation def _add_subscribers_for_type(self, callback_type, subscribers, callbacks, **kwargs): ''' add a done/queued/progress callback to the appropriate list ''' for subscriber in subscribers: callback_name = 'on_' + callback_type ...
You are a Python code analyst, evaluating scripts for potential improvements.
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)
How would you code a function in Python 3 to add a done callback to be invoked when transfer is complete
You are a Python code architect, reviewing and designing scalable and efficient code
Add a callbacks to be invoked during transfer
Can you generate a brief explanation for the following Python 3 code def add_subscribers(self, subscribers, **kwargs): if subscribers: with self._callbacks_lock: self._add_subscribers_for_type( 'done', subscribers, self._done_callbacks, **kwargs) s...
You are a Python code generator, capable of creating scripts from specifications.
run the init or quued calback when the trasnfer is initiated on apsera
Given the following Python 3 function, write the documentation def _run_queued_callbacks(self): ''' run the init/quued calback when the trasnfer is initiated on apsera ''' for callback in self._queued_callbacks: try: callback() except Exception as ex: ...
You are a Python code generator, capable of creating scripts from specifications.
pass the number of bytes process to progress callbacks
Can you tell what is the following Python 3 function doing 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(by...
You are a Python code analyst, evaluating scripts for potential improvements.
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: ...
How would you implement a function in Python 3 that runs the callbacks and remove the callbacks from the internal list so they do not get run again.
You are a Python code generator, capable of creating scripts from specifications.
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 sel...
Implement a Python 3 function for getting the first node with the given role
As a Python code translator, you convert algorithms and pseudocode into Python.
Gets the BioCSentence object with the specified offset
Can you generate the documentation for the following Python 3 function def get_sentence(self, offset: int) -> BioCSentence or None: for sentence in self.sentences: if sentence.offset == offset: return sentence return None
As a Python code composer, you craft elegant and concise scripts.
def get_passage(self, offset: int) -> BioCPassage or None: """ Gets passage Args: offset: passage offset Return: the passage with specified offset """ for passage in self.passages: if passage.offset == offset: return p...
Can you write a function in Python 3 where it gets a passage with the specified offset
You are a Python code architect, reviewing and designing scalable and efficient code
Returns a collection of passages.
Here you have a function in Python 3, explain what it does def of(cls, *passages: BioCPassage): 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 ValueErro...
You are a Python code generator, capable of creating scripts from specifications.
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: ra...
Write a Python 3 function for returning a collection of documents.
As a python code expert, you are capable of creating scripts from specifications.
Add the given file_list to workbench as samples also add them as nodes.
Explain what the following Python 3 code does def add_it(workbench, file_list, labels): 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(p...
You are a Python code generator, capable of creating scripts from specifications.
Compute Jaccard similarities between all the observations in the feature list.
How would you explain what the following Python 3 function does 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 feature_info in feature_list: md5_target = fea...
As a Python code translator, you convert algorithms and pseudocode into Python.
Compute similarity between two sets using Jaccard similarity.
Make a summary of the following Python 3 code def jaccard_sim(features1, features2): set1 = set(features1) set2 = set(features2) try: return len(set1.intersection(set2))/float(max(len(set1), len(set2))) except ZeroDivisionError: return 0
As a Python code translator, you convert algorithms and pseudocode into 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
Write a Python 3 script for padding a text until the given length.
You are a Python code generator, capable of creating scripts from specifications.
def get_text(obj) -> Tuple[int, str]: """ Return text with its offset in the document Args: obj: BioCDocument, BioCPassage, or BioCSentence Returns: offset, text """ from bioc.bioc import BioCDocument, BioCPassage, BioCSentence if isinstance(obj, BioCSentence):...
Write a Python 3 function for returning the text of the most recent occurrence of a single object in the document with its offset in the document.
You are a Python code analyst, evaluating scripts for potential improvements.
Return a short repr of text if it is longer than 40
Can you generate the documentation for the following Python 3 function def shorten_text(text: str): if len(text) <= 40: text = text else: text = text[:17] + ' ... ' + text[-17:] return repr(text)
As a Python code composer, you craft elegant and concise scripts.
This worker computes meta data for any file type.
Explain what the following Python 3 code does 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'] ...
You are a Python code architect, reviewing and designing scalable and efficient code
Execute the Strings worker
Can you generate a brief explanation for the following Python 3 code 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}
As a Python code composer, you craft elegant and concise scripts.
Execute the PEIndicators worker
Given the following Python 3 function, write the documentation 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 ...
You are a Python code architect, reviewing and designing scalable and efficient code
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 Check...
Create a Python 3 function for checking for a checksum that doesn t match the generated checksum
You are a Python code generator, capable of creating scripts from specifications.
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...
Implement a function in Python 3 to check if a non - standard section name is present in the PE file.
As a Python code translator, you convert algorithms and pseudocode into 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_H...
How would you implement a function in Python 3 that checks if the reported image size matches the actual image size
You are a Python code architect, reviewing and designing scalable and efficient code
Checks if any of the sections are unaligned
Can you tell what is the following Python 3 function doing def check_section_unaligned(self): ''' Checking if any of the sections are unaligned ''' file_alignment = self.pefile_handle.OPTIONAL_HEADER.FileAlignment unaligned_sections = [] for section in self.pefile_handle.sections: ...
You are a Python code analyst, evaluating scripts for potential improvements.
Checks if any of the sections go past the total size of the image
Can you tell what is the following Python 3 function doing def check_section_oversized(self): ''' Checking if any of the sections go past the total size of the image ''' total_image_size = self.pefile_handle.OPTIONAL_HEADER.SizeOfImage for section in self.pefile_handle.sections: if ...
As a Python code analyst, you investigate and solve complex coding mysteries
def _search_for_import_symbols(self, matches): ''' Just encapsulating a search that takes place fairly often ''' # Sanity check if not hasattr(self.pefile_handle, 'DIRECTORY_ENTRY_IMPORT'): return [] # Find symbols that match pattern = '|'.join(re.escape(match) for ...
Write a Python 3 function for searching for all symbols that match a pattern in the list of matches.
You are a Python code generator, capable of creating scripts from specifications.
This method uses a regular expression to search for export symbols.
Given the following Python 3 function, write the documentation def _search_for_export_symbols(self, matches): ''' Just encapsulating a search that takes place fairly often ''' pattern = '|'.join(re.escape(match) for match in matches) exp = re.compile(pattern) symbol_list = [] try...
You are a Python code generator, capable of creating scripts from specifications.
def annotations(obj: BioCCollection or BioCDocument or BioCPassage or BioCSentence, docid: str = None, level: int = PASSAGE) -> Generator[BioCAnnotation, None, None]: """ Get all annotations in document id. Args: obj: BioCCollection, BioCDocument, BioCPassage, or BioCSentence ...
Write a Python 3 function that can return an iterator over the annotations of a given document or a collection of documents.
You are a Python code analyst, evaluating scripts for potential improvements.
def sentences(obj: BioCCollection or BioCDocument or BioCPassage) \ -> Generator[BioCSentence, None, None]: """ Get all sentences in document id. Args: obj: BioCCollection, BioCDocument, or BioCPassage Yields: one sentence """ if isinstance(obj, BioCCollectio...
Can you create a Python 3 function that returns an iterator over all sentences in a document id.
As a Python code composer, you craft elegant and concise scripts.
This worker classifies PEFiles as Evil or AOK
Explain what the following Python 3 code does def execute(self, input_data): ''' This worker classifies PEFiles as Evil or AOK (TOY not a real classifier at this point)''' # In general you'd do something different with these two outputs # for this toy example will just smash them in a big stri...
As a Python code translator, you convert algorithms and pseudocode into Python.
def dump(collection: BioCCollection, fp, pretty_print: bool = True): """ Serialize ``collection`` as a BioC formatted stream to ``fp``. Args: collection: the BioC collection fp: a ``.write()``-supporting file-like object pretty_print: enables formatted XML """ fp.wr...
How would you implement a function in Python 3 that serializes a collection as a BioC formatted stream to fp.
As a Python code composer, you craft elegant and concise scripts.
def dumps(collection: BioCCollection, pretty_print: bool = True) -> str: """ Serialize ``collection`` to a BioC formatted ``str``. Args: collection: the BioC collection pretty_print: enables formatted XML Returns: a BioC formatted ``str`` """ doc = etree.Elem...
How would you code a function in Python 3 to serialize a BioC collection to a BioC formatted str.
As a Python code translator, you convert algorithms and pseudocode into Python.
Encode a single location.
Can you tell what is the following Python 3 function doing def encode_location(location: BioCLocation): return etree.Element('location', {'offset': str(location.offset), 'length': str(location.length)})
You are a Python code architect, reviewing and designing scalable and efficient code
def encode_relation(relation: BioCRelation): """Encode a single relation.""" tree = etree.Element('relation', {'id': relation.id}) encode_infons(tree, relation.infons) for node in relation.nodes: tree.append(encode_node(node)) return tree
How would you code a function in Python 3 to encode a single relation.
You are a Python code analyst, evaluating scripts for potential improvements.
Encode a single annotation.
Here you have a function in Python 3, explain what it does def encode_annotation(annotation): tree = etree.Element('annotation', {'id': annotation.id}) encode_infons(tree, annotation.infons) for location in annotation.locations: tree.append(encode_location(location)) etree.SubElement(tree, ...
As a Python code analyst, you investigate and solve complex coding mysteries
def encode_sentence(sentence): """Encode a single sentence.""" tree = etree.Element('sentence') encode_infons(tree, sentence.infons) etree.SubElement(tree, 'offset').text = str(sentence.offset) if sentence.text: etree.SubElement(tree, 'text').text = sentence.text for ann in senten...
How would you implement a function in Python 3 that encodes a single sentence.
You are a Python code generator, capable of creating scripts from specifications.
def encode_passage(passage): """Encode a single passage.""" tree = etree.Element('passage') encode_infons(tree, passage.infons) etree.SubElement(tree, 'offset').text = str(passage.offset) if passage.text: etree.SubElement(tree, 'text').text = passage.text for sen in passage.senten...
Write a Python 3 function that can encode a single passage.
As a Python code translator, you convert algorithms and pseudocode into Python.
Encode a single document.
How would you explain what the following Python 3 function does def encode_document(document): tree = etree.Element('document') etree.SubElement(tree, 'id').text = document.id encode_infons(tree, document.infons) for passage in document.passages: tree.append(encode_passage(passage)) fo...
As a Python code composer, you craft elegant and concise scripts.
def encode_collection(collection): """Encode a single collection.""" tree = etree.Element('collection') etree.SubElement(tree, 'source').text = collection.source etree.SubElement(tree, 'date').text = collection.date etree.SubElement(tree, 'key').text = collection.key encode_infons(tree, co...
Can you implement a function in Python 3 that encodes a single collection.
You are a Python code analyst, evaluating scripts for potential improvements.
Implement this method in a subclass such that it returns a tree for o.
Explain what the following Python 3 code does def default(self, obj): if isinstance(obj, BioCDocument): return encode_document(obj) if isinstance(obj, BioCCollection): return encode_collection(obj) raise TypeError(f'Object of type {obj.__class__.__name__} is not BioC...
As a Python code composer, you craft elegant and concise scripts.
Writes the collection information to the underlying XML file.
Make a summary of the following Python 3 code def write_collection_info(self, collection: BioCCollection): elem = etree.Element('source') elem.text = collection.source self.__writer.send(elem) elem = etree.Element('date') elem.text = collection.date self.__writer....
You are a Python code architect, reviewing and designing scalable and efficient code
Encode and write a single document.
Can you generate a brief explanation for the following Python 3 code def write_document(self, document: BioCDocument): tree = self.encoder.encode(document) self.__writer.send(tree)
As a Python code composer, you craft elegant and concise scripts.
This client generates customer reports on all the samples in workbench.
Make a summary of the following Python 3 code def run(): # 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']) all_set = workbench.generat...
As a Python code translator, you convert algorithms and pseudocode into Python.
def check_io_access(ioobj, access, is_file=False): ''' check if a file/folder exists and has a given IO access ''' if ((is_file and not os.path.isfile(ioobj)) or (not is_file and not os.path.isdir(ioobj)) or not os.access(ioobj, access)): _objtype = "File" if is_file else "Direct...
Can you create a Python 3 function that checks if a file or folder exists and has a given IO access
As a Python code composer, you craft elegant and concise scripts.
Validate BioC data structure.
Can you generate a brief explanation for the following Python 3 code def validate(collection, onerror: Callable[[str, List], None] = None): BioCValidator(onerror).validate(collection)
As a python code expert, you are capable of creating scripts from specifications.
Validate a single document.
Can you generate the documentation for the following Python 3 function def validate_doc(self, document: BioCDocument): annotations = [] annotations.extend(document.annotations) annotations.extend(document.relations) for passage in document.passages: annotations.extend(passage...
You are a Python code generator, capable of creating scripts from specifications.
def validate(self, collection: BioCCollection): """Validate a single collection.""" for document in collection.documents: self.validate_doc(document)
Implement a function in Python 3 to validate a single collection.
You are a Python code analyst, evaluating scripts for potential improvements.
Execute the procdump plugin and store the output into the output field of the current table.
How would you explain what the following Python 3 function does def execute(self, input_data): ''' Execute method ''' # Spin up the rekall adapter adapter = RekallAdapter() adapter.set_plugin_name(self.plugin_name) # Create a temporary directory and run this plugin from...
You are a Python code architect, reviewing and designing scalable and efficient code
Convert string to UTF8
Explain what the following Python 3 code does def convert_to_utf8(string): ''' Convert string to UTF8 ''' if (isinstance(string, unicode)): return string.encode('utf-8') try: u = unicode(string, 'utf-8') except TypeError: return str(string) utf8 = u.encode('utf-8') return...
You are a Python code generator, capable of creating scripts from specifications.
Process the input bytes with pefile and extract the features
Can you generate the documentation for the following Python 3 function def execute(self, input_data): ''' Process the input bytes with pefile ''' raw_bytes = input_data['sample']['raw_bytes'] # Have the PE File module process the file pefile_handle, error_str = self.open_using_pefile('...
As a Python code analyst, you investigate and solve complex coding mysteries
def open_using_pefile(input_name, input_bytes): ''' Open the PE File using the Python pefile module. ''' try: pef = pefile.PE(data=input_bytes, fast_load=False) except (AttributeError, pefile.PEFormatError), error: print 'warning: pe_fail (with exception from pefile modul...
Write a Python 3 function that can open the PE File using the Python PEFile module.
As a python code expert, you are capable of creating scripts from specifications.
Process the PE File using the Python PEFile module.
How would you explain what the following Python 3 function does def extract_features_using_pefile(self, pef): ''' Process the PE File using the Python pefile module. ''' # Store all extracted features into feature lists extracted_dense = {} extracted_sparse = {} # Now slog thro...
You are a Python code architect, reviewing and designing scalable and efficient code
This method tries to parse the Bro log header section.
Make a summary of the following Python 3 code def _parse_bro_header(self, logfile): # Skip until you find the #fields line _line = next(logfile) while (not _line.startswith('#fields')): _line = next(logfile) # Read in the field names _field_names = _line.strip().spl...
As a Python code composer, you craft elegant and concise scripts.
Internal method that makes sure any dictionary elements are properly cast into the correct types.
Can you tell what is the following Python 3 function doing def _cast_dict(self, data_dict): for key, value in data_dict.iteritems(): data_dict[key] = self._cast_value(value) # Fixme: resp_body_data can be very large so removing it for now if 'resp_body_data' in data_dict: ...
You are a Python code analyst, evaluating scripts for potential improvements.
This client shows workbench extacting files from a zip file.
How would you explain what the following Python 3 function does def run(): # 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 ou...
You are a Python code generator, capable of creating scripts from specifications.
def execute(self, input_data): ''' Execute the VTQuery worker ''' md5 = input_data['meta']['md5'] response = requests.get('http://www.virustotal.com/vtapi/v2/file/report', params={'apikey':self.apikey,'resource':md5, 'allinfo':1}) # Make sure we got a js...
How would you implement a function in Python 3 that executes the VTQuery worker
As a Python code composer, you craft elegant and concise scripts.
def get_peid_db(): ''' Grab the peid_userdb.txt file from local disk ''' # Try to find the yara rules directory relative to the worker my_dir = os.path.dirname(os.path.realpath(__file__)) db_path = os.path.join(my_dir, 'peid_userdb.txt') if not os.path.exists(db_path): raise RuntimeError('p...
Implement a function in Python 3 to grab the peid_userdb. txt file from local disk
As a Python code composer, you craft elegant and concise scripts.
Get features from PEid signature database
Given the following Python 3 function, write the documentation def peid_features(self, pefile_handle): ''' Get features from PEid signature database''' peid_match = self.peid_sigs.match(pefile_handle) return peid_match if peid_match else []
As a Python code translator, you convert algorithms and pseudocode into Python.
This client pulls PCAP files for building report.
Make a summary of the following Python 3 code def run(): global WORKBENCH # Grab grab_server_argsrver 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...
You are a Python code analyst, evaluating scripts for potential improvements.
Renders template with view of the md5.
How would you explain what the following Python 3 function does def show_files(md5): '''Renders template with `view` of the md5.''' if not WORKBENCH: return flask.redirect('/') md5_view = WORKBENCH.work_request('view', md5) return flask.render_template('templates/md5_view.html', md5_view=md5_vi...
As a Python code composer, you craft elegant and concise scripts.
def show_md5_view(md5): '''Renders template with `stream_sample` of the md5.''' if not WORKBENCH: return flask.redirect('/') md5_view = WORKBENCH.stream_sample(md5) return flask.render_template('templates/md5_view.html', md5_view=list(md5_view), md5=md5)
How would you implement a function in Python 3 that renders template with stream_sample of the md5.
You are a Python code analyst, evaluating scripts for potential improvements.
Add the node with name and labels.
Can you generate a brief explanation for the following Python 3 code def add_node(self, node_id, name, labels): node = self.graph_db.get_or_create_indexed_node('Node', 'node_id', node_id, {'node_id': node_id, 'name': name}) try: node.add_labels(*labels) except NotImplementedError: ...
As a Python code composer, you craft elegant and concise scripts.
Add a relationship between nodes.
Can you generate a brief explanation for the following Python 3 code def add_rel(self, source_node_id, target_node_id, rel): # Add the relationship n1_ref = self.graph_db.get_indexed_node('Node', 'node_id', source_node_id) n2_ref = self.graph_db.get_indexed_node('Node', 'node_id', target_node_i...
As a Python code composer, you craft elegant and concise scripts.
Add a node to the database.
Make a summary of the following Python 3 code def add_node(self, node_id, name, labels): print 'NeoDB Stub getting called...' print '%s %s %s %s' % (self, node_id, name, labels)
You are a Python code generator, capable of creating scripts from specifications.
Add a relationship between two nodes.
How would you explain what the following Python 3 function does def add_rel(self, source_node_id, target_node_id, rel): print 'NeoDB Stub getting called...' print '%s %s %s %s' % (self, source_node_id, target_node_id, rel)
As a Python code analyst, you investigate and solve complex coding mysteries
Yields the lines of a file in a generator.
How would you explain what the following Python 3 function does def tail_file(filename): ''' Tail a file using pygtail. Note: this could probably be improved ''' with make_temp_file() as offset_file: while True: for line in pygtail.Pygtail(filename, offset_file=offset_file): ...
As a Python code analyst, you investigate and solve complex coding mysteries
def execute(self, input_data): ''' Execute the ViewPE worker ''' # Just a small check to make sure we haven't been called on the wrong file type if (input_data['meta']['type_tag'] != 'exe'): return {'error': self.__class__.__name__+': called on '+input_data['meta']['type_tag']} ...
Write a Python 3 script for executing the ViewPE worker
As a python code expert, you are capable of creating scripts from specifications.
Safely access dictionary keys when plugin may have failed
Here you have a function in Python 3, explain what it does def safe_get(data, key_list): ''' Safely access dictionary keys when plugin may have failed ''' for key in key_list: data = data.get(key, {}) return data if data else 'plugin_failed'
You are a Python code architect, reviewing and designing scalable and efficient code
def execute(self): ''' Begin capturing PCAPs and sending them to workbench ''' # Create a temporary directory self.temp_dir = tempfile.mkdtemp() os.chdir(self.temp_dir) # Spin up the directory watcher DirWatcher(self.temp_dir, self.file_created) # Spin up tcpdu...
Implement a Python 3 function for beginning capturing PCAPs and sending them to workbench
As a python code expert, you are capable of creating scripts from specifications.
def store_file(self, filename): ''' Store a file into workbench ''' # Spin up workbench self.workbench = zerorpc.Client(timeout=300, heartbeat=60) self.workbench.connect("tcp://127.0.0.1:4242") # Open the file and send it to workbench storage_name = "streamin...
Implement a function in Python 3 to store a file into workbench
As a Python code analyst, you investigate and solve complex coding mysteries
def encode_document(obj): """Encode a single document.""" warnings.warn("deprecated. Please use bioc.biocxml.encoder.encode_document", DeprecationWarning) return bioc.biocxml.encoder.encode_document(obj)
How would you code a function in Python 3 to encode a single document.
As a Python code composer, you craft elegant and concise scripts.
Encode a single passage.
Can you generate the documentation for the following Python 3 function def encode_passage(obj): warnings.warn("deprecated. Please use bioc.biocxml.encoder.encode_passage", DeprecationWarning) return bioc.biocxml.encoder.encode_passage(obj)
You are a Python code analyst, evaluating scripts for potential improvements.
def encode_sentence(obj): """Encode a single sentence.""" warnings.warn("deprecated. Please use bioc.biocxml.encoder.encode_sentence", DeprecationWarning) return bioc.biocxml.encoder.encode_sentence(obj)
Create a Python 3 function for encoding a single sentence.
You are a Python code architect, reviewing and designing scalable and efficient code
Encode a single annotation.
Here you have a function in Python 3, explain what it does def encode_annotation(obj): warnings.warn("deprecated. Please use bioc.biocxml.encoder.encode_annotation", DeprecationWarning) return bioc.biocxml.encoder.encode_annotation(obj)
As a Python code translator, you convert algorithms and pseudocode into Python.
Encode a single relation.
How would you explain what the following Python 3 function does def encode_relation(obj): warnings.warn("deprecated. Please use bioc.biocxml.encoder.encode_relation", DeprecationWarning) return bioc.biocxml.encoder.encode_relation(obj)
As a Python code composer, you craft elegant and concise scripts.
def parse_eprocess(self, eprocess_data): """Parse the EProcess object we get from some rekall output""" Name = eprocess_data['_EPROCESS']['Cybox']['Name'] PID = eprocess_data['_EPROCESS']['Cybox']['PID'] PPID = eprocess_data['_EPROCESS']['Cybox']['Parent_PID'] return {'Name': Nam...
Implement a function in Python 3 to parse the EProcess object we get from some rekall output
As a python code expert, you are capable of creating scripts from specifications.
Execute the Unzip worker
How would you explain what the following Python 3 function does def execute(self, input_data): ''' Execute the Unzip worker ''' raw_bytes = input_data['sample']['raw_bytes'] zipfile_output = zipfile.ZipFile(StringIO(raw_bytes)) payload_md5s = [] for name in zipfile_output.namelis...
You are a Python code analyst, evaluating scripts for potential improvements.
def execute(self, input_data): ''' Execute method ''' # Spin up the rekall adapter adapter = RekallAdapter() adapter.set_plugin_name(self.plugin_name) rekall_output = adapter.execute(input_data) # Process the output data for line in rekall_output: i...
Can you write a function in Python 3 where it executes the method in the base class.
As a python code expert, you are capable of creating scripts from specifications.
def help_cli(self): """ Help on Workbench CLI """ help = '%sWelcome to Workbench CLI Help:%s' % (color.Yellow, color.Normal) help += '\n\t%s> help cli_basic %s for getting started help' % (color.Green, color.LightBlue) help += '\n\t%s> help workers %s for help on available workers' % (co...
Write a Python 3 function for helping on Workbench CLI
As a Python code analyst, you investigate and solve complex coding mysteries
def help_cli_basic(self): """ Help for Workbench CLI Basics """ help = '%sWorkbench: Getting started...' % (color.Yellow) help += '\n%sLoad in a sample:' % (color.Green) help += '\n\t%s> load_sample /path/to/file' % (color.LightBlue) help += '\n\n%sNotice the prompt now shows t...
Write a Python 3 script to help for Workbench CLI Basics
You are a Python code architect, reviewing and designing scalable and efficient code
Help for Workbench CLI Search
Explain what the following Python 3 code does def help_cli_search(self): help = '%sSearch: %s returns sample_sets, a sample_set is a set/list of md5s.' % (color.Yellow, color.Green) help += '\n\n\t%sSearch for all samples in the database that are known bad pe files,' % (color.Green) help += '\...
You are a Python code analyst, evaluating scripts for potential improvements.
Help for making a DataFrame with Workbench CLI
Here you have a function in Python 3, explain what it does def help_dataframe(self): help = '%sMaking a DataFrame: %s how to make a dataframe from raw data (pcap, memory, pe files)' % (color.Yellow, color.Green) help += '\n\t%sNote: for memory_image and pe_files see > help dataframe_memory or dataframe...
You are a Python code architect, reviewing and designing scalable and efficient code
def help_dataframe_memory(self): """ Help for making a DataFrame with Workbench CLI """ help = '%sMaking a DataFrame: %s how to make a dataframe from memory_forensics sample' % (color.Yellow, color.Green) help += '\n\n%sMemory Images Example:' % (color.Green) help += '\n\t%s> load_samp...
Can you create a Python 3 function that helps for making a dataframe with Workbench CLI
You are a Python code architect, reviewing and designing scalable and efficient code
def help_dataframe_pe(self): """ Help for making a DataFrame with Workbench CLI """ help = '%sMaking a DataFrame: %s how to make a dataframe from pe files' % (color.Yellow, color.Green) help += '\n\n%sPE Files Example (loading a directory):' % (color.Green) help += '\n\t%s> load_sample...
Write a Python 3 function that can help for making a DataFrame from PE files
As a Python code composer, you craft elegant and concise scripts.
Returns a list of all the Workbench commands
Make a summary of the following Python 3 code def _all_help_methods(self): methods = {name:method for name, method in inspect.getmembers(self, predicate=inspect.isroutine) if not name.startswith('_')} return methods
You are a Python code analyst, evaluating scripts for potential improvements.
def execute(self, input_data): ''' ViewPcapDeep execute method ''' # Copy info from input view = input_data['view_pcap'] # Grab a couple of handles extracted_files = input_data['view_pcap']['extracted_files'] # Dump a couple of fields del view['extracted_files'...
Can you write a function in Python 3 where it executes the view_pcap_deep method
As a Python code composer, you craft elegant and concise scripts.
Execute method that returns the sample s meta data files
Can you tell what is the following Python 3 function doing def execute(self, input_data): ''' Execute Method ''' # View on all the meta data files in the sample fields = ['filename', 'md5', 'length', 'customer', 'import_time', 'type_tag'] view = {key:input_data['meta'][key] for key in f...
You are a Python code architect, reviewing and designing scalable and efficient code
def execute(self, input_data): """ Info objects all have a type_tag of ('help','worker','command', or 'other') """ input_data = input_data['info'] type_tag = input_data['type_tag'] if type_tag == 'help': return {'help': input_data['help'], 'type_tag': input_data['type_tag']} ...
Write a Python 3 function for executing the action for the info object
As a Python code translator, you convert algorithms and pseudocode into Python.
Deserialize a dict obj to a BioCCollection object
Can you generate a brief explanation for the following Python 3 code def parse_collection(obj: dict) -> BioCCollection: collection = BioCCollection() collection.source = obj['source'] collection.date = obj['date'] collection.key = obj['key'] collection.infons = obj['infons'] for doc in obj...
As a Python code analyst, you investigate and solve complex coding mysteries
Deserialize a dict obj to a BioCSentence object
Explain what the following Python 3 code does def parse_sentence(obj: dict) -> BioCSentence: sentence = BioCSentence() sentence.offset = obj['offset'] sentence.infons = obj['infons'] sentence.text = obj['text'] for annotation in obj['annotations']: sentence.add_annotation(parse_annotat...
As a Python code analyst, you investigate and solve complex coding mysteries
Deserialize a dict obj to a BioCDocument object
Can you generate the documentation for the following Python 3 function def parse_doc(obj: dict) -> BioCDocument: doc = BioCDocument() doc.id = obj['id'] doc.infons = obj['infons'] for passage in obj['passages']: doc.add_passage(parse_passage(passage)) for annotation in obj['annotations...
You are a Python code architect, reviewing and designing scalable and efficient code
Deserialize a string containing a JSON document into a collection of BioC objects.
Can you generate the documentation for the following Python 3 function def loads(s: str, **kwargs) -> BioCCollection: obj = json.loads(s, **kwargs) return parse_collection(obj)
As a Python code analyst, you investigate and solve complex coding mysteries
def execute(self, input_data): ''' Okay this worker is going build graphs from PCAP Bro output logs ''' # Grab the Bro log handles from the input bro_logs = input_data['pcap_bro'] # Weird log if 'weird_log' in bro_logs: stream = self.workbench.stream_sample(bro_logs...
Write a Python 3 function that can okay this worker is going build graphs from PCAP Bro output logs
As a Python code analyst, you investigate and solve complex coding mysteries
Build a graph of nodes and edges from a Bro http. log file.
Can you generate a brief explanation for the following Python 3 code def http_log_graph(self, stream): ''' Build up a graph (nodes and edges from a Bro http.log) ''' print 'Entering http_log_graph...' for row in list(stream): # Skip '-' hosts if (row['id.orig_h'] == '-')...
As a Python code analyst, you investigate and solve complex coding mysteries