output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Executes an action on a device and returns the results of the action.
Can you tell what is the following Python 3 function doing def execute(self, uri, namespace, action, timeout=2, **kwargs): if not uri: raise ValueError("No action URI has been defined.") if not namespace: raise ValueError("No namespace has been defined.") if not action...
As a Python code translator, you convert algorithms and pseudocode into Python.
def _extractErrorString(request): """Extract error string from a failed UPnP call. :param request: the failed request result :type request: requests.Response :return: an extracted error text or empty str :rtype: str """ errorStr = "" tag = None ...
Write a Python 3 function for extracting an error string from a failed UPnP call.
You are a Python code generator, capable of creating scripts from specifications.
Setup actions for known devices.
Can you generate a brief explanation for the following Python 3 code def setupTR64Device(self, deviceType): if deviceType.lower() != "fritz.box": raise ValueError("Unknown device type given.") self.__deviceServiceDefinitions = {} self.__deviceXMLInitialized = False # Fritz...
As a Python code composer, you craft elegant and concise scripts.
Loads the device definitions from a given URL which points to the root XML in the device.
Here you have a function in Python 3, explain what it does def loadDeviceDefinitions(self, urlOfXMLDefinition, timeout=3): # setup proxies proxies = {} if self.__httpsProxy: proxies = {"https": self.__httpsProxy} if self.__httpProxy: proxies = {"http": self.__ht...
You are a Python code generator, capable of creating scripts from specifications.
This method is used to iterate through the device definition XML tree and populate the object with the information from the device information.
Can you tell what is the following Python 3 function doing def _iterateToFindSCPDElements(self, element, baseURIPath): for child in element.getchildren(): tagName = child.tag.lower() if tagName.endswith('servicelist'): self._processServiceList(child,baseURIPath) ...
You are a Python code analyst, evaluating scripts for potential improvements.
Load the SCPD for a given service type.
Can you generate a brief explanation for the following Python 3 code def loadSCPD(self, serviceType=None, timeout=3, ignoreFailures=False): if serviceType is not None: self._loadSCPD(serviceType, float(timeout)) else: self.__deviceSCPD = {} for serviceType in self.__...
As a Python code translator, you convert algorithms and pseudocode into Python.
Internal method to parse the SCPD definitions.
Can you generate the documentation for the following Python 3 function def _parseSCPDActions(self, actionListElement, actions, variableParameterDict): # go through all action elements in this list for actionElement in actionListElement.getchildren(): action = {} # go through a...
As a Python code composer, you craft elegant and concise scripts.
Internal method to parse the variable types in the SCPD definitions.
Given the following Python 3 function, write the documentation def _parseSCPDVariableTypes(self, variableListElement, variableTypes): # iterate through all variables for variableElement in variableListElement.getchildren(): variable = {} # iterate through the variable definiti...
You are a Python code generator, capable of creating scripts from specifications.
Factory method to create a Wifi object from an XML device definition.
Explain what the following Python 3 code does def createFromURL(urlOfXMLDefinition): url = urlparse(urlOfXMLDefinition) if not url.port: if url.scheme.lower() == "https": port = 443 else: port = 80 else: port = url.port ...
As a Python code composer, you craft elegant and concise scripts.
Execute GetInfo action to get Wifi basic information s.
Given the following Python 3 function, write the documentation def getWifiInfo(self, wifiInterfaceId=1, timeout=1): namespace = Wifi.getServiceType("getWifiInfo") + str(wifiInterfaceId) uri = self.getControlURL(namespace) results = self.execute(uri, namespace, "GetInfo", timeout=timeout) ...
As a Python code composer, you craft elegant and concise scripts.
def getTotalAssociations(self, wifiInterfaceId=1, timeout=1): """Execute GetTotalAssociations action to get the amount of associated Wifi clients. :param int wifiInterfaceId: the id of the Wifi interface :param float timeout: the timeout to wait for the action to be executed :return: th...
Can you write a function in Python 3 where it executes GetTotalAssociations action to get the amount of associated Wifi clients.
You are a Python code analyst, evaluating scripts for potential improvements.
def getGenericAssociatedDeviceInfo(self, index, wifiInterfaceId=1, timeout=1): """Execute GetGenericAssociatedDeviceInfo action to get detailed information about a Wifi client. :param int index: the number of the client :param int wifiInterfaceId: the id of the Wifi interface :param flo...
Implement a Python 3 function for executing GetGenericAssociatedDeviceInfo action to get detailed information about a Wifi client.
As a python code expert, you are capable of creating scripts from specifications.
def getSpecificAssociatedDeviceInfo(self, macAddress, wifiInterfaceId=1, timeout=1): """Execute GetSpecificAssociatedDeviceInfo action to get detailed information about a Wifi client. :param str macAddress: MAC address in the form ``38:C9:86:26:7E:38``; be aware that the MAC address might b...
Write a Python 3 script to execute GetSpecificAssociatedDeviceInfo action to get detailed information about a Wifi client.
As a python code expert, you are capable of creating scripts from specifications.
def setEnable(self, status, wifiInterfaceId=1, timeout=1): """Set enable status for a Wifi interface, be careful you don't cut yourself off. :param bool status: enable or disable the interface :param int wifiInterfaceId: the id of the Wifi interface :param float timeout: the timeout to ...
Create a Python 3 function to set enable status for a Wifi interface.
As a Python code analyst, you investigate and solve complex coding mysteries
def setChannel(self, channel, wifiInterfaceId=1, timeout=1): """Set the channel of this Wifi interface :param int channel: the channel number :param int wifiInterfaceId: the id of the Wifi interface :param float timeout: the timeout to wait for the action to be executed """ ...
Write a Python 3 script to set the channel of this Wifi interface
As a Python code composer, you craft elegant and concise scripts.
Set the SSID of the Wifi network
Can you generate a brief explanation for the following Python 3 code def setSSID(self, ssid, wifiInterfaceId=1, timeout=1): namespace = Wifi.getServiceType("setChannel") + str(wifiInterfaceId) uri = self.getControlURL(namespace) self.execute(uri, namespace, "SetChannel", timeout=timeout, NewSSI...
You are a Python code architect, reviewing and designing scalable and efficient code
def enabled_checker(func): """ Access decorator which checks if a RPC method is enabled by our configuration """ @wraps(func) def wrap(self, *args, **kwargs): if self.allowed_methods and isinstance(self.allowed_methods, list) and func.__name__ not in self.allowed_methods: ...
How would you implement a function in Python 3 that accesses decorator which checks if a RPC method is enabled by our configuration
As a Python code translator, you convert algorithms and pseudocode into Python.
List all available presets.
Can you generate a brief explanation for the following Python 3 code async def list_presets(self): presets = await self.request.app.vmshepherd.preset_manager.list_presets() return list(presets.keys())
You are a Python code architect, reviewing and designing scalable and efficient code
List virtual machines in a given preset
How would you explain what the following Python 3 function does async def list_vms(self, preset): vmshepherd = self.request.app.vmshepherd preset = vmshepherd.preset_manager.get_preset(preset) result_vms = {vm.id: {'ip': vm.ip[0], 'state': vm.state.value} for vm in preset.vms} return pre...
As a python code expert, you are capable of creating scripts from specifications.
Discard vm in specified preset
Can you tell what is the following Python 3 function doing async def terminate_vm(self, preset, vm_id): vmshepherd = self.request.app.vmshepherd preset = vmshepherd.preset_manager.get_preset(preset) await preset.iaas.terminate_vm(vm_id) return 'OK'
You are a Python code analyst, evaluating scripts for potential improvements.
async def get_vm_metadata(self, preset, vm_id): """ Get vm metadata :arg string preset: preset name :arg int vm_id: Virtual Machine id :return: Metadata for Virtual Machine :rtype: dict Sample response: ``{ 'time_shutdown' : "12312312321' }`` """ ...
Create a Python 3 function to get VM metadata for a given VM
You are a Python code analyst, evaluating scripts for potential improvements.
Convert URL - like and email - like strings into links.
Here you have a function in Python 3, explain what it does def linkify(text, attrs={}): def separate_parentheses(s): start = re_find(r'^\(*', s) end = re_find(r'\)*$', s) n = min(len(start), len(end)) if n: return s[:n], s[n:-n], s[-n:] else: return ''...
You are a Python code architect, reviewing and designing scalable and efficient code
def force_unicode(s, encoding='utf-8', errors='strict'): """ Similar to smart_text, except that lazy instances are resolved to strings, rather than kept as lazy objects. """ # Handle the common case first, saves 30-40% when s is an instance of # six.text_type. This function gets called often in ...
Write a Python 3 function for forcing unicode string s to be unicode.
As a Python code analyst, you investigate and solve complex coding mysteries
Save dictionary to HDF5 file.
Explain what the following Python 3 code does def save_dict_to_hdf5(dic, filename): with h5py.File(filename, 'w') as h5file: rf = recursively_save_dict_contents_to_group(h5file, '/', dic) h5_rf = h5file.create_group("_reconstruction_flags") # h5_rf = h5file.create_group("_reconstruction_key_...
As a Python code translator, you convert algorithms and pseudocode into Python.
Recursively loads the contents of a group into a single dict.
Make a summary of the following Python 3 code def recursively_load_dict_contents_from_group(h5file, path): rf = h5file["_reconstruction_flags"] # rkf = h5file["_reconstruction_key_flags"] ans = {} for key, item in h5file[path].items(): dest_key = key # if key in ("_reconstruction_flags",...
You are a Python code analyst, evaluating scripts for potential improvements.
Parse the arguments for the command line
Can you generate a brief explanation for the following Python 3 code def parse_args(*args): parser = argparse.ArgumentParser( description="Send push notifications for a feed") parser.add_argument('--version', action='version', version="%(prog)s " + __version__.__version__) ...
As a python code expert, you are capable of creating scripts from specifications.
def get_environments(self, project_key: str) -> dict: """ Retrieve all environments for a given project. Includes name, key, and mobile key. :param project_key: Key for project. :returns: dictionary of environments. """ try: resp = self.client.get_p...
Write a Python 3 script for retrieving all environments for a given project.
You are a Python code architect, reviewing and designing scalable and efficient code
def update_flag(self, state: str, feature_key: str) \ -> launchdarkly_api.FeatureFlag: """ Update the flag status for the specified feature flag. :param state: New feature flag state :param featureKey: Feature flag key :returns: FeatureFlag object. """ b...
Can you implement a function in Python 3 that updates the status of a feature flag.
You are a Python code architect, reviewing and designing scalable and efficient code
Generates code for calling the stored routine in the wrapper method.
Given the following Python 3 function, write the documentation def _write_result_handler(self, routine): self._write_line('ret = {}') self._write_execute_rows(routine) self._write_line('for row in rows:') num_of_dict = len(routine['columns']) i = 0 while i < num_of_dict...
As a Python code composer, you craft elegant and concise scripts.
Logs the query on the console.
Explain what the following Python 3 code does def _log_query(query): query = query.strip() if os.linesep in query: # Query is a multi line query MetadataDataLayer.io.log_very_verbose('Executing query:') MetadataDataLayer.io.log_very_verbose('<sql>{0}</sql>'.format(qu...
You are a Python code generator, capable of creating scripts from specifications.
send a public key to request a token
Can you generate the documentation for the following Python 3 function def request_token(self, board): '''send a public key to request a token. When we call this function, we already have an RSA key at self.key board: the discourse board to post to ''' nonce = str(uuid.uuid4()) data = {'...
You are a Python code analyst, evaluating scripts for potential improvements.
def create_post(self, title, body, board, category, username): '''create a Discourse post, given a title, body, board, and token. Parameters ========== title: the issue title body: the issue body board: the discourse board to post to ''' category_url = "%s/categories.js...
Write a Python 3 script to create a Discourse post given a title body board and token.
You are a Python code generator, capable of creating scripts from specifications.
Load the stored routines into the current schema.
Can you generate a brief explanation for the following Python 3 code def main(self, config_filename, file_names=None): self._io.title('Loader') if file_names: self.__load_list(config_filename, file_names) else: self.__load_all(config_filename) if self.error_file...
You are a Python code architect, reviewing and designing scalable and efficient code
Log information about stored routines that were not loaded successfully.
Can you tell what is the following Python 3 function doing def __log_overview_errors(self): if self.error_file_names: self._io.warning('Routines in the files below are not loaded:') self._io.listing(sorted(self.error_file_names))
You are a Python code analyst, evaluating scripts for potential improvements.
def _add_replace_pair(self, name, value, quote): """ Adds a replace part to the map of replace pairs. :param name: The name of the replace pair. :param value: The value of value of the replace pair. """ key = '@' + name + '@' key = key.lower() class_name...
How would you code a function in Python 3 to add a replace part to the map of replace pairs.
You are a Python code generator, capable of creating scripts from specifications.
Loads all stored routines in a list into the RDBMS instance.
Explain what the following Python 3 code does def __load_list(self, config_filename, file_names): self._read_configuration_file(config_filename) self.connect() self.find_source_files_from_list(file_names) self._get_column_type() self.__read_stored_routine_metadata() self....
You are a Python code generator, capable of creating scripts from specifications.
def __load_all(self, config_filename): """ Loads all stored routines into the RDBMS instance. :param str config_filename: string The filename of the configuration file. """ self._read_configuration_file(config_filename) self.connect() self.__find_source_files() ...
How would you implement a function in Python 3 that loads all stored routines into the RDBMS instance.
As a Python code translator, you convert algorithms and pseudocode into Python.
def _read_configuration_file(self, config_filename): """ Reads parameters from the configuration file. :param str config_filename: The name of the configuration file. """ config = configparser.ConfigParser() config.read(config_filename) self._source_directory = ...
Write a Python 3 function for reading the parameters from the configuration file.
You are a Python code generator, capable of creating scripts from specifications.
Searches recursively for all source files in a directory and adds them to the internal list of error files.
Make a summary of the following Python 3 code def __find_source_files(self): for dir_path, _, files in os.walk(self._source_directory): for name in files: if name.lower().endswith(self._source_file_extension): basename = os.path.splitext(os.path.basename(name))[0]...
As a Python code composer, you craft elegant and concise scripts.
Reads the metadata of stored routines from the metadata file.
Can you tell what is the following Python 3 function doing def __read_stored_routine_metadata(self): if os.path.isfile(self._pystratum_metadata_filename): with open(self._pystratum_metadata_filename, 'r') as file: self._pystratum_metadata = json.load(file)
As a Python code translator, you convert algorithms and pseudocode into Python.
def __load_stored_routines(self): """ Loads all stored routines into the RDBMS instance. """ self._io.writeln('') for routine_name in sorted(self._source_file_names): if routine_name in self._pystratum_metadata: old_metadata = self._pystratum_metadata...
Create a Python 3 function to load all stored routines into the RDBMS instance.
As a python code expert, you are capable of creating scripts from specifications.
def __remove_obsolete_metadata(self): """ Removes obsolete entries from the metadata of all stored routines. """ clean = {} for key, _ in self._source_file_names.items(): if key in self._pystratum_metadata: clean[key] = self._pystratum_metadata[key] ...
Write a Python 3 function that can remove obsolete entries from the metadata of all stored routines.
As a Python code translator, you convert algorithms and pseudocode into Python.
Writes the metadata of all stored routines to the metadata file.
Can you generate the documentation for the following Python 3 function def __write_stored_routine_metadata(self): with open(self._pystratum_metadata_filename, 'w') as stream: json.dump(self._pystratum_metadata, stream, indent=4, sort_keys=True)
You are a Python code analyst, evaluating scripts for potential improvements.
def find_source_files_from_list(self, file_names): """ Finds all source files that actually exists from a list of file names. :param list[str] file_names: The list of file names. """ for file_name in file_names: if os.path.exists(file_name): routine_n...
Implement a Python 3 function for finding all source files that actually exists from a list of file names.
As a Python code composer, you craft elegant and concise scripts.
Gets the constants from the class that acts like a namespace for constants and adds them to the replace pairs.
Can you generate the documentation for the following Python 3 function def __get_constants(self): helper = ConstantClass(self._constants_class_name, self._io) helper.reload() constants = helper.constants() for name, value in constants.items(): self._add_replace_pair(name, va...
As a Python code composer, you craft elegant and concise scripts.
Initialize a new logger object.
Can you generate a brief explanation for the following Python 3 code def init_logger( name="", handler_path_levels=None, level=logging.INFO, formatter=None, formatter_str=None, datefmt="%Y-%m-%d %H:%M:%S", ): """Add a default handler for logger. Args: name = '' or logger obj. ...
You are a Python code analyst, evaluating scripts for potential improvements.
Simple print use logger print with time and file line number.
Can you tell what is the following Python 3 function doing def print_info(*messages, **kwargs): sep = kwargs.pop("sep", " ") frame = sys._getframe(1) ln = frame.f_lineno _file = frame.f_globals.get("__file__", "") fn = os.path.split(_file)[-1] return print_logger.info( sep.join(map(unico...
You are a Python code analyst, evaluating scripts for potential improvements.
def get_fields(model): """ Returns a Model's knockout_fields, or the default set of field names. """ try: if hasattr(model, "knockout_fields"): fields = model.knockout_fields() else: try: fields = model_to_dict(model).keys() except...
Write a Python 3 script to return a list of field names for a Knockout model.
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_object_data(obj, fields, safe): """ Given an object and a list of fields, recursively build an object for serialization. Returns a dictionary. """ temp_dict = dict() for field in fields: try: attribute = getattr(obj, str(field)) if isinstance(attribute,...
Can you write a function in Python 3 where it gives an object and a list of fields recursively build an object for serialization.
As a python code expert, you are capable of creating scripts from specifications.
def ko_model(model, field_names=None, data=None): """ Given a model, returns the Knockout Model and the Knockout ViewModel. Takes optional field names and data. """ try: if isinstance(model, str): modelName = model else: modelName = model.__class__.__name__ ...
How would you implement a function in Python 3 that returns the Knockout Model and Knockout ViewModel.
You are a Python code analyst, evaluating scripts for potential improvements.
def ko_bindings(model): """ Given a model, returns the Knockout data bindings. """ try: if isinstance(model, str): modelName = model else: modelName = model.__class__.__name__ modelBindingsString = "ko.applyBindings(new " + modelName + "ViewModel(), $('#...
Create a Python 3 function to return the Knockout data bindings for a given model
As a Python code composer, you craft elegant and concise scripts.
def ko_json(queryset, field_names=None, name=None, safe=False): """ Given a QuerySet, return just the serialized representation based on the knockout_fields. Useful for middleware/APIs. Convenience method around ko_data. """ return ko_data(queryset, field_names, name, safe, return_json=True)
Implement a Python 3 function for giving a QuerySet return just the serialized representation of the Knockout object.
You are a Python code architect, reviewing and designing scalable and efficient code
def ko_data(queryset, field_names=None, name=None, safe=False, return_json=False): """ Given a QuerySet, return just the serialized representation based on the knockout_fields as JavaScript. """ try: try: # Get an inital instance of the QS. queryset_instance = query...
Write a Python 3 function for giving a QuerySet return just the serialized representation of the knockout_fields as JavaScript.
As a Python code analyst, you investigate and solve complex coding mysteries
Converts a Django QuerySet into a complete Knockout implementation.
Here you have a function in Python 3, explain what it does def ko(queryset, field_names=None): try: koDataString = ko_data(queryset, field_names) koModelString = ko_model(queryset[0].__class__.__name__, field_names, data=True) koBindingsString = ko_bindings(queryset[0]) koString = ...
As a Python code translator, you convert algorithms and pseudocode into Python.
load a keypair from a keypair file
How would you explain what the following Python 3 function does def load_keypair(keypair_file): '''load a keypair from a keypair file. We add attributes key (the raw key) and public_key (the url prepared public key) to the client. Parameters ========== keypair_file: the pem file to load...
You are a Python code analyst, evaluating scripts for potential improvements.
def __message(expected_row_count, actual_row_count, query): """ Composes the exception message. :param str expected_row_count: The expected row count. :param int actual_row_count: The actual row count. :param str query: The query. :rtype: str """ query =...
How would you code a function in Python 3 to return a string that can be used to construct the exception message.
As a Python code translator, you convert algorithms and pseudocode into Python.
def _submit(self): '''submit the issue to github. When we get here we should have: {'user_prompt_issue': 'I want to do the thing.', 'user_prompt_repo': 'vsoch/hello-world', 'user_prompt_title': 'Error with this thing', 'record_asciinema': '/tmp/helpme...
Create a Python 3 function for submitting the issue to github.
As a Python code analyst, you investigate and solve complex coding mysteries
def resolve_refs(uri, spec): """Resolve JSON references in a given dictionary. OpenAPI spec may contain JSON references to its nodes or external sources, so any attempt to rely that there's some expected attribute in the spec may fail. So we need to resolve JSON references before we use it (i.e. re...
Implement a Python 3 function for resolving JSON references in a given OpenAPI spec.
You are a Python code analyst, evaluating scripts for potential improvements.
This is the main function for the helper. It is the main function for the helper.
Here you have a function in Python 3, explain what it does def main(args, extras): '''This is the actual driver for the helper. ''' from helpme.main import get_helper name = args.command if name in HELPME_HELPERS: # Get the helper, do the recording, submit helper = get_helper(nam...
You are a Python code analyst, evaluating scripts for potential improvements.
def extract(self, html_contents, css_contents=None, base_url=None): """ Extracts the cleaned html tree as a string and only css rules matching the cleaned html tree :param html_contents: The HTML contents to parse :type html_contents: str :param css_contents: The CSS con...
Implement a Python 3 function for extracting the cleaned html tree as a string and only css rules matching the cleaned html tree.
As a Python code composer, you craft elegant and concise scripts.
def __add(self, dest, xpath): """ Adds a Xpath expression to the dest list :param dest: The destination list to add the Xpath :type dest: list :param xpath: The Xpath expression to add :type xpath: str """ assert isinstance(xpath, string_types) de...
Implement a Python 3 function for adding a Xpath expression to the dest list
As a Python code analyst, you investigate and solve complex coding mysteries
def _write_line(self, line=None): """ Appends a line of code to the generated code and adjust the indent level of the generated code. :param line: The line of code (with out LF) that must be appended. """ if line is None: self._write("\n") if self.__inden...
Can you implement a function in Python 3 that appends a line of code to the generated code and adjusts the indent level of the generated code.
As a Python code composer, you craft elegant and concise scripts.
def _write_separator(self): """ Inserts a horizontal (commented) line tot the generated code. """ tmp = self._page_width - ((4 * self.__indent_level) + 2) self._write_line('# ' + ('-' * tmp))
Write a Python 3 script for writing a separator line at the top of the generated code.
You are a Python code architect, reviewing and designing scalable and efficient code
Returns a complete wrapper method.
Explain what the following Python 3 code does def write_routine_method(self, routine): if self._lob_as_string_flag: return self._write_routine_method_without_lob(routine) else: if self.is_lob_parameter(routine['parameters']): return self._write_routine_method_with...
You are a Python code architect, reviewing and designing scalable and efficient code
Writes the parameters part of the docstring for the wrapper method of a stored routine.
Can you generate a brief explanation for the following Python 3 code def _write_docstring_parameters(self, routine): if routine['pydoc']['parameters']: self._write_line('') for param in routine['pydoc']['parameters']: lines = param['description'].split(os.linesep) ...
You are a Python code analyst, evaluating scripts for potential improvements.
def __write_docstring_return_type(self): """ Writes the return type part of the docstring for the wrapper method of a stored routine. """ rtype = self._get_docstring_return_type() if rtype: self._write_line('') self._write_line(':rtype: {0}'.format(rtype))
How would you code a function in Python 3 to write the return type part of the docstring for the stored routine.
You are a Python code analyst, evaluating scripts for potential improvements.
def __write_docstring(self, routine): """ Writes the docstring for the wrapper method of a stored routine. :param dict routine: The metadata of the stored routine. """ self._write_line('"""') self.__write_docstring_description(routine) self._write_docstring_para...
Write a Python 3 function that can write the docstring for the wrapper method of a stored routine.
You are a Python code analyst, evaluating scripts for potential improvements.
Returns code for the parameters of the wrapper method for the stored routine.
Make a summary of the following Python 3 code def _get_wrapper_args(routine): ret = '' for parameter_info in routine['parameters']: if ret: ret += ', ' ret += parameter_info['name'] return ret
As a Python code translator, you convert algorithms and pseudocode into Python.
def generate_relay_config(self, environments: list) -> None: """Generate ld-relay.conf file. Given a list of environments of a project, this will generate a ``ld-relay.conf`` file in the current working directory. The conf file follows the specification that is documented in the main `l...
Write a Python 3 function that can generate the ld - relay. conf file.
You are a Python code architect, reviewing and designing scalable and efficient code
def __load(self): """ Loads dynamically the class that acts like a namespace for constants. """ parts = self.__class_name.split('.') module_name = ".".join(parts[:-1]) module = __import__(module_name) modules = [] for comp in parts[1:]: module ...
Implement a function in Python 3 to load dynamically the class that acts like a namespace for constants.
You are a Python code architect, reviewing and designing scalable and efficient code
Returns the constants from the class that acts like a namespace for constants.
Given the following Python 3 function, write the documentation def constants(self): ret = {} name = self.__class_name.split('.')[-1] constant_class = getattr(self.__module, name) for name, value in constant_class.__dict__.items(): if re.match(r'^[A-Z][A-Z0-9_]*$', name): ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def __extract_info(self, lines): """ Extracts the following info from the source of the module with the class that acts like a namespace for constants: * Start line with constants * Last line with constants * Indent for constants :param list[str] lines: The sourc...
Implement a Python 3 function for extracting the following info from the source of the module with the class that acts like a namespace for constants.
You are a Python code analyst, evaluating scripts for potential improvements.
def source_with_constants(self, constants): """ Returns the source of the module with the class that acts like a namespace for constants with new constants. :param dict[str,int] constants: The new constants. :rtype: str """ old_lines = self.source().split("\n") ...
Create a Python 3 function to return the source of the module with the class that acts like a namespace for constants with new constants.
As a python code expert, you are capable of creating scripts from specifications.
return the full path for the user configuration file. If doesn t exist create it.
Explain what the following Python 3 code does def get_configfile_user(): '''return the full path for the user configuration file. If doesn't exist, create it for the user. ''' from helpme.defaults import HELPME_CLIENT_SECRETS # The inital file has a funny username if not os.path.exists(HELP...
As a Python code composer, you craft elegant and concise scripts.
remove a setting from the global config file
Can you generate the documentation for the following Python 3 function def _remove_setting(section, name, configfile, save=False): '''remove a setting from the global config ''' removed = False config = _load_config(configfile) if section in config: if name.lower() in config[section]: ...
As a Python code analyst, you investigate and solve complex coding mysteries
remove a setting from the global config
Can you generate a brief explanation for the following Python 3 code def remove_setting(self, section, name, save=False): '''remove a setting from the global config ''' configfile = get_configfile() return _remove_setting(section, name, configfile, save)
As a Python code translator, you convert algorithms and pseudocode into Python.
remove a setting from the user config
Can you generate the documentation for the following Python 3 function def remove_user_setting(self, section, name, save=False): '''remove a setting from the user config ''' configfile = get_configfile_user() return _remove_setting(section, name, configfile, save)
You are a Python code architect, reviewing and designing scalable and efficient code
def load_envars(self, items): '''load a tuple of environment variables, to add to the user settings Example: items = [('HELPME_DISCOURSE_BOARD', 'user_prompt_board'), ('HELPME_DISCOURSE_CATEGORY', 'user_prompt_category')] # Note that it's added to the client with an ...
Implement a function in Python 3 to load a tuple of environment variables to add to the user settings
As a python code expert, you are capable of creating scripts from specifications.
def get_setting(self, name, section=None, default=None, user=True): '''return a setting from the environment (first priority) and then secrets (second priority) if one can be found. If not, return None. Parameters ========== section: the section in the config, defaults to self.name ...
Implement a Python 3 function for returning a setting from the environment then secrets file or main config.
As a Python code composer, you craft elegant and concise scripts.
def get_settings(self): '''get all settings for a client, if defined in config. ''' config = self._load_config_user() if self.name in config: return config[self.name]
Create a Python 3 function to get all settings for a client
You are a Python code analyst, evaluating scripts for potential improvements.
def update_settings(self, updates, config=None): '''update client secrets will update the data structure for a particular authentication. This should only be used for a (quasi permanent) token or similar. The secrets file, if found, is updated and saved by default. Parameters ==========...
Write a Python 3 function for updating client secrets will update the data structure for a particular token authentication.
As a Python code analyst, you investigate and solve complex coding mysteries
Look for a setting in the environment and then update the client secrets with the new values.
Can you generate the documentation for the following Python 3 function def get_and_update_setting(self, name, default=None, user=True): '''Look for a setting in the environment (first priority) and then the settings file (second). If something is found, the settings file is updated. The order of opera...
As a Python code analyst, you investigate and solve complex coding mysteries
Run commands in a plain django environment
Make a summary of the following Python 3 code def run(app, argv=sys.argv, extra_args=None): if app not in argv[:2]: # app is automatically added if not present argv.insert(1, app) if len(argv) < 3 and 'test' not in argv[:2]: # test argument is given if not argument is passed argv...
You are a Python code generator, capable of creating scripts from specifications.
def cms(app, argv=sys.argv, extra_args=None): """ Run commands in a django cMS environment :param app: application :param argv: arguments (default to sys.argv) :param extra_args: list of extra arguments """ try: import cms # NOQA # nopyflakes except ImportError: print(...
Implement a Python 3 function for running commands in a django CMS environment
You are a Python code generator, capable of creating scripts from specifications.
Setup the Django environment and return the environment settings.
Can you generate the documentation for the following Python 3 function def setup(app, helper_module, extra_args=None, use_cms=False): helper = helper_module.__file__ argv = [os.path.basename(helper), app, 'setup', '--extra-settings={0}'.format(helper)] if use_cms: argv.append('--cms') if extra_a...
You are a Python code architect, reviewing and designing scalable and efficient code
def parse(self): """ Returns a cleaned lxml ElementTree :returns: Whether the cleaned HTML has matches or not :rtype: bool """ # Create the element tree self.tree = self._build_tree(self.html_contents) # Get explicits elements to keep and discard ...
Write a Python 3 script for parsing the HTML and returns a cleaned lxml ElementTree with the elements removed.
As a Python code analyst, you investigate and solve complex coding mysteries
Converts relative links from html contents to absolute links
Make a summary of the following Python 3 code def rel_to_abs(self, base_url): # Delete target attributes strip_attributes(self.tree, 'target') # Absolute links self.tree.rewrite_links( lambda link: urljoin(base_url, link) if not link.startswith(self.rel_to_abs_ex...
You are a Python code analyst, evaluating scripts for potential improvements.
def _get_elements(self, source): """ Returns the list of HtmlElements for the source :param source: The source list to parse :type source: list :returns: A list of HtmlElements :rtype: list """ return list(chain(*[self.tree.xpath(xpath) for xpath in sourc...
Create a Python 3 function to return the list of HtmlElements for the source
You are a Python code architect, reviewing and designing scalable and efficient code
Parses an element recursively and returns a list of all the related elements.
Can you tell what is the following Python 3 function doing def _parse_element(self, elt, parent_is_keep=False): for e in elt.iterchildren(): is_discard_element = self._is_discard(e) is_keep_element = self._is_keep(e) # Element is an explicit one to discard, flag it and cont...
As a Python code composer, you craft elegant and concise scripts.
def _has_keep_elt_in_descendants(self, elt): """ Returns whether the element has a descendant to keep or not :param elt: The HtmlElement to check :type elt: lxml.html.HtmlElement :returns: True if the element has a keep element in its descendants :rtype: bool """...
Can you implement a function in Python 3 that returns whether the element has a descendant to keep or not
As a Python code translator, you convert algorithms and pseudocode into Python.
def _remove_elements(self, elts_to_remove): """ Removes flagged elements from the ElementTree """ for e in elts_to_remove: # Get the element parent parent = e.getparent() # lxml also remove the element tail, preserve it if e.tail and e.ta...
Can you create a Python 3 function that removes flagged elements from the ElementTree.
As a Python code analyst, you investigate and solve complex coding mysteries
Execute GetInfo action to get information about the System on the device.
How would you explain what the following Python 3 function does def getSystemInfo(self, timeout=1): namespace = System.getServiceType("getSystemInfo") uri = self.getControlURL(namespace) results = self.execute(uri, namespace, "GetInfo", timeout=timeout) return SystemInfo(results)
As a Python code translator, you convert algorithms and pseudocode into Python.
Execute GetInfo action to get information about the time on the device.
Can you generate a brief explanation for the following Python 3 code def getTimeInfo(self, timeout=1): namespace = System.getServiceType("getTimeInfo") uri = self.getControlURL(namespace) results = self.execute(uri, namespace, "GetInfo", timeout=timeout) return TimeInfo(results)
You are a Python code architect, reviewing and designing scalable and efficient code
def softwareUpdateAvailable(self, timeout=1): """Returns if a software update is available :return: if a software update is available :rtype: bool """ namespace = System.getServiceType("softwareUpdateAvailable") uri = self.getControlURL(namespace) results = self...
Write a Python 3 function for returning if a software update is available for this service.
You are a Python code architect, reviewing and designing scalable and efficient code
Make the cache control headers based on a previous request s response headers
Can you generate a brief explanation for the following Python 3 code def make_headers(headers): out = {} if 'etag' in headers: out['if-none-match'] = headers['etag'] if 'last-modified' in headers: out['if-modified-since'] = headers['last-modified'] return out
You are a Python code generator, capable of creating scripts from specifications.
Get the cached object for a given url.
Given the following Python 3 function, write the documentation def get(self, prefix, url, schema_version=None): if not self.cache_dir: return None filename = self._get_cache_file(prefix, url) try: with open(filename, 'rb') as file: item = pickle.load(fil...
As a Python code composer, you craft elegant and concise scripts.
Add an object into the cache
Can you tell what is the following Python 3 function doing def set(self, prefix, url, obj): if not self.cache_dir: return filename = self._get_cache_file(prefix, url) try: os.makedirs(os.path.join(self.cache_dir, prefix)) except OSError: pass ...
As a Python code analyst, you investigate and solve complex coding mysteries
def join_path(*path_to_join, **kwargs): """Join input path to sample data path (usually in ~/lisa_data) :param path_to_join: one or more paths :param get_root: return dataset root path. If false, the path would be into "medical/orig" :return: joined path """ if "get_root" in kwargs: get...
Implement a Python 3 function for joining input path to sample data path
You are a Python code architect, reviewing and designing scalable and efficient code
Sets path to dataset.
Can you generate the documentation for the following Python 3 function def set_dataset_path(path, cache=None, cachefile="~/.io3d_cache.yaml"): if cachefile is not None: cache = cachef.CacheFile(cachefile) cache.update("local_dataset_dir", path)
As a Python code composer, you craft elegant and concise scripts.
def dataset_path(cache=None, cachefile="~/.io3d_cache.yaml", get_root=False): """Get dataset path. :param cache: CacheFile object :param cachefile: cachefile path, default '~/.io3d_cache.yaml' :return: path to dataset """ local_data_dir = local_dir if cachefile is not None: cache =...
Write a Python 3 script for getting dataset path. :param cache: CacheFile object :param cachefile: cachefile path, default '~/.io3d_cache.yaml' :return: path to dataset
As a Python code analyst, you investigate and solve complex coding mysteries