output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
def Read(self): """See base class.""" raw_in = os.read(self.dev, self.GetInReportDataLength()) decoded_in = list(bytearray(raw_in)) return decoded_in
Write a Python 3 script to read the next chunk of data from the device.
You are a Python code analyst, evaluating scripts for potential improvements.
Fills out the attributes of the device into the device descriptor.
Make a summary of the following Python 3 code def FillDeviceAttributes(device, descriptor): attributes = HidAttributes() result = hid.HidD_GetAttributes(device, ctypes.byref(attributes)) if not result: raise ctypes.WinError() buf = ctypes.create_string_buffer(1024) result = hid.HidD_GetProductString(devi...
As a Python code composer, you craft elegant and concise scripts.
def FillDeviceCapabilities(device, descriptor): """Fill out device capabilities. Fills the HidCapabilitites of the device into descriptor. Args: device: A handle to the open device descriptor: DeviceDescriptor to populate with the capabilities Returns: none Raises: WindowsError when ...
How would you code a function in Python 3 to fill out the HidCapabilitites of the device into the device descriptor.
As a Python code analyst, you investigate and solve complex coding mysteries
Open the device and return a handle to it.
Make a summary of the following Python 3 code def OpenDevice(path, enum=False): desired_access = GENERIC_WRITE | GENERIC_READ share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE if enum: desired_access = 0 h = kernel32.CreateFileA(path, desired_access, shar...
As a Python code analyst, you investigate and solve complex coding mysteries
def Enumerate(): """See base class.""" hid_guid = GUID() hid.HidD_GetHidGuid(ctypes.byref(hid_guid)) devices = setupapi.SetupDiGetClassDevsA( ctypes.byref(hid_guid), None, None, 0x12) index = 0 interface_info = DeviceInterfaceData() interface_info.cbSize = ctypes.sizeof(DeviceInterf...
Write a Python 3 script for enumerating the available devices.
As a python code expert, you are capable of creating scripts from specifications.
Writes a packet to the report.
Can you tell what is the following Python 3 function doing def Write(self, packet): if len(packet) != self.GetOutReportDataLength(): raise errors.HidError("Packet length must match report data length.") packet_data = [0] + packet # Prepend the zero-byte (report ID) out = bytes(bytearray(packet_data)...
You are a Python code analyst, evaluating scripts for potential improvements.
def Read(self): """See base class.""" buf = ctypes.create_string_buffer(self.desc.internal_max_in_report_len) num_read = wintypes.DWORD() ret = kernel32.ReadFile( self.dev, buf, len(buf), ctypes.byref(num_read), None) if num_read.value != self.desc.internal_max_in_report_len: raise er...
Can you implement a function in Python 3 that reads the next report from the device.
As a Python code composer, you craft elegant and concise scripts.
def Authenticate(self, app_id, challenge_data, print_callback=sys.stderr.write): """See base class.""" for authenticator in self.authenticators: if authenticator.IsAvailable(): result = authenticator.Authenticate(app_id, challenge_data...
Write a Python 3 script for authenticating the user with the challenge data.
You are a Python code generator, capable of creating scripts from specifications.
Obtains a U2FInterface for the first valid local U2FHID device found.
Can you tell what is the following Python 3 function doing def GetLocalU2FInterface(origin=socket.gethostname()): hid_transports = hidtransport.DiscoverLocalHIDU2FDevices() for t in hid_transports: try: return U2FInterface(security_key=hardware.SecurityKey(transport=t), origin=or...
You are a Python code analyst, evaluating scripts for potential improvements.
Registers the app_id with the security key.
Make a summary of the following Python 3 code def Register(self, app_id, challenge, registered_keys): client_data = model.ClientData(model.ClientData.TYP_REGISTRATION, challenge, self.origin) challenge_param = self.InternalSHA256(client_data.GetJson()) app_param = self.Int...
As a Python code translator, you convert algorithms and pseudocode into Python.
Authenticates app_id with the security key.
Can you generate a brief explanation for the following Python 3 code def Authenticate(self, app_id, challenge, registered_keys): client_data = model.ClientData(model.ClientData.TYP_AUTHENTICATION, challenge, self.origin) app_param = self.InternalSHA256(app_id) challenge_pa...
As a Python code composer, you craft elegant and concise scripts.
This function is used to register a security key with a particular origin & client.
Explain what the following Python 3 code does def CmdRegister(self, challenge_param, app_param): self.logger.debug('CmdRegister') if len(challenge_param) != 32 or len(app_param) != 32: raise errors.InvalidRequestError() body = bytearray(challenge_param + app_param) response = self.InternalSendApd...
You are a Python code architect, reviewing and designing scalable and efficient code
This function is used to request an authentication signature over a particular key handle.
Make a summary of the following Python 3 code def CmdAuthenticate(self, challenge_param, app_param, key_handle, check_only=False): """Attempt to obtain an authentication signature. Ask the security key to sign a challenge f...
As a Python code composer, you craft elegant and concise scripts.
def CmdVersion(self): """Obtain the version of the device and test transport format. Obtains the version of the device and determines whether to use ISO 7816-4 or the U2f variant. This function should be called at least once before CmdAuthenticate or CmdRegister to make sure the object is using the ...
Write a Python 3 script for obtaining the version of the device and test transport format. Obtains the version of the device and determines whether to use ISO 7816-4 or the U2f variant. This function should be called at least once before CmdAuthenticate or CmdRegister to make sure the object is using the proper transpo...
As a python code expert, you are capable of creating scripts from specifications.
def InternalSendApdu(self, apdu_to_send): """Send an APDU to the device. Sends an APDU to the device, possibly falling back to the legacy encoding format that is not ISO7816-4 compatible. Args: apdu_to_send: The CommandApdu object to send Returns: The ResponseApdu object constructed o...
Write a Python 3 function that can send an APDU to the device.
As a python code expert, you are capable of creating scripts from specifications.
def GetDeviceIntProperty(dev_ref, key): """Reads int property from the HID device.""" cf_key = CFStr(key) type_ref = iokit.IOHIDDeviceGetProperty(dev_ref, cf_key) cf.CFRelease(cf_key) if not type_ref: return None if cf.CFGetTypeID(type_ref) != cf.CFNumberGetTypeID(): raise errors.OsHidError('Expect...
Can you implement a function in Python 3 that reads int property from the HID device.
You are a Python code analyst, evaluating scripts for potential improvements.
def GetDeviceStringProperty(dev_ref, key): """Reads string property from the HID device.""" cf_key = CFStr(key) type_ref = iokit.IOHIDDeviceGetProperty(dev_ref, cf_key) cf.CFRelease(cf_key) if not type_ref: return None if cf.CFGetTypeID(type_ref) != cf.CFStringGetTypeID(): raise errors.OsHidError('...
Can you implement a function in Python 3 that reads string property from the HID device.
As a python code expert, you are capable of creating scripts from specifications.
Retrieves the unique path for the device.
Make a summary of the following Python 3 code def GetDevicePath(device_handle): # Obtain device path from IO Registry io_service_obj = iokit.IOHIDDeviceGetService(device_handle) str_buffer = ctypes.create_string_buffer(DEVICE_PATH_BUFFER_SIZE) iokit.IORegistryEntryGetPath(io_service_obj, K_IO_SERVICE_PLANE, str...
You are a Python code architect, reviewing and designing scalable and efficient code
Handles incoming IN report from HID device.
Explain what the following Python 3 code does def HidReadCallback(read_queue, result, sender, report_type, report_id, report, report_length): """Handles incoming IN report from HID device.""" del result, sender, report_type, report_id # Unused by the callback function incoming_bytes = [repor...
You are a Python code generator, capable of creating scripts from specifications.
def DeviceReadThread(hid_device): """Binds a device to the thread's run loop, then starts the run loop. Args: hid_device: The MacOsHidDevice object The HID manager requires a run loop to handle Report reads. This thread function serves that purpose. """ # Schedule device events with run loop hid_de...
Write a Python 3 script for binding a device to the run loop and starts the run loop.
You are a Python code generator, capable of creating scripts from specifications.
Enumerate the HID components of a single HID container.
Here you have a function in Python 3, explain what it does def Enumerate(): # Init a HID manager hid_mgr = iokit.IOHIDManagerCreate(None, None) if not hid_mgr: raise errors.OsHidError('Unable to obtain HID manager reference') iokit.IOHIDManagerSetDeviceMatching(hid_mgr, None) # Get devices fr...
You are a Python code analyst, evaluating scripts for potential improvements.
def Write(self, packet): """See base class.""" report_id = 0 out_report_buffer = (ctypes.c_uint8 * self.internal_max_out_report_len)() out_report_buffer[:] = packet[:] result = iokit.IOHIDDeviceSetReport(self.device_handle, K_IO_HID_REPORT_TYPE_OUTPUT, ...
Create a Python 3 function for writing a report to device.
As a Python code translator, you convert algorithms and pseudocode into Python.
def Read(self): """See base class.""" result = None while result is None: try: result = self.read_queue.get(timeout=60) except queue.Empty: continue return result
Implement a Python 3 function for reading a single element from the read queue.
You are a Python code architect, reviewing and designing scalable and efficient code
def change_view(self, *args, **kwargs): """Renders detailed model edit page.""" Hierarchy.init_hierarchy(self) self.hierarchy.hook_change_view(self, args, kwargs) return super(HierarchicalModelAdmin, self).change_view(*args, **kwargs)
Write a Python 3 script for rendering detailed model edit page.
As a Python code analyst, you investigate and solve complex coding mysteries
Renders checkboxes. Disable checkbox for parent item navigation link.
Given the following Python 3 function, write the documentation def action_checkbox(self, obj): if getattr(obj, Hierarchy.UPPER_LEVEL_MODEL_ATTR, False): return '' return super(HierarchicalModelAdmin, self).action_checkbox(obj)
You are a Python code generator, capable of creating scripts from specifications.
Renders hierarchy navigation elements.
Can you generate the documentation for the following Python 3 function def hierarchy_nav(self, obj): result_repr = '' # For items without children. ch_count = getattr(obj, Hierarchy.CHILD_COUNT_MODEL_ATTR, 0) is_parent_link = getattr(obj, Hierarchy.UPPER_LEVEL_MODEL_ATTR, False) if i...
As a python code expert, you are capable of creating scripts from specifications.
def get_queryset(self, request): """Constructs a query set. :param request: :return: """ self._hierarchy.hook_get_queryset(self, request) return super(HierarchicalChangeList, self).get_queryset(request)
Write a Python 3 function that can construct a query set.
You are a Python code generator, capable of creating scripts from specifications.
Gets query set results.
Can you tell what is the following Python 3 function doing def get_results(self, request): super(HierarchicalChangeList, self).get_results(request) self._hierarchy.hook_get_results(self)
As a python code expert, you are capable of creating scripts from specifications.
Implements field exists check for debugging purposes.
Given the following Python 3 function, write the documentation def check_field_exists(self, field_name): if not settings.DEBUG: return try: self.lookup_opts.get_field(field_name) except FieldDoesNotExist as e: raise AdmirarchyConfigurationError(e)
As a Python code composer, you craft elegant and concise scripts.
Initializes model admin with hierarchy data.
How would you explain what the following Python 3 function does def init_hierarchy(cls, model_admin): hierarchy = getattr(model_admin, 'hierarchy') if hierarchy: if not isinstance(hierarchy, Hierarchy): hierarchy = AdjacencyList() # For `True` and etc. TODO heuristics maybe...
You are a Python code generator, capable of creating scripts from specifications.
Gets parent ID from query string.
How would you explain what the following Python 3 function does def get_pid_from_request(cls, changelist, request): val = request.GET.get(cls.PARENT_ID_QS_PARAM, False) pid = val or None try: del changelist.params[cls.PARENT_ID_QS_PARAM] except KeyError: pass ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Hooked by ChangeList. get_queryset.
Explain what the following Python 3 code does def hook_get_queryset(self, changelist, request): changelist.check_field_exists(self.pid_field) self.pid = self.get_pid_from_request(changelist, request) changelist.params[self.pid_field] = self.pid
You are a Python code generator, capable of creating scripts from specifications.
Hooked by ChangeList. get_results.
How would you explain what the following Python 3 function does def hook_get_results(self, changelist): result_list = list(changelist.result_list) if self.pid: # Render to upper level link. parent = changelist.model.objects.get(pk=self.pid) parent = changelist.model(...
As a Python code translator, you convert algorithms and pseudocode into Python.
Hooked by ChangeList. get_queryset.
Can you generate the documentation for the following Python 3 function def hook_get_queryset(self, changelist, request): changelist.check_field_exists(self.left_field) changelist.check_field_exists(self.right_field) self.pid = self.get_pid_from_request(changelist, request) # Get parent ...
You are a Python code analyst, evaluating scripts for potential improvements.
Reads a file within package directories.
Can you generate a brief explanation for the following Python 3 code def read_file(fpath): with io.open(os.path.join(PATH_BASE, fpath)) as f: return f.read()
You are a Python code architect, reviewing and designing scalable and efficient code
Returns version number without module import
Can you generate a brief explanation for the following Python 3 code def get_version(): contents = read_file(os.path.join('admirarchy', '__init__.py')) version = re.search('VERSION = \(([^)]+)\)', contents) version = version.group(1).replace(', ', '.').strip() return version
You are a Python code generator, capable of creating scripts from specifications.
def process_update(self, update): """Process an incoming update from a remote NetworkTables""" data = json.loads(update) NetworkTables.getEntry(data["k"]).setValue(data["v"])
Create a Python 3 function to process an incoming update from a remote NetworkTables
As a Python code translator, you convert algorithms and pseudocode into Python.
Send a NetworkTables update via the stored send_update callback
Can you generate the documentation for the following Python 3 function def _send_update(self, data): if isinstance(data, dict): data = json.dumps(data) self.update_callback(data)
As a Python code translator, you convert algorithms and pseudocode into Python.
def close(self): """ Clean up NetworkTables listeners """ NetworkTables.removeGlobalListener(self._nt_on_change) NetworkTables.removeConnectionListener(self._nt_connected)
Can you create a Python 3 function that cleans up listeners that are no longer needed.
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns a dict of str climate zones that contain lat and long coordinates.
Explain what the following Python 3 code does def get_lat_long_climate_zones(latitude, longitude): try: from shapely.geometry import Point except ImportError: # pragma: no cover raise ImportError("Finding climate zone of lat/long points requires shapely.") ( iecc_climate_zones, ...
You are a Python code generator, capable of creating scripts from specifications.
Get the metadata about a ZIP Code Tabulation Area.
Can you generate a brief explanation for the following Python 3 code def get_zcta_metadata(zcta): conn = metadata_db_connection_proxy.get_connection() cur = conn.cursor() cur.execute( """ select * from zcta_metadata where zcta_id = ? """, (zcta,)...
You are a Python code architect, reviewing and designing scalable and efficient code
def zcta_to_lat_long(zcta): """Get location of ZCTA centroid Retrieves latitude and longitude of centroid of ZCTA to use for matching with weather station. Parameters ---------- zcta : str ID of the target ZCTA. Returns ------- latitude : float Latitude of centroid...
Write a Python 3 script to get latitude and longitude of the target ZCTA in the specified location.
As a python code expert, you are capable of creating scripts from specifications.
Returns a list of all supported ZCTAs optionally by state.
Can you generate a brief explanation for the following Python 3 code def get_zcta_ids(state=None): conn = metadata_db_connection_proxy.get_connection() cur = conn.cursor() if state is None: cur.execute( """ select zcta_id from zcta_metadata """ ) else: ...
You are a Python code architect, reviewing and designing scalable and efficient code
def valid_zcta_or_raise(zcta): """ Check if ZCTA is valid and raise eeweather.UnrecognizedZCTAError if not. """ conn = metadata_db_connection_proxy.get_connection() cur = conn.cursor() cur.execute( """ select exists ( select zcta_id from zcta_metadata ...
Can you write a function in Python 3 where it checks if ZCTA is valid and raise UnrecognizedZCTAError if not.
As a Python code translator, you convert algorithms and pseudocode into Python.
Check if USAF ID is valid and raise UnrecognizedUSAFIDError if not.
How would you explain what the following Python 3 function does def valid_usaf_id_or_raise(usaf_id): conn = metadata_db_connection_proxy.get_connection() cur = conn.cursor() cur.execute( """ select exists ( select usaf_id from isd_station_metadata w...
As a Python code analyst, you investigate and solve complex coding mysteries
def rank_stations( site_latitude, site_longitude, site_state=None, site_elevation=None, match_iecc_climate_zone=False, match_iecc_moisture_regime=False, match_ba_climate_zone=False, match_ca_climate_zone=False, match_state=False, minimum_quality=None, minimum_tmy3_class=None,...
Implement a Python 3 function for returning a ranked version of the candidate weather stations and metadata structures for a particular site.
As a Python code composer, you craft elegant and concise scripts.
Combine the ranked stations into a single hybrid ranking dataframe.
Explain what the following Python 3 code does def combine_ranked_stations(rankings): if len(rankings) == 0: raise ValueError("Requires at least one ranking.") combined_ranking = rankings[0] for ranking in rankings[1:]: filtered_ranking = ranking[~ranking.index.isin(combined_ranking.index)]...
As a Python code analyst, you investigate and solve complex coding mysteries
def select_station( candidates, coverage_range=None, min_fraction_coverage=0.9, distance_warnings=(50000, 200000), rank=1, ): """ Select a station from a list of candidates that meets given data quality criteria. Parameters ---------- candidates : :any:`pandas.DataFrame` ...
How would you code a function in Python 3 to select a single station from a list of candidates that meets a given data.
As a python code expert, you are capable of creating scripts from specifications.
def _load_isd_station_metadata(download_path): """ Collect metadata for US isd stations. """ from shapely.geometry import Point # load ISD history which contains metadata isd_history = pd.read_csv( os.path.join(download_path, "isd-history.csv"), dtype=str, parse_dates=["BEGI...
How would you code a function in Python 3 to load ISD stations metadata from a CSV file.
As a Python code composer, you craft elegant and concise scripts.
Load the metadata for the isd files.
Can you tell what is the following Python 3 function doing def _load_isd_file_metadata(download_path, isd_station_metadata): isd_inventory = pd.read_csv( os.path.join(download_path, "isd-inventory.csv"), dtype=str ) # filter to stations with metadata station_keep = [usaf in isd_station_metadat...
As a Python code analyst, you investigate and solve complex coding mysteries
def build_metadata_db( zcta_geometry=False, iecc_climate_zone_geometry=True, iecc_moisture_regime_geometry=True, ba_climate_zone_geometry=True, ca_climate_zone_geometry=True, ): """ Build database of metadata from primary sources. Downloads primary sources, clears existing DB, and rebuilds ...
Can you create a Python 3 function that builds the metadata database from primary sources.
As a Python code composer, you craft elegant and concise scripts.
def json(self): """ Return a JSON-serializeable object containing station metadata.""" return { "elevation": self.elevation, "latitude": self.latitude, "longitude": self.longitude, "icao_code": self.icao_code, "name": self.name, "qu...
Write a Python 3 script to return a JSON - serializeable object containing station metadata.
As a Python code composer, you craft elegant and concise scripts.
def get_isd_filenames(self, year=None, with_host=False): """ Get filenames of raw ISD station data. """ return get_isd_filenames(self.usaf_id, year, with_host=with_host)
Can you implement a function in Python 3 that gets filenames of raw ISD station data.
As a python code expert, you are capable of creating scripts from specifications.
def get_gsod_filenames(self, year=None, with_host=False): """ Get filenames of raw GSOD station data. """ return get_gsod_filenames(self.usaf_id, year, with_host=with_host)
Write a Python 3 script for getting filenames of GSOD station data.
As a python code expert, you are capable of creating scripts from specifications.
Load ISD hourly temperature data from start to end date.
Given the following Python 3 function, write the documentation def load_isd_hourly_temp_data( self, start, end, read_from_cache=True, write_to_cache=True, error_on_missing_years=True, ): """ Load resampled hourly ISD temperature data from start date to end dat...
As a Python code analyst, you investigate and solve complex coding mysteries
Load resampled daily ISD temperature data from start date to end date.
Given the following Python 3 function, write the documentation def load_isd_daily_temp_data( self, start, end, read_from_cache=True, write_to_cache=True ): """ Load resampled daily ISD temperature data from start date to end date (inclusive). This is the primary convenience method for loadi...
As a Python code composer, you craft elegant and concise scripts.
def load_gsod_daily_temp_data( self, start, end, read_from_cache=True, write_to_cache=True ): """ Load resampled daily GSOD temperature data from start date to end date (inclusive). This is the primary convenience method for loading resampled daily GSOD temperature data. Parameters...
Can you write a function in Python 3 where it loads resampled GSOD temperature data from start date to end date.
As a Python code translator, you convert algorithms and pseudocode into Python.
Load TMY3 hourly temperature data from start to end date.
Here you have a function in Python 3, explain what it does def load_tmy3_hourly_temp_data( self, start, end, read_from_cache=True, write_to_cache=True ): """ Load hourly TMY3 temperature data from start date to end date (inclusive). This is the primary convenience method for loading hourly ...
You are a Python code generator, capable of creating scripts from specifications.
Load hourly CZ2010 temperature data from start date to end date.
Can you generate the documentation for the following Python 3 function def load_cz2010_hourly_temp_data( self, start, end, read_from_cache=True, write_to_cache=True ): """ Load hourly CZ2010 temperature data from start date to end date (inclusive). This is the primary convenience method for...
As a Python code composer, you craft elegant and concise scripts.
Plots this mapping on a map.
How would you explain what the following Python 3 function does def plot_station_mapping( target_latitude, target_longitude, isd_station, distance_meters, target_label="target", ): # pragma: no cover """ Plots this mapping on a map.""" try: import matplotlib.pyplot as plt except...
You are a Python code analyst, evaluating scripts for potential improvements.
def plot_station_mappings(mapping_results): # pragma: no cover """ Plot a list of mapping results on a map. Requires matplotlib and cartopy. Parameters ---------- mapping_results : list of MappingResult objects Mapping results to plot """ try: import matplotlib.pyplot as p...
How would you implement a function in Python 3 that plots a list of mapping results on a map.
You are a Python code generator, capable of creating scripts from specifications.
Execute the ViewPDF worker
Can you generate the documentation for the following Python 3 function def execute(self, input_data): ''' Execute the ViewPDF worker ''' # Just a small check to make sure we haven't been called on the wrong file type if (input_data['meta']['type_tag'] != 'pdf'): return {'error': sel...
As a Python code translator, you convert algorithms and pseudocode into Python.
def conn_log_graph(self, stream): ''' Build up a graph (nodes and edges from a Bro conn.log) ''' conn_log = list(stream) print 'Entering conn_log_graph...(%d rows)' % len(conn_log) for row in stream: # Add the connection id with service as one of the labels self....
How would you implement a function in Python 3 that builds a graph of nodes and edges from a conn. log file.
You are a Python code generator, capable of creating scripts from specifications.
Build a graph of nodes and edges from a Bro dns. log file.
Make a summary of the following Python 3 code def dns_log_graph(self, stream): ''' Build up a graph (nodes and edges from a Bro dns.log) ''' dns_log = list(stream) print 'Entering dns_log_graph...(%d rows)' % len(dns_log) for row in dns_log: # Skip '-' hosts ...
As a Python code composer, you craft elegant and concise scripts.
Build a graph of nodes and edges from a Bro weird. log file.
Can you generate the documentation for the following Python 3 function def weird_log_graph(self, stream): ''' Build up a graph (nodes and edges from a Bro weird.log) ''' weird_log = list(stream) print 'Entering weird_log_graph...(%d rows)' % len(weird_log) # Here we're just going to cap...
You are a Python code analyst, evaluating scripts for potential improvements.
def files_log_graph(self, stream): ''' Build up a graph (nodes and edges from a Bro files.log) ''' file_log = list(stream) print 'Entering file_log_graph...(%d rows)' % len(file_log) for row in file_log: # If the mime-type is interesting add the uri and the host->uri->host r...
Create a Python 3 function for building a graph of nodes and edges from a Bro files. log file stream.
You are a Python code generator, capable of creating scripts from specifications.
Execute the URL worker
Make a summary of the following Python 3 code def execute(self, input_data): ''' Execute the URL worker ''' string_output = input_data['strings']['string_list'] flatten = ' '.join(string_output) urls = self.url_match.findall(flatten) return {'url_list': urls}
You are a Python code architect, reviewing and designing scalable and efficient code
Recursively ist all files under a directory
Can you generate the documentation for the following Python 3 function def all_files_in_directory(path): file_list = [] for dirname, dirnames, filenames in os.walk(path): for filename in filenames: file_list.append(os.path.join(dirname, filename)) return file_list
As a Python code translator, you convert algorithms and pseudocode into Python.
Load all the plugins in the plugin directory
How would you explain what the following Python 3 function does def load_all_plugins(self): # Go through the existing python files in the plugin directory self.plugin_path = os.path.realpath(self.plugin_dir) sys.path.append(self.plugin_dir) print '<<< Plugin Manager >>>' for f i...
As a Python code composer, you craft elegant and concise scripts.
def remove_plugin(self, f): """Remvoing a deleted plugin. Args: f: the filepath for the plugin. """ if f.endswith('.py'): plugin_name = os.path.splitext(os.path.basename(f))[0] print '- %s %sREMOVED' % (plugin_name, color.Red) print '\t%sN...
Write a Python 3 function for removing a deleted plugin.
As a Python code translator, you convert algorithms and pseudocode into Python.
def add_plugin(self, f): """Adding and verifying plugin. Args: f: the filepath for the plugin. """ if f.endswith('.py'): # Just the basename without extension plugin_name = os.path.splitext(os.path.basename(f))[0] # It's possible the plu...
Create a Python 3 function for adding and verifying a plugin.
As a Python code composer, you craft elegant and concise scripts.
Validate the plugin, each plugin must have the following: 1) The worker class must have an execute method: execute(self, input_data). 2) The worker class must have a dependencies list (even if it's empty). 3) The file must have a top level test() method. Args: ha...
Make a summary of the following Python 3 code def validate(self, handler): # Check for the test method first test_method = self.plugin_test_validation(handler) if not test_method: return None # Here we iterate through the classes found in the module and pick # the f...
You are a Python code generator, capable of creating scripts from specifications.
Store a sample into the datastore.
Can you generate a brief explanation for the following Python 3 code def store_sample(self, sample_bytes, filename, type_tag): # Temp sanity check for old clients if len(filename) > 1000: print 'switched bytes/filename... %s %s' % (sample_bytes[:100], filename[:100]) exit(1) ...
You are a Python code analyst, evaluating scripts for potential improvements.
def sample_storage_size(self): """Get the storage size of the samples storage collection.""" try: coll_stats = self.database.command('collStats', 'fs.chunks') sample_storage_size = coll_stats['size']/1024.0/1024.0 return sample_storage_size except pymongo.err...
Create a Python 3 function for getting the storage size of the samples storage collection.
As a Python code composer, you craft elegant and concise scripts.
Expire data within the samples collection.
Can you generate the documentation for the following Python 3 function def expire_data(self): # Do we need to start deleting stuff? while self.sample_storage_size() > self.samples_cap: # This should return the 'oldest' record in samples record = self.database[self.sample_collec...
As a python code expert, you are capable of creating scripts from specifications.
Delete a specific sample from the database
Make a summary of the following Python 3 code def remove_sample(self, md5): # Grab the sample record = self.database[self.sample_collection].find_one({'md5': md5}) if not record: return # Delete it print 'Deleting sample: %s (%.2f MB)...' % (record['md5'], record['l...
You are a Python code architect, reviewing and designing scalable and efficient code
def clean_for_serialization(self, data): """Clean data in preparation for serialization. Deletes items having key either a BSON, datetime, dict or a list instance, or starting with __. Args: data: Sample data to be serialized. Returns: Cleaned data dict...
Implement a function in Python 3 to clean data in preparation for serialization.
As a python code expert, you are capable of creating scripts from specifications.
def clean_for_storage(self, data): """Clean data in preparation for storage. Deletes items with key having a '.' or is '_id'. Also deletes those items whose value is a dictionary or a list. Args: data: Sample data dictionary to be cleaned. Returns: Clea...
Write a Python 3 script for cleaning data in preparation for storage.
As a Python code analyst, you investigate and solve complex coding mysteries
def get_full_md5(self, partial_md5, collection): """Support partial/short md5s, return the full md5 with this method""" print 'Notice: Performing slow md5 search...' starts_with = '%s.*' % partial_md5 sample_info = self.database[collection].find_one({'md5': {'$regex' : starts_with}},{'md...
Write a Python 3 script to support partial md5s return the full md5 with this method
You are a Python code analyst, evaluating scripts for potential improvements.
Get the sample from the data store.
Make a summary of the following Python 3 code def get_sample(self, md5): # Support 'short' md5s but don't waste performance if the full md5 is provided if len(md5) < 32: md5 = self.get_full_md5(md5, self.sample_collection) # Grab the sample sample_info = self.database[self....
As a python code expert, you are capable of creating scripts from specifications.
Get a window of samples of type type_tag not to exceed size.
Can you generate the documentation for the following Python 3 function def get_sample_window(self, type_tag, size=10): # Convert size to MB size = size * 1024 * 1024 # Grab all the samples of type=type_tag, sort by import_time (newest to oldest) cursor = self.database[self.sample_colle...
As a python code expert, you are capable of creating scripts from specifications.
Checks if the data store has this sample with the given md5.
Given the following Python 3 function, write the documentation def has_sample(self, md5): # The easiest thing is to simply get the sample and if that # succeeds than return True, else return False sample = self.get_sample(md5) return True if sample else False
As a Python code analyst, you investigate and solve complex coding mysteries
List all samples that meet the predicate or all.
Explain what the following Python 3 code does def _list_samples(self, predicate=None): cursor = self.database[self.sample_collection].find(predicate, {'_id':0, 'md5':1}) return [item['md5'] for item in cursor]
As a Python code analyst, you investigate and solve complex coding mysteries
def tag_match(self, tags=None): """List all samples that match the tags or all if tags are not specified. Args: tags: Match samples against these tags (or all if not specified) Returns: List of the md5s for the matching samples """ if 'tags' not in self....
Write a Python 3 script for listing all samples that match the tags or all if tags are not specified.
You are a Python code architect, reviewing and designing scalable and efficient code
Returns a list of the tags and md5s for all samples
Can you tell what is the following Python 3 function doing def tags_all(self): if 'tags' not in self.database.collection_names(): print 'Warning: Searching on non-existance tags collection' return None cursor = self.database['tags'].find({}, {'_id':0, 'md5':1, 'tags':1}) ...
As a python code expert, you are capable of creating scripts from specifications.
Store the results of the worker in the database.
Explain what the following Python 3 code does def store_work_results(self, results, collection, md5): # Make sure the md5 and time stamp is on the data before storing results['md5'] = md5 results['__time_stamp'] = datetime.datetime.utcnow() # If the data doesn't have a 'mod_time' field...
You are a Python code architect, reviewing and designing scalable and efficient code
Return a list of all md5s matching the type_tag.
Can you generate a brief explanation for the following Python 3 code def all_sample_md5s(self, type_tag=None): if type_tag: cursor = self.database[self.sample_collection].find({'type_tag': type_tag}, {'md5': 1, '_id': 0}) else: cursor = self.database[self.sample_collection].find...
As a python code expert, you are capable of creating scripts from specifications.
Removes all of the worker output collections
Can you generate the documentation for the following Python 3 function def clear_worker_output(self): print 'Dropping all of the worker output collections... Whee!' # Get all the collections in the workbench database all_c = self.database.collection_names() # Remove collections...
You are a Python code architect, reviewing and designing scalable and efficient code
Run periodic operations on the data store.
Explain what the following Python 3 code does def periodic_ops(self): # Only run every 30 seconds if (time.time() - self.last_ops_run) < 30: return try: # Reset last ops run self.last_ops_run = time.time() print 'Running Periodic Ops' ...
You are a Python code architect, reviewing and designing scalable and efficient code
Convert an elementary datatype to unicode.
Can you generate the documentation for the following Python 3 function def to_unicode(self, s): # Fixme: This is total horseshit if isinstance(s, unicode): return s if isinstance(s, str): return unicode(s, errors='ignore') # Just return the original object ...
You are a Python code generator, capable of creating scripts from specifications.
Execute the SWF command.
Make a summary of the following Python 3 code def execute(self, input_data): # Spin up SWF class swf = SWF() # Get the raw_bytes raw_bytes = input_data['sample']['raw_bytes'] # Parse it swf.parse(StringIO(raw_bytes)) # Header info ...
You are a Python code architect, reviewing and designing scalable and efficient code
Grab server info from command line
Here you have a function in Python 3, explain what it does def grab_server_args(): workbench_conf = ConfigParser.ConfigParser() config_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'config.ini') workbench_conf.read(config_path) server = workbench_conf.get('workbench', 'server_uri...
You are a Python code architect, reviewing and designing scalable and efficient code
Returns a dict of email. attachments item formatted for sending with Mailjet
Here you have a function in Python 3, explain what it does def _make_attachment(self, attachment, str_encoding=None): is_inline_image = False if isinstance(attachment, MIMEBase): name = attachment.get_filename() content = attachment.get_payload(decode=True) mimetype =...
You are a Python code generator, capable of creating scripts from specifications.
Take an arbitrary dictionary of data and index it with ELS.
Given the following Python 3 function, write the documentation def index_data(self, data, index_name, doc_type): # Index the data (which needs to be a dict/object) if it's not # we're going to toss an exception if not isinstance(data, dict): raise RuntimeError('Index failed, data ne...
You are a Python code generator, capable of creating scripts from specifications.
def search(self, index_name, query): """Search the given index_name with the given ELS query. Args: index_name: Name of the Index query: The string to be searched. Returns: List of results. Raises: RuntimeError: When the search query fai...
Write a Python 3 function that can search the given index with the given ELS query.
As a Python code analyst, you investigate and solve complex coding mysteries
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)
Create a Python 3 function for indexing data in Stub Indexer.
As a python code expert, you are capable of creating scripts from specifications.
Execute method of the cluster_cache_get_cluster_entry method
How would you explain what the following Python 3 function does def execute(self, input_data): ''' Execute method ''' my_ssdeep = input_data['meta_deep']['ssdeep'] my_md5 = input_data['meta_deep']['md5'] # For every PE sample in the database compute my ssdeep fuzzy match sample_...
As a python code expert, you are capable of creating scripts from specifications.
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'], co...
Write a Python 3 function that can execute the help_formatter command
You are a Python code generator, capable of creating scripts from specifications.
Run the workbench server
Here you have a function in Python 3, explain what it does def run(): # 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...
As a python code expert, you are capable of creating scripts from specifications.
Store a sample into the DataStore.
Can you generate a brief explanation for the following Python 3 code def store_sample(self, input_bytes, filename, type_tag): # If the sample comes in with an unknown type_tag try to determine it if type_tag == 'unknown': print 'Info: Unknown File -- Trying to Determine Type...' ...
You are a Python code generator, capable of creating scripts from specifications.