output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
log with different level
Can you generate a brief explanation for the following Python 3 code def _tolog(self,level): def wrapper(msg): if self.log_colors: color = self.log_colors[level.upper()] getattr(self.logger, level.lower())(coloring("- {}".format(msg), color)) else: ...
As a python code expert, you are capable of creating scripts from specifications.
Returns a class method from bottle. HTTPResponse. status_line attribute.
Make a summary of the following Python 3 code def from_status(cls, status_line, msg=None): method = getattr(cls, status_line.lower()[4:].replace(' ', '_')) return method(msg)
As a Python code translator, you convert algorithms and pseudocode into Python.
Shortcut API for HTTP 400 Bad Request response.
Make a summary of the following Python 3 code def bad_request(cls, errors=None): if cls.expose_status: # pragma: no cover cls.response.content_type = 'application/json' cls.response._status_line = '400 Bad Request' return cls(400, errors=errors).to_json
You are a Python code generator, capable of creating scripts from specifications.
Shortcut API for HTTP 401 Unauthorized response.
Make a summary of the following Python 3 code def unauthorized(cls, errors=None): if cls.expose_status: # pragma: no cover cls.response.content_type = 'application/json' cls.response._status_line = '401 Unauthorized' return cls(401, errors=errors).to_json
As a Python code analyst, you investigate and solve complex coding mysteries
def to_json(self): """Short cut for JSON response service data. Returns: Dict that implements JSON interface. """ web_resp = collections.OrderedDict() web_resp['status_code'] = self.status_code web_resp['status_text'] = dict(HTTP_CODES).get(self.status_code...
Write a Python 3 function that can short cut for JSON response service data.
As a Python code analyst, you investigate and solve complex coding mysteries
Setup logging configuration Args: **kwargs: See below logging_config_dict (dict): Logging configuration dictionary OR logging_config_json (str): Path to JSON Logging configuration OR logging_config_yaml (str): Path to YAML Logging configuration. Defaults to internal logging_configur...
Here you have a function in Python 3, explain what it does def setup_logging(**kwargs): # type: (Any) -> None """Setup logging configuration Args: **kwargs: See below logging_config_dict (dict): Logging configuration dictionary OR logging_config_json (str): Path to JSON Logging conf...
You are a Python code generator, capable of creating scripts from specifications.
A helper method for self. search that returns a generator rather than a list.
Here you have a function in Python 3, explain what it does def _search_generator(self, item: Any) -> Generator[Tuple[Any, Any], None, None]: results = 0 for key, value in self.enumerate(item): yield key, value results += 1 if results == 0: raise SearchError(st...
As a Python code translator, you convert algorithms and pseudocode into Python.
Asks a question yes no style
Make a summary of the following Python 3 code def ask_bool(question: str, default: bool = True) -> bool: default_q = "Y/n" if default else "y/N" answer = input("{0} [{1}]: ".format(question, default_q)) lower = answer.lower() if not lower: return default return lower == "y"
You are a Python code analyst, evaluating scripts for potential improvements.
Asks for a number in a question
Can you generate the documentation for the following Python 3 function def ask_int(question: str, default: int = None) -> int: default_q = " [default: {0}]: ".format( default) if default is not None else "" answer = input("{0} [{1}]: ".format(question, default_q)) if not answer: if default ...
As a Python code composer, you craft elegant and concise scripts.
def ask_path(question: str, default: str = None) -> str: """Asks for a path""" default_q = " [default: {0}]: ".format( default) if default is not None else "" answer = input("{0} [{1}]: ".format(question, default_q)) if answer == "": return default if os.path.isdir(answer): ...
How would you code a function in Python 3 to ask for a path
As a Python code translator, you convert algorithms and pseudocode into Python.
Asks for a comma seperated list of strings
Explain what the following Python 3 code does def ask_list(question: str, default: list = None) -> list: default_q = " [default: {0}]: ".format( ",".join(default)) if default is not None else "" answer = input("{0} [{1}]: ".format(question, default_q)) if answer == "": return default re...
As a Python code analyst, you investigate and solve complex coding mysteries
def ask_str(question: str, default: str = None): """Asks for a simple string""" default_q = " [default: {0}]: ".format( default) if default is not None else "" answer = input("{0} [{1}]: ".format(question, default_q)) if answer == "": return default return answer
Write a Python 3 script to ask for a simple string
As a Python code composer, you craft elegant and concise scripts.
def get_tools(self) -> list: """Lets the user enter the tools he want to use""" tools = "flake8,pylint,vulture,pyroma,isort,yapf,safety,dodgy,pytest,pypi".split( ",") print("Available tools: {0}".format(",".join(tools))) answer = ask_list("What tools would you like to use?", ...
Can you create a Python 3 function that lets the user enter the tools he want to use
As a Python code translator, you convert algorithms and pseudocode into Python.
def paginator(limit, offset, record_count, base_uri, page_nav_tpl='&limit={}&offset={}'): """Compute pagination info for collection filtering. Args: limit (int): Collection filter limit. offset (int): Collection filter offset. record_count (int): Collection filter total record count. ...
Implement a function in Python 3 to compute pagination info for the current record count and base uri.
You are a Python code generator, capable of creating scripts from specifications.
JSON serializer that accepts datetime & date
How would you explain what the following Python 3 function does def serialize(obj): from datetime import datetime, date, time if isinstance(obj, date) and not isinstance(obj, datetime): obj = datetime.combine(obj, time.min) if isinstance(obj, datetime): return obj.isoformat()
As a Python code composer, you craft elegant and concise scripts.
def check(response, expected_status=200, url=None): """ Check whether the status code of the response equals expected_status and raise an APIError otherwise. @param url: The url of the response (for error messages). Defaults to response.url @param json: if True, return r.json(), othe...
Write a Python 3 script to check whether the status code of the response equals expected_status and raise an APIError otherwise.
As a Python code analyst, you investigate and solve complex coding mysteries
Get the authentication info for the current user from the AUTH_FILE environment variable
How would you explain what the following Python 3 function does def _get_auth(self, user=None, password=None): fn = os.path.expanduser(AUTH_FILE) if os.path.exists(fn): for i, line in enumerate(csv.reader(open(fn))): if len(line) != 3: log.warning("Cannot ...
As a Python code composer, you craft elegant and concise scripts.
Make an HTTP request to the given URL with the host user and password information. Returns the deserialized json if successful and raises an exception if not successful.
Here you have a function in Python 3, explain what it does def request(self, url, method="get", format="json", data=None, expected_status=None, headers=None, use_xpost=True, **options): """ Make an HTTP request to the given relative URL with the host, user, and password informati...
As a Python code composer, you craft elegant and concise scripts.
Get all pages at url yielding individual results
Given the following Python 3 function, write the documentation def get_pages(self, url, page=1, page_size=100, yield_pages=False, **filters): n = 0 for page in itertools.count(page): r = self.request(url, page=page, page_size=page_size, **filters) n += len(r['results']) ...
You are a Python code generator, capable of creating scripts from specifications.
Get the scroll through the resource at url and yield the individual results
Explain what the following Python 3 code does def get_scroll(self, url, page_size=100, yield_pages=False, **filters): n = 0 options = dict(page_size=page_size, **filters) format = filters.get('format') while True: r = self.request(url, use_xpost=False, **options) ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_status(self): """Get the AmCAT status page""" url = URL.status.format(**locals()) return self.get_request(url)
How would you code a function in Python 3 to get the AmCAT status page
As a Python code composer, you craft elegant and concise scripts.
def aggregate(self, **filters): """Conduct an aggregate query""" url = URL.aggregate.format(**locals()) return self.get_pages(url, **filters)
Can you implement a function in Python 3 that conducts an aggregate query
You are a Python code analyst, evaluating scripts for potential improvements.
def list_sets(self, project, **filters): """List the articlesets in a project""" url = URL.articlesets.format(**locals()) return self.get_pages(url, **filters)
Can you create a Python 3 function that lists the articlesets in a project
You are a Python code architect, reviewing and designing scalable and efficient code
def get_set(self, project, articleset, **filters): """List the articlesets in a project""" url = URL.articleset.format(**locals()) return self.request(url, **filters)
Can you write a function in Python 3 where it lists the articlesets in a project
You are a Python code generator, capable of creating scripts from specifications.
List the articles in a set
Make a summary of the following Python 3 code def list_articles(self, project, articleset, page=1, **filters): url = URL.article.format(**locals()) return self.get_pages(url, page=page, **filters)
As a Python code translator, you convert algorithms and pseudocode into Python.
def create_set(self, project, json_data=None, **options): """ Create a new article set. Provide the needed arguments using post_data or with key-value pairs """ url = URL.articlesets.format(**locals()) if json_data is None: # form encoded request r...
Can you implement a function in Python 3 that creates a new article set.
You are a Python code generator, capable of creating scripts from specifications.
Create one or more articles in the set.
Can you generate the documentation for the following Python 3 function def create_articles(self, project, articleset, json_data=None, **options): url = URL.article.format(**locals()) # TODO duplicated from create_set, move into requests # (or separate post method?) if json_data is None: ...
As a python code expert, you are capable of creating scripts from specifications.
def sign(self, encoded): """ Return authentication signature of encoded bytes """ signature = self._hmac.copy() signature.update(encoded) return signature.hexdigest().encode('utf-8')
How would you code a function in Python 3 to return authentication signature of encoded bytes
As a Python code translator, you convert algorithms and pseudocode into Python.
Split into message and signature
Can you generate the documentation for the following Python 3 function def split(self, encoded): maxlen = len(encoded) - self.sig_size message = encoded[:maxlen] signature = encoded[-self.sig_size:] return message, signature
As a python code expert, you are capable of creating scripts from specifications.
Validate integrity of encoded bytes
Make a summary of the following Python 3 code def auth(self, encoded): message, signature = self.split(encoded) computed = self.sign(message) if not hmac.compare_digest(signature, computed): raise AuthenticatorInvalidSignature
As a Python code analyst, you investigate and solve complex coding mysteries
A memorization decorator for class properties.
Can you generate the documentation for the following Python 3 function def cached_classproperty(fun): @functools.wraps(fun) def get(cls): try: return cls.__cache[fun] except AttributeError: cls.__cache = {} except KeyError: # pragma: no cover pass ...
As a Python code analyst, you investigate and solve complex coding mysteries
Custom handler routing decorator.
Can you generate the documentation for the following Python 3 function def route_method(method_name, extra_part=False): def wrapper(callable_obj): if method_name.lower() not in DEFAULT_ROUTES: raise HandlerHTTPMethodError( 'Invalid http method in method: {}'.format(method_name) ...
You are a Python code architect, reviewing and designing scalable and efficient code
Create a new issue on the issue tracker.
Can you tell what is the following Python 3 function doing def issue_add(lancet, assign, add_to_sprint, summary): summary = " ".join(summary) issue = create_issue( lancet, summary, # project_id=project_id, add_to_active_sprint=add_to_sprint, ) if assign: if assign...
As a Python code composer, you craft elegant and concise scripts.
def _maybe_update(self, user, attribute, new_value): """ DRY helper. If the specified attribute of the user differs from the specified value, it will be updated. """ old_value = getattr(user, attribute) if new_value != old_value: self.stderr.write( ...
Can you write a function in Python 3 where it dries helper. If the specified attribute of the user differs from the specified value, it will be updated.
You are a Python code architect, reviewing and designing scalable and efficient code
def _check_email_match(self, user, email): """ DRY helper. Requiring the user to specify both username and email will help catch certain issues, for example if the expected username has already been taken by someone else. """ if user.email != email: #...
Write a Python 3 script to check that the passed email address matches the username and email.
As a Python code translator, you convert algorithms and pseudocode into Python.
def credentials_checker(url, username, password): """Check the provided credentials using the Harvest API.""" api = HarvestAPI(url, (username, password)) try: api.whoami() except HarvestError: return False else: return True
Implement a function in Python 3 to check the provided credentials using the Harvest API.
As a Python code analyst, you investigate and solve complex coding mysteries
Construct a new Harvest client.
Can you generate the documentation for the following Python 3 function def harvest(lancet, config_section): url, username, password = lancet.get_credentials( config_section, credentials_checker ) project_id_getter = lancet.get_instance_from_config( "timer", "project_id_getter", lancet )...
As a python code expert, you are capable of creating scripts from specifications.
def temp_dir(folder=None, delete=True): # type: (Optional[str], bool) -> str """Get a temporary directory optionally with folder appended (and created if it doesn't exist) Args: folder (Optional[str]): Folder to create in temporary folder. Defaults to None. delete (bool): Whether to delete ...
Write a Python 3 script for returning a temporary directory optionally with folder appended and created if it doesn t exist.
As a Python code translator, you convert algorithms and pseudocode into Python.
Send a push notification.
How would you explain what the following Python 3 function does def send(self, obj): if not isinstance(obj, NotificationMessage): raise ValueError, u"You can only send NotificationMessage objects." self._send_queue.put(obj)
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_error(self, block = True, timeout = None): """ Gets the next error message. Each error message is a 2-tuple of (status, identifier).""" return self._error_queue.get(block = block, timeout = timeout)
Write a Python 3 script for getting the next error message from the error queue.
You are a Python code analyst, evaluating scripts for potential improvements.
Get the next feedback message.
Make a summary of the following Python 3 code def get_feedback(self, block = True, timeout = None): if self._feedback_greenlet is None: self._feedback_greenlet = gevent.spawn(self._feedback_loop) return self._feedback_queue.get(block = block, timeout = timeout)
As a Python code analyst, you investigate and solve complex coding mysteries
def wait_send(self, timeout = None): """Wait until all queued messages are sent.""" self._send_queue_cleared.clear() self._send_queue_cleared.wait(timeout = timeout)
How would you implement a function in Python 3 that waits until all queued messages are sent.
You are a Python code analyst, evaluating scripts for potential improvements.
def start(self): """Start the message sending loop.""" if self._send_greenlet is None: self._send_greenlet = gevent.spawn(self._send_loop)
How would you code a function in Python 3 to start the message sending loop.
As a python code expert, you are capable of creating scripts from specifications.
Stop sending all pending messages and close connection.
Can you generate the documentation for the following Python 3 function def stop(self, timeout = 10.0): if (self._send_greenlet is not None) and \ (self._send_queue.qsize() > 0): self.wait_send(timeout = timeout) if self._send_greenlet is not None: gevent.kill(self._send_greenlet) self._send_greenlet =...
As a python code expert, you are capable of creating scripts from specifications.
Convert text to SSML based on the text s current format.
Can you generate a brief explanation for the following Python 3 code def convert_to_ssml(text, text_format): if text_format is None: return text elif text_format == 'plain': return plain_to_ssml(text) elif text_format == 'html': return html_to_ssml(text) else: raise Value...
You are a Python code generator, capable of creating scripts from specifications.
Replaces specific html tags with probable SSML counterparts.
Make a summary of the following Python 3 code def html_to_ssml(text): ssml_text = reduce(lambda x, y: x.replace(y, html_to_ssml_maps[y]), html_to_ssml_maps, text) return ssml_text
You are a Python code architect, reviewing and designing scalable and efficient code
Returns a list of matching blocks of text in a and b.
Can you generate a brief explanation for the following Python 3 code def get_matching_text_in_strs(a, b, match_min_size=30, ignore='', end_characters=''): # type: (str, str, int, str, str) -> List[str] """Returns a list of matching blocks of text in a and b Args: a (str): First string to match ...
You are a Python code architect, reviewing and designing scalable and efficient code
Returns a string containing the matching blocks of text in a list of strings followed by non - matching.
Can you tell what is the following Python 3 function doing def get_matching_text(string_list, match_min_size=30, ignore='', end_characters='.!\r\n'): # type: (List[str], int, str, str) -> str """Returns a string containing matching blocks of text in a list of strings followed by non-matching. Args: ...
As a python code expert, you are capable of creating scripts from specifications.
Returns a string containing the matching blocks of text followed by non - matching blocks of text.
How would you explain what the following Python 3 function does def get_matching_then_nonmatching_text(string_list, separator='', match_min_size=30, ignore='', end_characters='.!\r\n'): # type: (List[str], str, int, str, str) -> str """Returns a string containing matching ...
You are a Python code analyst, evaluating scripts for potential improvements.
Expand braces and return an iterator.
Can you generate the documentation for the following Python 3 function def iexpand(string, keep_escapes=False): if isinstance(string, bytes): is_bytes = True string = string.decode('latin-1') else: is_bytes = False if is_bytes: return (entry.encode('latin-1') for entry in ...
You are a Python code analyst, evaluating scripts for potential improvements.
def set_expanding(self): """Set that we are expanding a sequence, and return whether a release is required by the caller.""" status = not self.expanding if status: self.expanding = True return status
Can you create a Python 3 function that sets that we are expanding a sequence and return whether a release is required by the caller.
As a Python code composer, you craft elegant and concise scripts.
Returns a generator that squashes two iterables into one.
Explain what the following Python 3 code does def squash(self, a, b): return ((''.join(x) if isinstance(x, tuple) else x) for x in itertools.product(a, b))
You are a Python code architect, reviewing and designing scalable and efficient code
def get_literals(self, c, i, depth): """ Get a string literal. Gather all the literal chars up to opening curly or closing brace. Also gather chars between braces and commas within a group (is_expanding). """ result = [''] is_dollar = False try: ...
Create a Python 3 function to get a string literal.
You are a Python code analyst, evaluating scripts for potential improvements.
A generator that combines two iterables.
Can you generate the documentation for the following Python 3 function def combine(self, a, b): for l in (a, b): for x in l: yield x
As a Python code analyst, you investigate and solve complex coding mysteries
Get the sequence of the current item.
Can you tell what is the following Python 3 function doing def get_sequence(self, c, i, depth): result = [] release = self.set_expanding() has_comma = False # Used to indicate validity of group (`{1..2}` are an exception). is_empty = True # Tracks whether the current slot is empty `{s...
As a python code expert, you are capable of creating scripts from specifications.
def get_range(self, i): """ Check and retrieve range if value is a valid range. Here we are looking to see if the value is series or range. We look for `{1..2[..inc]}` or `{a..z[..inc]}` (negative numbers are fine). """ try: m = i.match(RE_INT_ITER) ...
How would you implement a function in Python 3 that checks and retrieve range if value is a valid range.
As a Python code analyst, you investigate and solve complex coding mysteries
def format_value(self, value, padding): """Get padding adjusting for negative values.""" # padding = padding - 1 if value < 0 and padding > 0 else padding # prefix = '-' if value < 0 else '' if padding: return "{:0{pad}d}".format(value, pad=padding) else: ...
Create a Python 3 function for formatting the value for the log entry.
You are a Python code generator, capable of creating scripts from specifications.
Get an integer range between start and end and increments of increment.
Make a summary of the following Python 3 code def get_int_range(self, start, end, increment=None): first, last = int(start), int(end) increment = int(increment) if increment is not None else 1 max_length = max(len(start), len(end)) # Zero doesn't make sense as an incrementer # ...
You are a Python code architect, reviewing and designing scalable and efficient code
Get a range of alphabetic characters.
Explain what the following Python 3 code does def get_char_range(self, start, end, increment=None): increment = int(increment) if increment else 1 if increment < 0: increment = -increment # Zero doesn't make sense as an incrementer # but like bash, just assume one i...
You are a Python code architect, reviewing and designing scalable and efficient code
Yields the entries from the given string.
How would you explain what the following Python 3 function does def expand(self, string): self.expanding = False empties = [] found_literal = False if string: i = iter(StringIter(string)) for x in self.get_literals(next(i), i, 0): # We don't want ...
As a python code expert, you are capable of creating scripts from specifications.
Merges two dicts into a and returns a new dict that is merged with b.
Explain what the following Python 3 code does def merge_two_dictionaries(a, b, merge_lists=False): # type: (DictUpperBound, DictUpperBound, bool) -> DictUpperBound """Merges b into a and returns merged result NOTE: tuples and arbitrary objects are not handled as it is totally ambiguous what should happen ...
You are a Python code generator, capable of creating scripts from specifications.
Merges all dictionaries in dicts into a single dictionary and returns the result
How would you explain what the following Python 3 function does def merge_dictionaries(dicts, merge_lists=False): # type: (List[DictUpperBound], bool) -> DictUpperBound """Merges all dictionaries in dicts into a single dictionary and returns result Args: dicts (List[DictUpperBound]): Dictionaries t...
You are a Python code generator, capable of creating scripts from specifications.
def dict_diff(d1, d2, no_key='<KEYNOTFOUND>'): # type: (DictUpperBound, DictUpperBound, str) -> Dict """Compares two dictionaries Args: d1 (DictUpperBound): First dictionary to compare d2 (DictUpperBound): Second dictionary to compare no_key (str): What value to use if key is not fo...
Write a Python 3 function that can compare two dictionaries returning a new dictionary with the keys that differ.
As a Python code composer, you craft elegant and concise scripts.
Adds value to a list in a dictionary by key
Make a summary of the following Python 3 code def dict_of_lists_add(dictionary, key, value): # type: (DictUpperBound, Any, Any) -> None """Add value to a list in a dictionary by key Args: dictionary (DictUpperBound): Dictionary to which to add values key (Any): Key within dictionary ...
You are a Python code architect, reviewing and designing scalable and efficient code
Adds value to a set in a dictionary by key
Can you generate a brief explanation for the following Python 3 code def dict_of_sets_add(dictionary, key, value): # type: (DictUpperBound, Any, Any) -> None """Add value to a set in a dictionary by key Args: dictionary (DictUpperBound): Dictionary to which to add values key (Any): Key with...
As a python code expert, you are capable of creating scripts from specifications.
Distribute the contents of a list of items in a list.
Explain what the following Python 3 code does def list_distribute_contents_simple(input_list, function=lambda x: x): # type: (List, Callable[[Any], Any]) -> List """Distribute the contents of a list eg. [1, 1, 1, 2, 2, 3] -> [1, 2, 3, 1, 2, 1]. List can contain complex types like dictionaries in which case ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Distribute the contents of a list eg. 1 2 3 4 5 5
Here you have a function in Python 3, explain what it does def list_distribute_contents(input_list, function=lambda x: x): # type: (List, Callable[[Any], Any]) -> List """Distribute the contents of a list eg. [1, 1, 1, 2, 2, 3] -> [1, 2, 1, 2, 1, 3]. List can contain complex types like dictionaries in which...
As a Python code translator, you convert algorithms and pseudocode into Python.
Extract a list by looking up key in each member of a list of dictionaries
Can you generate a brief explanation for the following Python 3 code def extract_list_from_list_of_dict(list_of_dict, key): # type: (List[DictUpperBound], Any) -> List """Extract a list by looking up key in each member of a list of dictionaries Args: list_of_dict (List[DictUpperBound]): List of dic...
As a Python code translator, you convert algorithms and pseudocode into Python.
Convert keys and values of a dictionary using functions passed in as parameters
Given the following Python 3 function, write the documentation def key_value_convert(dictin, keyfn=lambda x: x, valuefn=lambda x: x, dropfailedkeys=False, dropfailedvalues=False, exception=ValueError): # type: (DictUpperBound, Callable[[Any], Any], Callable[[Any], Any], bool, bool, ExceptionUp...
As a Python code translator, you convert algorithms and pseudocode into Python.
Convert keys of dictionary to integers.
Explain what the following Python 3 code does def integer_key_convert(dictin, dropfailedkeys=False): # type: (DictUpperBound, bool) -> Dict """Convert keys of dictionary to integers Args: dictin (DictUpperBound): Input dictionary dropfailedkeys (bool): Whether to drop dictionary entries whe...
You are a Python code analyst, evaluating scripts for potential improvements.
Convert values of dictionary to integers
Make a summary of the following Python 3 code def integer_value_convert(dictin, dropfailedvalues=False): # type: (DictUpperBound, bool) -> Dict """Convert values of dictionary to integers Args: dictin (DictUpperBound): Input dictionary dropfailedvalues (bool): Whether to drop dictionary ent...
You are a Python code generator, capable of creating scripts from specifications.
Convert values of dictionary to floats
Here you have a function in Python 3, explain what it does def float_value_convert(dictin, dropfailedvalues=False): # type: (DictUpperBound, bool) -> Dict """Convert values of dictionary to floats Args: dictin (DictUpperBound): Input dictionary dropfailedvalues (bool): Whether to drop dicti...
As a Python code translator, you convert algorithms and pseudocode into Python.
def avg_dicts(dictin1, dictin2, dropmissing=True): # type: (DictUpperBound, DictUpperBound, bool) -> Dict """Create a new dictionary from two dictionaries by averaging values Args: dictin1 (DictUpperBound): First input dictionary dictin2 (DictUpperBound): Second input dictionary dro...
Implement a function in Python 3 to create a new dictionary from two dictionaries by averaging values of keys in one dictionary.
You are a Python code architect, reviewing and designing scalable and efficient code
def read_list_from_csv(filepath, dict_form=False, headers=None, **kwargs): # type: (str, bool, Union[int, List[int], List[str], None], Any) -> List[Union[Dict, List]] """Read a list of rows in dict or list form from a csv. (The headers argument is either a row number or list of row numbers (in case of mu...
Can you implement a function in Python 3 that reads a list of rows from a CSV file.
As a Python code composer, you craft elegant and concise scripts.
def write_list_to_csv(list_of_rows, filepath, headers=None): # type: (List[Union[DictUpperBound, List]], str, Union[int, List[int], List[str], None]) -> None """Write a list of rows in dict or list form to a csv. (The headers argument is either a row number or list of row numbers (in case of multi-line h...
Can you create a Python 3 function that writes a list of rows in dict or list form to a csv file.
As a Python code analyst, you investigate and solve complex coding mysteries
Convert command line arguments in a comma separated string to a dictionary
Explain what the following Python 3 code does def args_to_dict(args): # type: (str) -> DictUpperBound[str,str] """Convert command line arguments in a comma separated string to a dictionary Args: args (str): Command line arguments Returns: DictUpperBound[str,str]: Dictionary of argument...
As a python code expert, you are capable of creating scripts from specifications.
def compare_files(path1, path2): # type: (str, str) -> List[str] """Returns the delta between two files using -, ?, + format excluding lines that are the same Args: path1 (str): Path to first file path2 (str): Path to second file Returns: List[str]: Delta between the two fi...
How would you implement a function in Python 3 that returns the delta between two files using -?,? format excluding lines that are the same
You are a Python code generator, capable of creating scripts from specifications.
def assert_files_same(path1, path2): # type: (str, str) -> None """Asserts that two files are the same and returns delta using -, ?, + format if not Args: path1 (str): Path to first file path2 (str): Path to second file Returns: None """ difflines = compare_files(p...
Implement a function in Python 3 to assert that two files are the same and returns delta using -?,?, + format if not
You are a Python code architect, reviewing and designing scalable and efficient code
Entry point when called on the command - line.
Make a summary of the following Python 3 code def main(): # Locale locale.setlocale(locale.LC_ALL, '') # Encoding for output streams if str == bytes: # PY2 writer = codecs.getwriter(locale.getpreferredencoding()) o_stdout, o_stderr = sys.stdout, sys.stderr sys.stdout = writer(s...
You are a Python code analyst, evaluating scripts for potential improvements.
def apply(self, callback, context): # pragma: no cover """Apply the HTTPError wrapper to the callback. """ def wrapper(*args, **kwargs): try: return callback(*args, **kwargs) except bottle.HTTPError as error: return self.error_wrapper.fro...
Create a Python 3 function for applying the HTTPError wrapper to the callback.
You are a Python code architect, reviewing and designing scalable and efficient code
def add_episode(self, text, text_format, title, author, summary=None, publish_date=None, synthesizer='watson', synth_args=None, sentence_break='. '): """ Add a new episode to the podcast. :param text: See :meth:`Episode`. :param text_format: S...
Write a Python 3 function for adding a new episode to the podcast.
As a Python code analyst, you investigate and solve complex coding mysteries
def add_scheduled_job(self, text_source, cron_args, text_format, title, author, summary=None, synthesizer='watson', synth_args=None, sentence_break='. '): """ Add and start a new scheduled job to dynamically generate podcasts. Note: scheduling will end when the process...
Implement a function in Python 3 to add a new scheduled job to the scheduler.
As a Python code translator, you convert algorithms and pseudocode into Python.
def publish(self, titles): """ Publish a set of episodes to the Podcast's RSS feed. :param titles: Either a single episode title or a sequence of episode titles to publish. """ if isinstance(titles, Sequence) and not isinstance(titles, six.string_types): ...
How would you code a function in Python 3 to publish a set of episodes to the Podcast s RSS feed.
As a Python code analyst, you investigate and solve complex coding mysteries
def render_audio(self): """ Synthesize audio from the episode's text. """ segment = text_to_speech(self._text, self.synthesizer, self.synth_args, self.sentence_break) milli = len(segment) seconds = '{0:.1f}'.format(float(milli) / 1000 % 60).zfill(2) minutes = '{0...
Can you implement a function in Python 3 that renders audio from the episode s text.
You are a Python code architect, reviewing and designing scalable and efficient code
Mark an episode as published.
Can you tell what is the following Python 3 function doing def publish(self): if self.published is False: self.published = True else: raise Warning(self.title + ' is already published.')
You are a Python code architect, reviewing and designing scalable and efficient code
def unpublish(self): """ Mark an episode as not published. """ if self.published is True: self.published = False else: raise Warning(self.title + ' is already not published.')
Create a Python 3 function for marking an episode as not published.
You are a Python code generator, capable of creating scripts from specifications.
def _environment_variables(**kwargs): # type: (Any) -> Any """ Overwrite keyword arguments with environment variables Args: **kwargs: See below user_agent (str): User agent string. Returns: kwargs: Changed keyword arguments """ ...
Can you create a Python 3 function that over-writes keyword arguments with environment variables.
As a Python code translator, you convert algorithms and pseudocode into Python.
Constructs user agent string from user agent configuration and user agent string.
Can you generate the documentation for the following Python 3 function def _construct(configdict, prefix, ua): # type: (Dict, str, str) -> str """ Construct user agent Args: configdict (str): Additional configuration for user agent prefix (str): Text to put at st...
As a python code expert, you are capable of creating scripts from specifications.
Load user agent config file and construct new instance of class
Given the following Python 3 function, write the documentation def _load(cls, prefix, user_agent_config_yaml, user_agent_lookup=None): # type: (str, str, Optional[str]) -> str """ Load user agent YAML file Args: prefix (str): Text to put at start of user agent us...
As a Python code translator, you convert algorithms and pseudocode into Python.
Create a new user agent string.
How would you explain what the following Python 3 function does def _create(cls, user_agent=None, user_agent_config_yaml=None, user_agent_lookup=None, **kwargs): # type: (Optional[str], Optional[str], Optional[str], Any) -> str """ Get full user agent string Args: ...
As a Python code analyst, you investigate and solve complex coding mysteries
def set_global(cls, user_agent=None, user_agent_config_yaml=None, user_agent_lookup=None, **kwargs): # type: (Optional[str], Optional[str], Optional[str], Any) -> None """ Set global user agent string Args: user_agent (Optional[str]): User agent string. HD...
Implement a Python 3 function for setting the global user agent string for this class.
You are a Python code architect, reviewing and designing scalable and efficient code
def get(cls, user_agent=None, user_agent_config_yaml=None, user_agent_lookup=None, **kwargs): # type: (Optional[str], Optional[str], Optional[str], Any) -> str """ Get full user agent string from parameters if supplied falling back on global user agent if set. Args: user_age...
Can you create a Python 3 function that returns the full user agent string from user agent string from parameters if supplied falling back on global user agent if set.
As a Python code analyst, you investigate and solve complex coding mysteries
Save dictionary to YAML file preserving order if it is an OrderedDict ArcGIS object
Explain what the following Python 3 code does def save_yaml(dictionary, path, pretty=False, sortkeys=False): # type: (Dict, str, bool, bool) -> None """Save dictionary to YAML file preserving order if it is an OrderedDict Args: dictionary (Dict): Python dictionary to save path (str): Path t...
You are a Python code generator, capable of creating scripts from specifications.
def save_json(dictionary, path, pretty=False, sortkeys=False): # type: (Dict, str, bool, bool) -> None """Save dictionary to JSON file preserving order if it is an OrderedDict Args: dictionary (Dict): Python dictionary to save path (str): Path to JSON file pretty (bool): Whether to ...
Implement a Python 3 function for saving a Python dictionary to a JSON file preserving order if it is an OrderedDict AttributeNames
As a python code expert, you are capable of creating scripts from specifications.
def load_yaml(path): # type: (str) -> OrderedDict """Load YAML file into an ordered dictionary Args: path (str): Path to YAML file Returns: OrderedDict: Ordered dictionary containing loaded YAML file """ with open(path, 'rt') as f: yamldict = yaml.load(f.read(), Loader=...
Implement a Python 3 function for loading a YAML file into an ordered dictionary
As a Python code translator, you convert algorithms and pseudocode into Python.
Load a JSON file into an ordered dictionary
How would you explain what the following Python 3 function does def load_json(path): # type: (str) -> OrderedDict """Load JSON file into an ordered dictionary Args: path (str): Path to JSON file Returns: OrderedDict: Ordered dictionary containing loaded JSON file """ with open(...
As a python code expert, you are capable of creating scripts from specifications.
def load_file_to_str(path): # type: (str) -> str """ Load file into a string removing newlines Args: path (str): Path to file Returns: str: String contents of file """ with open(path, 'rt') as f: string = f.read().replace(linesep, '') if not string: rai...
Can you write a function in Python 3 where it loads file into a string removing newlines
As a python code expert, you are capable of creating scripts from specifications.
List all contributors visible in the git history.
Make a summary of the following Python 3 code def contributors(lancet, output): sorting = pygit2.GIT_SORT_TIME | pygit2.GIT_SORT_REVERSE commits = lancet.repo.walk(lancet.repo.head.target, sorting) contributors = ((c.author.name, c.author.email) for c in commits) contributors = OrderedDict(contributors)...
As a Python code analyst, you investigate and solve complex coding mysteries
Converts given text to a pydub AudioSegment using a specified speech synthesizer.
Explain what the following Python 3 code does def text_to_speech(text, synthesizer, synth_args, sentence_break): if len(text.split()) < 50: if synthesizer == 'watson': with open('.temp.wav', 'wb') as temp: temp.write(watson_request(text=text, synth_args=synth_args).content) ...
As a Python code composer, you craft elegant and concise scripts.
def watson_request(text, synth_args): """ Makes a single request to the IBM Watson text-to-speech API. :param text: The text that will be synthesized to audio. :param synth_args: A dictionary of arguments to add to the request. These should include username and password for auth...
How would you code a function in Python 3 to make a single request to the IBM Watson text - to - speech API.
As a Python code composer, you craft elegant and concise scripts.