output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
def remove(self,obj): """ Remove an object from the relation """ relationship_table = self.params['relationship_table'] with self.obj.backend.transaction(implicit = True): condition = and_(relationship_table.c[self.params['related_pk_field_name']] == obj.pk, ...
Create a Python 3 function to remove an object from the relation
You are a Python code analyst, evaluating scripts for potential improvements.
Begin a new transaction.
Explain what the following Python 3 code does def begin(self): if self.in_transaction: # we're already in a transaction... if self._auto_transaction: self._auto_transaction = False return self.commit() self.in_transaction = True for collec...
As a Python code analyst, you investigate and solve complex coding mysteries
Roll back a transaction.
Here you have a function in Python 3, explain what it does def rollback(self, transaction = None): if not self.in_transaction: raise NotInTransaction for collection, store in self.stores.items(): store.rollback() indexes = self.indexes[collection] indexes_...
As a Python code analyst, you investigate and solve complex coding mysteries
def commit(self,transaction = None): """Commit all pending transactions to the database. .. admonition:: Warning This operation can be **expensive** in runtime if a large number of documents (>100.000) is contained in the database, since it will cause all database i...
How would you code a function in Python 3 to commit all pending transactions to the database.
As a Python code composer, you craft elegant and concise scripts.
def create_index(self, cls_or_collection, params=None, fields=None, ephemeral=False, unique=False): """Create new index on the given collection/class with given parameters. :param cls_or_collection: The name of the collection or the class for which to create an ...
Write a Python 3 script for creating a new index on the given collection or class with given parameters.
As a Python code composer, you craft elegant and concise scripts.
def get_pk_index(self, collection): """Return the primary key index for a given collection. :param collection: the collection for which to return the primary index :returns: the primary key index of the given collection """ cls = self.collections[collection] if not cl...
Implement a Python 3 function for returning the primary key index for a given collection.
You are a Python code generator, capable of creating scripts from specifications.
def update(self, obj, set_fields = None, unset_fields = None, update_obj = True): """ We return the result of the save method (updates are not yet implemented here). """ if set_fields: if isinstance(set_fields,(list,tuple)): set_attributes = {} ...
Can you create a Python 3 function that updates the object with the specified fields.
As a Python code translator, you convert algorithms and pseudocode into Python.
Transform the query dictionary to replace e. g. documents with __ref__ fields.
Given the following Python 3 function, write the documentation def _canonicalize_query(self, query): """ Transform the query dictionary to replace e.g. documents with __ref__ fields. """ def transform_query(q): if isinstance(q, dict): nq = {} ...
You are a Python code architect, reviewing and designing scalable and efficient code
This method registers a new document class for use in the backend.
Here you have a function in Python 3, explain what it does def register(self, cls, parameters=None,overwrite = False): if cls in self.deprecated_classes and not overwrite: return False if parameters is None: parameters = {} if 'collection' in parameters: col...
As a Python code analyst, you investigate and solve complex coding mysteries
def serialize(self, obj, convert_keys_to_str=False, embed_level=0, encoders=None, autosave=True, for_query=False,path = None): """ Serializes a given object, i.e. converts it to a representation that can be stored in the database. ...
Write a Python 3 script to serialize a given object to a dictionary.
As a Python code translator, you convert algorithms and pseudocode into Python.
Deserializes a given object by lazy instances of the corresponding class.
Given the following Python 3 function, write the documentation def deserialize(self, obj, encoders=None, embedded=False, create_instance=True): if not encoders: encoders = [] for encoder in encoders + self.standard_encoders: obj = encoder.decode(obj) if isinstance(obj,...
As a Python code composer, you craft elegant and concise scripts.
def create_instance(self, collection_or_class, attributes, lazy=False, call_hook=True, deserialize=True, db_loader=None): """ Creates an instance of a `Document` class corresponding to the given collection name or class. :param collection_or_class: The name of the collection or a reference to t...
Can you implement a function in Python 3 that creates an instance of a Document class corresponding to the given collection name or class.
You are a Python code analyst, evaluating scripts for potential improvements.
Returns the collection name for a given document class.
How would you explain what the following Python 3 function does def get_collection_for_cls(self, cls): if cls not in self.classes: if issubclass(cls, Document) and cls not in self.classes and cls not in self.deprecated_classes: self.autoregister(cls) else: ...
As a Python code analyst, you investigate and solve complex coding mysteries
def get_collection_for_cls_name(self, cls_name): """ Returns the collection name for a given document class. :param cls: The document class for which to return the collection name. :returns: The collection name for the given class. """ for cls in self.classes: ...
Write a Python 3 script for returning the collection name for a given class name.
You are a Python code analyst, evaluating scripts for potential improvements.
def get_cls_for_collection(self, collection): """ Return the class for a given collection name. :param collection: The name of the collection for which to return the class. :returns: A reference to the class for the given collection name. """ for cls, params in self.cla...
Implement a Python 3 function for returning the class for a given collection name.
As a Python code analyst, you investigate and solve complex coding mysteries
def clear(self): """Clear index.""" self._index = defaultdict(list) self._reverse_index = defaultdict(list) self._undefined_keys = {}
How would you implement a function in Python 3 that clears index and reverse index.
You are a Python code analyst, evaluating scripts for potential improvements.
def get_value(self, attributes,key = None): """Get value to be indexed from document attributes. :param attributes: Document attributes :type attributes: dict :return: Value to be indexed :rtype: object """ value = attributes if key is None: ...
Can you write a function in Python 3 where it gets value to be indexed from document attributes.
As a python code expert, you are capable of creating scripts from specifications.
def save_to_store(self): """Save index to store. :raise AttributeError: If no datastore is defined """ if not self._store: raise AttributeError('No datastore defined!') saved_data = self.save_to_data(in_place=True) data = Serializer.serialize(saved_data) ...
Write a Python 3 script to save index to store.
As a python code expert, you are capable of creating scripts from specifications.
Get all keys indexed.
Given the following Python 3 function, write the documentation def get_all_keys(self): all_keys = [] for keys in self._index.values(): all_keys.extend(keys) return all_keys
As a Python code translator, you convert algorithms and pseudocode into Python.
def load_from_store(self): """Load index from store. :return: Whether index was correctly loaded or not :rtype: bool :raise AttributeError: If no datastore is defined """ if not self._store: raise AttributeError('No datastore defined!') if self._stor...
Implement a function in Python 3 to load index from store.
You are a Python code architect, reviewing and designing scalable and efficient code
Sort keys. Keys are sorted based on the value they are indexing. :param keys: Keys to be sorted :type keys: list(str) :param order: Order criteri (asending or descending) :type order: int :return: Sorted keys :rtype: list(str) :raise ValueError: If inval...
Explain what the following Python 3 code does def sort_keys(self, keys, order=QuerySet.ASCENDING): # to do: check that all reverse index values are unambiguous missing_keys = [ key for key in keys if not len(self._reverse_index[key]) ] keys_and_values ...
You are a Python code architect, reviewing and designing scalable and efficient code
Save index to data structure.
Can you generate the documentation for the following Python 3 function def save_to_data(self, in_place=False): if in_place: return [ list(self._index.items()), list(self._undefined_keys.keys()) ] return ( [(key, values[:]) for key, valu...
You are a Python code analyst, evaluating scripts for potential improvements.
Load index structure from data.
Can you generate a brief explanation for the following Python 3 code def load_from_data(self, data, with_undefined=False): if with_undefined: defined_values, undefined_values = data else: defined_values = data undefined_values = None self._index = defaultdict(...
As a Python code analyst, you investigate and solve complex coding mysteries
def get_hash_for(self, value): """Get hash for a given value. :param value: The value to be indexed :type value: object :return: Hashed value :rtype: str """ if isinstance(value,dict) and '__ref__' in value: return self.get_hash_for(value['__ref__'])...
Create a Python 3 function for getting hash for a given value.
As a Python code analyst, you investigate and solve complex coding mysteries
Get the keys for a given value.
Explain what the following Python 3 code does def get_keys_for(self, value): if callable(value): return value(self) hash_value = self.get_hash_for(value) return self._index[hash_value][:]
As a python code expert, you are capable of creating scripts from specifications.
Adds a hashed value to the index.
Here you have a function in Python 3, explain what it does def add_hashed_value(self, hash_value, store_key): if self._unique and hash_value in self._index: raise NonUnique('Hash value {} already in index'.format(hash_value)) if store_key not in self._index[hash_value]: self._ind...
You are a Python code generator, capable of creating scripts from specifications.
Add key to the index.
Can you generate a brief explanation for the following Python 3 code def add_key(self, attributes, store_key): undefined = False try: value = self.get_value(attributes) except (KeyError, IndexError): undefined = True # We remove old values in _reverse_index ...
You are a Python code analyst, evaluating scripts for potential improvements.
Remove the key from the index.
Can you generate a brief explanation for the following Python 3 code def remove_key(self, store_key): if store_key in self._undefined_keys: del self._undefined_keys[store_key] if store_key in self._reverse_index: for value in self._reverse_index[store_key]: self._...
You are a Python code architect, reviewing and designing scalable and efficient code
def rollback(self): """Drop changes from current transaction.""" if not self._in_transaction: raise NotInTransaction self._init_cache() self._in_transaction = False
How would you implement a function in Python 3 that drops changes from current transaction.
As a Python code composer, you craft elegant and concise scripts.
Adds a hashed value to the index.
Can you generate a brief explanation for the following Python 3 code def add_hashed_value(self, hash_value, store_key): if hash_value not in self._add_cache[store_key]: self._add_cache[store_key].append(hash_value) if store_key not in self._reverse_add_cache[hash_value]: self._re...
You are a Python code architect, reviewing and designing scalable and efficient code
def remove_key(self, store_key): """Remove key in the context of the current transaction. :param store_key: The key for the document in the store :type store_key: str """ self._remove_cache[store_key] = True if store_key in self._add_cache: for hash_value in...
Can you write a function in Python 3 where it removes the key in the context of the current transaction.
As a python code expert, you are capable of creating scripts from specifications.
Get the keys for a given value.
Here you have a function in Python 3, explain what it does def get_keys_for(self, value, include_uncommitted=False): if not include_uncommitted: return super(TransactionalIndex, self).get_keys_for(value) else: keys = super(TransactionalIndex, self).get_keys_for(value) ...
You are a Python code generator, capable of creating scripts from specifications.
This method returns a list of objects that correspond to a given set of properties.
How would you explain what the following Python 3 function does def filter(self, cls_or_collection, query, raw = False,only = None,include = None): if not isinstance(cls_or_collection, six.string_types): collection = self.get_collection_for_cls(cls_or_collection) cls = cls_or_collection...
You are a Python code generator, capable of creating scripts from specifications.
def _canonicalize_query(self, query): """ Transform the query dictionary to replace e.g. documents with __ref__ fields. """ def transform_query(q): for encoder in self.query_encoders: q = encoder.encode(q,[]) if isinstance(q, dict): ...
How would you implement a function in Python 3 that transforms the query dictionary to replace e. g. documents with __ref__ fields.
As a Python code composer, you craft elegant and concise scripts.
def filter(self, cls_or_collection, query, raw=False, only=None): """ Filter objects from the database that correspond to a given set of properties. See :py:meth:`blitzdb.backends.base.Backend.filter` for documentation of individual parameters .. note:: This function suppo...
Write a Python 3 script to filter objects from the database that correspond to a given set of properties.
As a Python code analyst, you investigate and solve complex coding mysteries
def boolean_operator_query(boolean_operator): """Generate boolean operator checking function.""" def _boolean_operator_query(expressions): """Apply boolean operator to expressions.""" def _apply_boolean_operator(query_function, expressions=expressions): """Return if expressions with ...
Write a Python 3 function for generating boolean operator checking function.
As a Python code translator, you convert algorithms and pseudocode into Python.
def filter_query(key, expression): """Filter documents with a key that satisfies an expression.""" if (isinstance(expression, dict) and len(expression) == 1 and list(expression.keys())[0].startswith('$')): compiled_expression = compile_query(expression) elif callable(expressi...
Implement a function in Python 3 to filter documents with a key that satisfies an expression.
As a python code expert, you are capable of creating scripts from specifications.
Return a function that returns the store keys that satisfy the given logical not expression.
Can you generate the documentation for the following Python 3 function def not_query(expression): compiled_expression = compile_query(expression) def _not(index, expression=compiled_expression): """Return store key for documents that satisfy expression.""" all_keys = index.get_all_keys() ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Generates a comparison operator checking function that returns a list of store keys that satisfy the given binary operator.
Can you generate a brief explanation for the following Python 3 code def comparison_operator_query(comparison_operator): def _comparison_operator_query(expression): """Apply binary operator to expression.""" def _apply_comparison_operator(index, expression=expression): """Return store ke...
As a Python code translator, you convert algorithms and pseudocode into Python.
def exists_query(expression): """Check that documents have a key that satisfies expression.""" def _exists(index, expression=expression): """Return store key for documents that satisfy expression.""" ev = expression() if callable(expression) else expression if ev: return [ ...
Write a Python 3 script to return a function that checks that documents have a key that satisfies expression.
As a Python code analyst, you investigate and solve complex coding mysteries
def regex_query(expression): """Apply regular expression to result of expression.""" def _regex(index, expression=expression): """Return store key for documents that satisfy expression.""" pattern = re.compile(expression) return [ store_key for value, store_keys ...
How would you implement a function in Python 3 that returns a function that returns the store key for documents that satisfy the regular expression.
As a Python code analyst, you investigate and solve complex coding mysteries
def all_query(expression): """Match arrays that contain all elements in the query.""" def _all(index, expression=expression): """Return store key for documents that satisfy expression.""" ev = expression() if callable(expression) else expression try: iter(ev) except T...
Can you implement a function in Python 3 that matches arrays that contain all elements in the query.
As a Python code analyst, you investigate and solve complex coding mysteries
def in_query(expression): """Match any of the values that exist in an array specified in query.""" def _in(index, expression=expression): """Return store key for documents that satisfy expression.""" ev = expression() if callable(expression) else expression try: iter(ev) ...
Can you create a Python 3 function that returns a function that returns the store key for documents that satisfy the given expression.
As a Python code translator, you convert algorithms and pseudocode into Python.
def compile_query(query): """Compile each expression in query recursively.""" if isinstance(query, dict): expressions = [] for key, value in query.items(): if key.startswith('$'): if key not in query_funcs: raise AttributeError('Invalid operator: {...
How would you implement a function in Python 3 that compiles each expression in query recursively.
As a python code expert, you are capable of creating scripts from specifications.
Temporarily overrides an environment variable.
Can you tell what is the following Python 3 function doing def environment_variable(key, value): if key not in os.environ: previous = None else: previous = os.environ[key] os.environ[key] = value yield if previous is None: del os.environ[key] else: os.environ[...
As a python code expert, you are capable of creating scripts from specifications.
def hookup(self, api): """ Hooks this module up to the given api. """ assert not hasattr(api, self.module_name), """ '{}' conflicts with existing attribute """.format(self.module_name) self.api = api setattr(api, self.module_name, self.execute)
Create a Python 3 function to hook this module up to the given api.
As a Python code translator, you convert algorithms and pseudocode into Python.
def execute(self, *args, **kwargs): """ Puts args and kwargs in a way ansible can understand. Calls ansible and interprets the result. """ assert self.is_hooked_up, "the module should be hooked up to the api" if set_global_context: set_global_context(self.api.option...
Can you write a function in Python 3 where it executes the module and returns the result.
You are a Python code architect, reviewing and designing scalable and efficient code
def ignore_further_calls_to_server(self, server): """ Takes a server out of the list. """ log.error(u'ignoring further calls to {}'.format(server)) self.api.servers.remove(server)
Can you write a function in Python 3 where it removes a server from the list of servers.
You are a Python code analyst, evaluating scripts for potential improvements.
def evaluate_results(self, callback): """ prepare the result of runner call for use with RunnerResults. """ for server, result in callback.unreachable.items(): log.error(u'{} could not be reached'.format(server)) log.debug(u'ansible-output =>\n{}'.format(pformat(result))) ...
Can you create a Python 3 function that evaluates the results of a runner call.
You are a Python code generator, capable of creating scripts from specifications.
Installs the given strategy plugins.
Given the following Python 3 function, write the documentation def install_strategy_plugins(directories): if isinstance(directories, str): directories = directories.split(':') for directory in directories: strategy_loader.add_directory(directory)
You are a Python code analyst, evaluating scripts for potential improvements.
Sets codes which are considered valid when returned from a context module.
Can you generate a brief explanation for the following Python 3 code def valid_return_codes(self, *codes): previous_codes = self._valid_return_codes self._valid_return_codes = codes yield self._valid_return_codes = previous_codes
You are a Python code generator, capable of creating scripts from specifications.
def construct_url(ip_address: str) -> str: """Construct the URL with a given IP address.""" if 'http://' not in ip_address and 'https://' not in ip_address: ip_address = '{}{}'.format('http://', ip_address) if ip_address[-1] == '/': ip_address = ip_address[:-1] return ip_address
Create a Python 3 function for constructing the URL with a given IP address.
As a Python code composer, you craft elegant and concise scripts.
async def update(self) -> None: """ Retrieve the data from the printer. Throws ValueError if host does not support SyncThru """ url = '{}{}'.format(self.url, ENDPOINT) try: async with self._session.get(url) as response: json_dict = de...
Write a Python 3 script for updating the data from the printer.
You are a Python code analyst, evaluating scripts for potential improvements.
def model(self): """Return the model name of the printer.""" try: return self.data.get('identity').get('model_name') except (KeyError, AttributeError): return self.device_status_simple('')
Can you implement a function in Python 3 that returns the model name of the printer.
You are a Python code analyst, evaluating scripts for potential improvements.
Return the location of the printer.
Make a summary of the following Python 3 code def location(self): try: return self.data.get('identity').get('location') except (KeyError, AttributeError): return self.device_status_simple('')
You are a Python code generator, capable of creating scripts from specifications.
Return the serial number of the printer.
Can you generate the documentation for the following Python 3 function def serial_number(self): try: return self.data.get('identity').get('serial_num') except (KeyError, AttributeError): return self.device_status_simple('')
As a Python code translator, you convert algorithms and pseudocode into Python.
def hostname(self): """Return the hostname of the printer.""" try: return self.data.get('identity').get('host_name') except (KeyError, AttributeError): return self.device_status_simple('')
Implement a function in Python 3 to return the hostname of the printer.
You are a Python code architect, reviewing and designing scalable and efficient code
Return the status of the device as string.
Make a summary of the following Python 3 code def device_status(self): try: return self.device_status_simple( self.data.get('status').get('status1')) except (KeyError, AttributeError): return self.device_status_simple('')
As a Python code translator, you convert algorithms and pseudocode into Python.
Return the capabilities of the printer.
How would you explain what the following Python 3 function does def capability(self) -> Dict[str, Any]: try: return self.data.get('capability', {}) except (KeyError, AttributeError): return {}
As a Python code analyst, you investigate and solve complex coding mysteries
def toner_status(self, filter_supported: bool = True) -> Dict[str, Any]: """Return the state of all toners cartridges.""" toner_status = {} for color in self.COLOR_NAMES: try: toner_stat = self.data.get( '{}_{}'.format(SyncThru.TONER, color),...
How would you implement a function in Python 3 that returns the state of all toners cartridges.
You are a Python code analyst, evaluating scripts for potential improvements.
def input_tray_status(self, filter_supported: bool = True) -> Dict[int, Any]: """Return the state of all input trays.""" tray_status = {} for i in range(1, 5): try: tray_stat = self.data.get('{}{}'.format(SyncThru.TRAY, i), {}) ...
Implement a function in Python 3 to return the state of all input trays.
As a Python code composer, you craft elegant and concise scripts.
def output_tray_status(self) -> Dict[int, Dict[str, str]]: """Return the state of all output trays.""" tray_status = {} try: tray_stat = self.data.get('outputTray', []) for i, stat in enumerate(tray_stat): tray_status[i] = { 'nam...
How would you code a function in Python 3 to return the state of all output trays.
As a python code expert, you are capable of creating scripts from specifications.
def drum_status(self, filter_supported: bool = True) -> Dict[str, Any]: """Return the state of all drums.""" drum_status = {} for color in self.COLOR_NAMES: try: drum_stat = self.data.get('{}_{}'.format(SyncThru.DRUM, color), ...
Write a Python 3 script for returning the state of all drums.
As a python code expert, you are capable of creating scripts from specifications.
def pdb_run(func: Callable, *args: Any, **kwargs: Any) -> None: """ Calls ``func(*args, **kwargs)``; if it raises an exception, break into the ``pdb`` debugger. """ # noinspection PyBroadException try: func(*args, **kwargs) except: # nopep8 type_, value, tb = sys.exc_info() ...
Write a Python 3 script to call func with args and kwargs and runs pdb.
As a Python code composer, you craft elegant and concise scripts.
This function attempts to retrieve the class name from a frame object.
How would you explain what the following Python 3 function does def get_class_name_from_frame(fr: FrameType) -> Optional[str]: # http://stackoverflow.com/questions/2203424/python-how-to-retrieve-class-information-from-a-frame-object # noqa args, _, _, value_dict = inspect.getargvalues(fr) # we check the fi...
You are a Python code architect, reviewing and designing scalable and efficient code
def get_caller_name(back: int = 0) -> str: """ Return details about the CALLER OF THE CALLER (plus n calls further back) of this function. So, if your function calls :func:`get_caller_name`, it will return the name of the function that called your function! (Or ``back`` calls further back.) ...
Write a Python 3 script to return details about the caller of this function.
As a Python code composer, you craft elegant and concise scripts.
def debug_object(obj, log_level: int = logging.DEBUG) -> None: """ Sends details about a Python to the log, specifically its ``repr()`` representation, and all of its attributes with their name, value, and type. Args: obj: object to debug log_level: log level to use; default is ``loggin...
Implement a function in Python 3 to send details about a Python object to the log.
As a Python code translator, you convert algorithms and pseudocode into Python.
Called in all circumstances when the data is loaded from the database including in aggregates and values() calls.
Can you generate the documentation for the following Python 3 function def from_db_value(self, value, expression, connection, context): if value is None: return value return json_decode(value)
As a python code expert, you are capable of creating scripts from specifications.
Parse the given XML input and return a dictionary.
Can you generate the documentation for the following Python 3 function def parse(xml_input, encoding=None, expat=expat, process_namespaces=False, namespace_separator=':', **kwargs): """Parse the given XML input and convert it into a dictionary. `xml_input` can either be a `string` or a file-like obje...
As a Python code translator, you convert algorithms and pseudocode into Python.
def cxxRecordDecl(*args): """Matches C++ class declarations. >>> from glud import * >>> config = ''' ... class W; ... template<typename T> class X {}; ... struct Y {}; ... union Z {}; ... ''' >>> m = cxxRecordDecl() >>> for c in walk(m, parse_string(config).cursor): ... ...
Implement a Python 3 function for matching C ++ class declarations.
As a Python code translator, you convert algorithms and pseudocode into Python.
def recordDecl(*args): """Matches class, struct, and union declarations. >>> from glud import * >>> config = ''' ... class W; ... template<typename T> class X {}; ... struct Y {}; ... union Z {}; ... ''' >>> m = recordDecl() >>> for c in walk(m, parse_string(config).cursor):...
Create a Python 3 function to match class struct and union declarations.
As a Python code composer, you craft elegant and concise scripts.
Converts a string or integer to a boolean.
Explain what the following Python 3 code does def convert_to_bool(x: Any, default: bool = None) -> bool: if isinstance(x, bool): return x if not x: # None, zero, blank string... return default try: return int(x) != 0 except (TypeError, ValueError): pass try: ...
As a Python code analyst, you investigate and solve complex coding mysteries
Transforms its input into an integer or returns default.
How would you explain what the following Python 3 function does def convert_to_int(x: Any, default: int = None) -> int: try: return int(x) except (TypeError, ValueError): return default
You are a Python code generator, capable of creating scripts from specifications.
Applies convert_to_bool to the specified attributes of an object.
Given the following Python 3 function, write the documentation def convert_attrs_to_bool(obj: Any, attrs: Iterable[str], default: bool = None) -> None: """ Applies :func:`convert_to_bool` to the specified attributes of an object, modifying it in place. ...
You are a Python code analyst, evaluating scripts for potential improvements.
Converts the specified attributes of an object to upper case.
Can you generate the documentation for the following Python 3 function def convert_attrs_to_uppercase(obj: Any, attrs: Iterable[str]) -> None: for a in attrs: value = getattr(obj, a) if value is None: continue setattr(obj, a, value.upper())
You are a Python code architect, reviewing and designing scalable and efficient code
Converts the specified attributes of an object to lower case.
Can you generate the documentation for the following Python 3 function def convert_attrs_to_lowercase(obj: Any, attrs: Iterable[str]) -> None: for a in attrs: value = getattr(obj, a) if value is None: continue setattr(obj, a, value.lower())
As a python code expert, you are capable of creating scripts from specifications.
Applies convert_to_int to the specified attributes of an object.
Explain what the following Python 3 code does def convert_attrs_to_int(obj: Any, attrs: Iterable[str], default: int = None) -> None: """ Applies :func:`convert_to_int` to the specified attributes of an object, modifying it in place. """ for a in attr...
As a Python code analyst, you investigate and solve complex coding mysteries
def hex_xformat_decode(s: str) -> Optional[bytes]: """ Reverse :func:`hex_xformat_encode`. The parameter is a hex-encoded BLOB like .. code-block:: none "X'CDE7A24B1A9DBA3148BCB7A0B9DA5BB6A424486C'" Original purpose and notes: - SPECIAL HANDLING for BLOBs: a string like ``X'01FF'`` ...
Write a Python 3 script to decode a string into a byte array.
As a Python code composer, you craft elegant and concise scripts.
def base64_64format_decode(s: str) -> Optional[bytes]: """ Reverse :func:`base64_64format_encode`. Original purpose and notes: - THIS IS ANOTHER WAY OF DOING BLOBS: base64 encoding, e.g. a string like ``64'cGxlYXN1cmUu'`` is a base-64-encoded BLOB (the ``64'...'`` bit is my representation)...
Create a Python 3 function to decode base64 encoded string.
As a python code expert, you are capable of creating scripts from specifications.
def environ_setting(name, default=None, required=True): """ Fetch setting from the environment. The bahavior of the setting if it is not in environment is as follows: 1. If it is required and the default is None, raise Exception 2. If it is requried and a default exists, return default ...
Can you write a function in Python 3 where it fetches a setting from the environment.
As a Python code translator, you convert algorithms and pseudocode into Python.
Loads the configuration from YAML files specified by the CONF_PATH module variable.
Can you generate the documentation for the following Python 3 function def load(klass): config = klass() for path in klass.CONF_PATHS: if os.path.exists(path): with open(path, 'r') as conf: config.configure(yaml.safe_load(conf)) return config
You are a Python code architect, reviewing and designing scalable and efficient code
def configure(self, conf={}): """ Allows updating of the configuration via a dictionary of configuration terms or a configuration object. Generally speaking, this method is utilized to configure the object from a JSON or YAML parsing. """ if not conf: return ...
Write a Python 3 function that can allow updating of the configuration of the object via a dictionary of configuration terms or a configuration object. Generally speaking this method is utilized to configure the object from a JSON or a YAML parsing.
You are a Python code generator, capable of creating scripts from specifications.
Returns an iterable of sorted option names and values for all the configuration directives in the class.
How would you explain what the following Python 3 function does def options(self): keys = self.__class__.__dict__.copy() keys.update(self.__dict__) keys = sorted(keys.keys()) for opt in keys: val = self.get(opt) if val is not None: yield opt, val
You are a Python code generator, capable of creating scripts from specifications.
def formatdt(date: datetime.date, include_time: bool = True) -> str: """ Formats a ``datetime.date`` to ISO-8601 basic format, to minute accuracy with no timezone (or, if ``include_time`` is ``False``, omit the time). """ if include_time: return date.strftime("%Y-%m-%dT%H:%M") else: ...
Create a Python 3 function for formatting a datetime. date to ISO - 8601 basic format.
You are a Python code architect, reviewing and designing scalable and efficient code
def convert_duration(duration: datetime.timedelta, units: str) -> Optional[float]: """ Convert a ``datetime.timedelta`` object -- a duration -- into other units. Possible units: ``s``, ``sec``, ``seconds`` ``m``, ``min``, ``minutes`` ``h``, ``hr``, ``hours`` ...
Create a Python 3 function for converting a datetime. timedelta object into other units.
As a python code expert, you are capable of creating scripts from specifications.
Returns True if this interval overlaps other.
Make a summary of the following Python 3 code def overlaps(self, other: "Interval") -> bool: return not(self.end <= other.start or self.start >= other.end)
You are a Python code analyst, evaluating scripts for potential improvements.
Is this interval contiguous?
Explain what the following Python 3 code does def contiguous(self, other: "Interval") -> bool: return not(self.end < other.start or self.start > other.end)
You are a Python code architect, reviewing and designing scalable and efficient code
def contains(self, time: datetime.datetime, inclusive: bool = True) -> bool: """ Does the interval contain a momentary time? Args: time: the ``datetime.datetime`` to check inclusive: use inclusive rather than exclusive range checks? """ i...
Can you write a function in Python 3 where it returns True if the interval contains the given time.
As a Python code analyst, you investigate and solve complex coding mysteries
def within(self, other: "Interval", inclusive: bool = True) -> bool: """ Is this interval contained within the other? Args: other: the :class:`Interval` to check inclusive: use inclusive rather than exclusive range checks? """ if not other: re...
Create a Python 3 function for returning True if this interval is contained within the other.
You are a Python code architect, reviewing and designing scalable and efficient code
Returns an interval representing the intersection of this and the other.
Can you generate the documentation for the following Python 3 function def intersection(self, other: "Interval") -> Optional["Interval"]: if not self.contiguous(other): return None return Interval( max(self.start, other.start), min(self.end, other.end) )
You are a Python code analyst, evaluating scripts for potential improvements.
def cut(self, times: Union[datetime.datetime, List[datetime.datetime]]) -> List["Interval"]: """ Returns a list of intervals produced by using times (a list of ``datetime.datetime`` objects, or a single such object) as a set of knives to slice this interval...
Can you write a function in Python 3 where it returns a list of intervals produced by using times as a list of knives to slice this interval.
You are a Python code generator, capable of creating scripts from specifications.
def wholeday(date: datetime.date) -> "Interval": """ Returns an :class:`Interval` covering the date given (midnight at the start of that day to midnight at the start of the next day). """ start = datetime.datetime.combine(date, datetime.time()) return Interval( ...
Can you implement a function in Python 3 that returns an interval covering the given date.
As a python code expert, you are capable of creating scripts from specifications.
def daytime(date: datetime.date, daybreak: datetime.time = datetime.time(NORMAL_DAY_START_H), nightfall: datetime.time = datetime.time(NORMAL_DAY_END_H)) \ -> "Interval": """ Returns an :class:`Interval` representing daytime on the date given. """ ...
Can you create a Python 3 function that returns an :class:`Interval` representing daytime on the date given.
You are a Python code architect, reviewing and designing scalable and efficient code
def dayspan(startdate: datetime.date, enddate: datetime.date, include_end: bool = True) -> Optional["Interval"]: """ Returns an :class:`Interval` representing the date range given, from midnight at the start of the first day to midnight at the end of the l...
Implement a function in Python 3 to return an interval representing the date range given from startdate to enddate.
You are a Python code analyst, evaluating scripts for potential improvements.
def component_on_date(self, date: datetime.date) -> Optional["Interval"]: """ Returns the part of this interval that falls on the date given, or ``None`` if the interval doesn't have any part during that date. """ return self.intersection(Interval.wholeday(date))
How would you implement a function in Python 3 that returns the part of this interval that falls on the given date.
As a Python code analyst, you investigate and solve complex coding mysteries
def day_night_duration( self, daybreak: datetime.time = datetime.time(NORMAL_DAY_START_H), nightfall: datetime.time = datetime.time(NORMAL_DAY_END_H)) \ -> Tuple[datetime.timedelta, datetime.timedelta]: """ Returns a ``(day, night)`` tuple of ``datetime.ti...
Create a Python 3 function for returning a tuple of the duration of this interval that falls into day and night.
As a python code expert, you are capable of creating scripts from specifications.
def duration_outside_nwh( self, starttime: datetime.time = datetime.time(NORMAL_DAY_START_H), endtime: datetime.time = datetime.time(NORMAL_DAY_END_H), weekdays_only: bool = False, weekends_only: bool = False) -> datetime.timedelta: """ Returns...
Implement a Python 3 function for returning the number of hours outside the given time range.
As a python code expert, you are capable of creating scripts from specifications.
Returns the set of dates of all Saturdays that this calendar contains.
Here you have a function in Python 3, explain what it does def saturdays_of_weekends(self) -> Set[datetime.date]: startdate = self.start.date() enddate = self.end.date() ndays = (enddate - startdate).days + 1 saturdays = set() for i in range(ndays): date = startdate +...
You are a Python code architect, reviewing and designing scalable and efficient code
Makes and returns a copy of the : class : IntervalList.
Can you generate the documentation for the following Python 3 function def copy(self, no_overlap: bool = None, no_contiguous: bool = None) -> "IntervalList": """ Makes and returns a copy of the :class:`IntervalList`. The ``no_overlap``/``no_contiguous`` parameters can be changed. ...
You are a Python code analyst, evaluating scripts for potential improvements.
def add(self, interval: Interval) -> None: """ Adds an interval to the list. If ``self.no_overlap`` is True, as is the default, it will merge any overlapping intervals thus created. """ if interval is None: return if not isinstance(interval, Interval): ...
Create a Python 3 function for adding an interval to the list.
As a python code expert, you are capable of creating scripts from specifications.