text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def service_unavailable(cls, errors=None): """Shortcut API for HTTP 503 `Service Unavailable` response. Args: errors (list): Response key/value data. Returns: W...
if cls.expose_status: # pragma: no cover cls.response.content_type = 'application/json' cls.response._status_line = '503 Service Unavailable' return cls(503, None, errors).to_json
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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) web_resp['data'] = self.data if self.data is not None else {} web_resp['errors'] = self.errors or [] return web_resp
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ask_bool(question: str, default: bool = True) -> bool: """Asks a question yes no style"""
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"
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ask_int(question: str, default: int = None) -> int: """Asks for a number in a question"""
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 is None: print("No default set, try again.") return ask_int(question, default) return default ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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): return answer print( "No such directory: {answer}, please try again"...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ask_list(question: str, default: list = None) -> list: """Asks for a comma seperated list of strings"""
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 return [ans.strip() for ans in answer.split(",")]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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?", ["flake8", "pytest"]) if any(tool not in tools for t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(self) -> None: """The main function for generating the config file"""
path = ask_path("where should the config be stored?", ".snekrc") conf = configobj.ConfigObj() tools = self.get_tools() for tool in tools: conf[tool] = getattr(self, tool)() # pylint: disable=assignment-from-no-return conf.filename = path conf.write() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def paginator(limit, offset, record_count, base_uri, page_nav_tpl='&limit={}&offset={}'): """Compute pagination info for collection filtering. Args: limit (int):...
total_pages = int(math.ceil(record_count / limit)) next_cond = limit + offset <= record_count prev_cond = offset >= limit next_page = base_uri + page_nav_tpl.format(limit, offset + limit) if next_cond else None prev_page = base_uri + page_nav_tpl.format(limit, offset - limit) if prev_cond else ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def serialize(obj): """JSON serializer that accepts datetime & date"""
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()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check(response, expected_status=200, url=None): """ Check whether the status code of the response equals expected_status and raise an APIError otherwise. @pa...
if response.status_code != expected_status: if url is None: url = response.url try: err = response.json() except: err = {} # force generic error if all(x in err for x in ("status", "message", "description", "details")): raise _APIErr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 gi...
if expected_status is None: if method == "get": expected_status = 200 elif method == "post": expected_status = 201 else: raise ValueError("No expected status supplied and method unknown.") if not url.startswith("http")...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_status(self): """Get the AmCAT status page"""
url = URL.status.format(**locals()) return self.get_request(url)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def aggregate(self, **filters): """Conduct an aggregate query"""
url = URL.aggregate.format(**locals()) return self.get_pages(url, **filters)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_articles(self, project, articleset, page=1, **filters): """List the articles in a set"""
url = URL.article.format(**locals()) return self.get_pages(url, page=page, **filters)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 return self.request(url, method="post", data=options) else: if not isinstance(json_data, (string_types)): json_data = json.dumps(json_data,default = serializ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_articles(self, project, articleset, json_data=None, **options): """ Create one or more articles in the set. Provide the needed arguments using the jso...
url = URL.article.format(**locals()) # TODO duplicated from create_set, move into requests # (or separate post method?) if json_data is None: # form encoded request return self.request(url, method="post", data=options) else: if not isinstance(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sign(self, encoded): """ Return authentication signature of encoded bytes """
signature = self._hmac.copy() signature.update(encoded) return signature.hexdigest().encode('utf-8')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def split(self, encoded): """ Split into signature and message """
maxlen = len(encoded) - self.sig_size message = encoded[:maxlen] signature = encoded[-self.sig_size:] return message, signature
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def auth(self, encoded): """ Validate integrity of encoded bytes """
message, signature = self.split(encoded) computed = self.sign(message) if not hmac.compare_digest(signature, computed): raise AuthenticatorInvalidSignature
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cached_classproperty(fun): """A memorization decorator for class properties. It implements the above `classproperty` decorator, with the difference that the ...
@functools.wraps(fun) def get(cls): try: return cls.__cache[fun] except AttributeError: cls.__cache = {} except KeyError: # pragma: no cover pass ret = cls.__cache[fun] = fun(cls) return ret return classproperty(get)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plugin_method(*plugin_names): """Plugin Method decorator. Signs a web handler function with the plugins to be applied as attributes. Args: plugin_names (list...
def wrapper(callable_obj): for plugin_name in plugin_names: if not hasattr(callable_obj, plugin_name): setattr(callable_obj, plugin_name, True) return callable_obj return wrapper
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def route_method(method_name, extra_part=False): """Custom handler routing decorator. Signs a web handler callable with the http method as attribute. Args: metho...
def wrapper(callable_obj): if method_name.lower() not in DEFAULT_ROUTES: raise HandlerHTTPMethodError( 'Invalid http method in method: {}'.format(method_name) ) callable_obj.http_method = method_name.upper() callable_obj.url_extra_part = callable_ob...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def issue_add(lancet, assign, add_to_sprint, summary): """ Create a new issue on the issue tracker. """
summary = " ".join(summary) issue = create_issue( lancet, summary, # project_id=project_id, add_to_active_sprint=add_to_sprint, ) if assign: if assign == "me": username = lancet.tracker.whoami() else: username = assign assi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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( _('Setting {attribute} for user "{username}" to "{new_value}"').format( attribute=attribute, username=user.username, new_value=new_value ) ) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 t...
if user.email != email: # The passed email address doesn't match this username's email address. # Assume a problem and fail. raise CommandError( _( 'Skipping user "{}" because the specified and existing email ' 'address...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def harvest(lancet, config_section): """Construct a new Harvest client."""
url, username, password = lancet.get_credentials( config_section, credentials_checker ) project_id_getter = lancet.get_instance_from_config( "timer", "project_id_getter", lancet ) task_id_getter = lancet.get_instance_from_config( "timer", "task_id_getter", lancet ) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send(self, obj): """Send a push notification"""
if not isinstance(obj, NotificationMessage): raise ValueError, u"You can only send NotificationMessage objects." self._send_queue.put(obj)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_feedback(self, block = True, timeout = None): """ Gets the next feedback message. Each feedback message is a 2-tuple of (timestamp, device_token)."...
if self._feedback_greenlet is None: self._feedback_greenlet = gevent.spawn(self._feedback_loop) return self._feedback_queue.get(block = block, timeout = timeout)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start(self): """Start the message sending loop."""
if self._send_greenlet is None: self._send_greenlet = gevent.spawn(self._send_loop)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def html_to_ssml(text): """ Replaces specific html tags with probable SSML counterparts. """
ssml_text = reduce(lambda x, y: x.replace(y, html_to_ssml_maps[y]), html_to_ssml_maps, text) return ssml_text
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def multiple_replace(string, replacements): # type: (str, Dict[str,str]) -> str """Simultaneously replace multiple strigns in a string Args: string (str): Input...
pattern = re.compile("|".join([re.escape(k) for k in sorted(replacements, key=len, reverse=True)]), flags=re.DOTALL) return pattern.sub(lambda x: replacements[x.group(0)], string)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 matchin...
compare = difflib.SequenceMatcher(lambda x: x in ignore) compare.set_seqs(a=a, b=b) matching_text = list() for match in compare.get_matching_blocks(): start = match.a text = a[start: start+match.size] if end_characters: prev_text = text while len(text) !...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def iexpand(string, keep_escapes=False): """Expand braces and return an iterator."""
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 ExpandBrace(keep_escapes).expand(string)) else: return (entry for entry in ExpandBrace(keep_escape...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_escape(self, c, i): """Get an escape."""
try: escaped = next(i) except StopIteration: escaped = '' return c + escaped if self.keep_escapes else escaped
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def squash(self, a, b): """ Returns a generator that squashes two iterables into one. ``` ['this', 'that'], [[' and', ' or']] => ['this and', 'this or', 'that an...
return ((''.join(x) if isinstance(x, tuple) else x) for x in itertools.product(a, b))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 brace...
result = [''] is_dollar = False try: while c: ignore_brace = is_dollar is_dollar = False if c == '$': is_dollar = True elif c == '\\': c = [self.get_escape(c, i)] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def combine(self, a, b): """A generator that combines two iterables."""
for l in (a, b): for x in l: yield x
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_sequence(self, c, i, depth): """ Get the sequence. Get sequence between `{}`, such as: `{a,b}`, `{1..2[..inc]}`, etc. It will basically crawl to the end ...
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 `{slot,slot,slot}`. # Detect numerical and alphabetic series: `{1..2}` etc. i.rew...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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[.....
try: m = i.match(RE_INT_ITER) if m: return self.get_int_range(*m.groups()) m = i.match(RE_CHR_ITER) if m: return self.get_char_range(*m.groups()) except Exception: # pragma: no cover # TODO: We really should ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: return str(value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_int_range(self, start, end, increment=None): """Get an integer range between start and end and increments of increment."""
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 # but like bash, just assume one if increment == 0: increment = 1 if st...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_char_range(self, start, end, increment=None): """Get a range of alphabetic characters."""
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 if increment == 0: increment = 1 inverse = start > end alpha = _nalpha ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def merge_two_dictionaries(a, b, merge_lists=False): # type: (DictUpperBound, DictUpperBound, bool) -> DictUpperBound """Merges b into a and returns merged resul...
key = None # ## debug output # sys.stderr.write('DEBUG: %s to %s\n' %(b,a)) try: if a is None or isinstance(a, (six.string_types, six.text_type, six.integer_types, float)): # border case for first run or if a is a primitive a = b elif isinstance(a, list): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def merge_dictionaries(dicts, merge_lists=False): # type: (List[DictUpperBound], bool) -> DictUpperBound """Merges all dictionaries in dicts into a single dictio...
dict1 = dicts[0] for other_dict in dicts[1:]: merge_two_dictionaries(dict1, other_dict, merge_lists=merge_lists) return dict1
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dict_diff(d1, d2, no_key='<KEYNOTFOUND>'): # type: (DictUpperBound, DictUpperBound, str) -> Dict """Compares two dictionaries Args: d1 (DictUpperBound): Fir...
d1keys = set(d1.keys()) d2keys = set(d2.keys()) both = d1keys & d2keys diff = {k: (d1[k], d2[k]) for k in both if d1[k] != d2[k]} diff.update({k: (d1[k], no_key) for k in d1keys - both}) diff.update({k: (no_key, d2[k]) for k in d2keys - both}) return diff
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 (DictUpp...
list_objs = dictionary.get(key, list()) list_objs.append(value) dictionary[key] = list_objs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 (DictUpper...
set_objs = dictionary.get(key, set()) set_objs.add(value) dictionary[key] = set_objs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 o...
result = list() for dictionary in list_of_dict: result.append(dictionary[key]) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def integer_key_convert(dictin, dropfailedkeys=False): # type: (DictUpperBound, bool) -> Dict """Convert keys of dictionary to integers Args: dictin (DictUpperBo...
return key_value_convert(dictin, keyfn=int, dropfailedkeys=dropfailedkeys)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def integer_value_convert(dictin, dropfailedvalues=False): # type: (DictUpperBound, bool) -> Dict """Convert values of dictionary to integers Args: dictin (DictU...
return key_value_convert(dictin, valuefn=int, dropfailedvalues=dropfailedvalues)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def float_value_convert(dictin, dropfailedvalues=False): # type: (DictUpperBound, bool) -> Dict """Convert values of dictionary to floats Args: dictin (DictUpper...
return key_value_convert(dictin, valuefn=float, dropfailedvalues=dropfailedvalues)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def avg_dicts(dictin1, dictin2, dropmissing=True): # type: (DictUpperBound, DictUpperBound, bool) -> Dict """Create a new dictionary from two dictionaries by ave...
dictout = dict() for key in dictin1: if key in dictin2: dictout[key] = (dictin1[key] + dictin2[key]) / 2 elif not dropmissing: dictout[key] = dictin1[key] if not dropmissing: for key in dictin2: if key not in dictin1: dictout[key] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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): ...
arguments = dict() for arg in args.split(','): key, value = arg.split('=') arguments[key] = value return arguments
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compare_files(path1, path2): # type: (str, str) -> List[str] """Returns the delta between two files using -, ?, + format excluding lines that are the same Ar...
diff = difflib.ndiff(open(path1).readlines(), open(path2).readlines()) return [x for x in diff if x[0] in ['-', '+', '?']]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ...
difflines = compare_files(path1, path2) assert len(difflines) == 0, ''.join(['\n'] + difflines)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.from_status( status_line=error.status_line, msg=error.body ) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_episode(self, text, text_format, title, author, summary=None, publish_date=None, synthesizer='watson', synth_args=None, sentence_break='. '): """ Add a n...
if title in self.episodes: raise ValueError('"' + title + '" already exists as an episode title.') link = self.output_path + '/' + title.replace(' ', '_').lower() + '.mp3' episode_text = convert_to_ssml(text, text_format) new_episode = Episode(episode_text, text_format, tit...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_scheduled_job(self, text_source, cron_args, text_format, title, author, summary=None, synthesizer='watson', synth_args=None, sentence_break='. '): """ Ad...
if not callable(text_source): raise TypeError('Argument "text" must be a function') def add_episode(): episode_text = text_source() episode_title = title + '_' + datetime.utcnow().strftime('%Y%m%d%H%M%S') self.add_episode(episode_text, text_format, epis...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ...
if isinstance(titles, Sequence) and not isinstance(titles, six.string_types): for title in titles: self.episodes[title].publish() elif isinstance(titles, six.string_types): self.episodes[titles].publish() else: raise TypeError('titles must be ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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:.0f}'.format((milli / (1000 * 60)) % 60).zfill(2) hours = '{0:.0f}'.format((milli / (100...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def publish(self): """ Mark an episode as published. """
if self.published is False: self.published = True else: raise Warning(self.title + ' is already published.')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _construct(configdict, prefix, ua): # type: (Dict, str, str) -> str """ Construct user agent Args: configdict (str): Additional configuration for user agent...
if not ua: raise UserAgentError("User_agent parameter missing. It can be your project's name for example.") preprefix = configdict.get('preprefix') if preprefix: user_agent = '%s:' % preprefix else: user_agent = '' if prefix: user_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)...
if not user_agent_config_yaml: user_agent_config_yaml = cls.default_user_agent_config_yaml logger.info( 'No user agent or user agent config file given. Using default user agent config file: %s.' % user_agent_config_yaml) if not isfile(user_agent_config_yaml): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _create(cls, user_agent=None, user_agent_config_yaml=None, user_agent_lookup=None, **kwargs): # type: (Optional[str], Optional[str], Optional[str], Any) -> s...
kwargs = UserAgent._environment_variables(**kwargs) if 'user_agent' in kwargs: user_agent = kwargs['user_agent'] del kwargs['user_agent'] prefix = kwargs.get('prefix') if prefix: del kwargs['prefix'] else: prefix = 'HDXPythonUtilit...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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) -...
cls.user_agent = cls._create(user_agent, user_agent_config_yaml, user_agent_lookup, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 "...
if user_agent or user_agent_config_yaml or 'user_agent' in UserAgent._environment_variables(**kwargs): return UserAgent._create(user_agent, user_agent_config_yaml, user_agent_lookup, **kwargs) if cls.user_agent: return cls.user_agent else: raise UserAgentErro...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ...
if sortkeys: dictionary = dict(dictionary) with open(path, 'w') as f: if pretty: pyaml.dump(dictionary, f) else: yaml.dump(dictionary, f, default_flow_style=None, Dumper=yamlloader.ordereddict.CDumper)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ...
with open(path, 'w') as f: if pretty: indent = 2 separators = (',', ': ') else: indent = None separators = (', ', ': ') json.dump(dictionary, f, indent=indent, sort_keys=sortkeys, separators=separators)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_yaml(path): # type: (str) -> OrderedDict """Load YAML file into an ordered dictionary Args: path (str): Path to YAML file Returns: OrderedDict: Ordered...
with open(path, 'rt') as f: yamldict = yaml.load(f.read(), Loader=yamlloader.ordereddict.CSafeLoader) if not yamldict: raise (LoadError('YAML file: %s is empty!' % path)) return yamldict
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_json(path): # type: (str) -> OrderedDict """Load JSON file into an ordered dictionary Args: path (str): Path to JSON file Returns: OrderedDict: Ordered...
with open(path, 'rt') as f: jsondict = json.loads(f.read(), object_pairs_hook=OrderedDict) if not jsondict: raise (LoadError('JSON file: %s is empty!' % path)) return jsondict
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 f...
with open(path, 'rt') as f: string = f.read().replace(linesep, '') if not string: raise LoadError('%s file is empty!' % path) return string
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def contributors(lancet, output): """ List all contributors visible in the git history. """
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) template_content = content_from_path( lancet.config.get('packagin...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def text_to_speech(text, synthesizer, synth_args, sentence_break): """ Converts given text to a pydub AudioSegment using a specified speech synthesizer. At the m...
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) response = AudioSegment.from_wav('.temp.wav') os.remove('.temp.wav') return respo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. :...
params = { 'text': text, 'accept': 'audio/wav' } if synth_args is not None: params.update(synth_args) if 'username' in params: username = params.pop('username') else: raise Warning('The IBM Watson API requires credentials that should be passed as "username" ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_rss_feed(podcast): """ Builds a podcast RSS feed and returns an xml file. :param podcast: A Podcast model to build the RSS feed from. """
if not os.path.exists(podcast.output_path): os.makedirs(podcast.output_path) rss = ET.Element('rss', attrib={'xmlns:itunes': 'http://www.itunes.com/dtds/podcast-1.0.dtd', 'version': '2.0'}) channel = ET.SubElement(rss, 'channel') ET.SubElement(channel, 'title').text = podcast.title ET.Sub...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get(self, uid=None): """Example retrieve API method. """
# Return resource collection if uid is None: return self.response_factory.ok(data=resource_db) # Return resource based on UID. try: record = [r for r in resource_db if r.get('id') == uid].pop() except IndexError: return self.response_facto...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def post(self): """Example POST method. """
resource_data = self.request.json record = {'id': str(len(resource_db) + 1), 'name': resource_data.get('name')} resource_db.append(record) return self.response_factory.ok(data=record)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def put(self, uid): """Example PUT method. """
resource_data = self.request.json try: record = resource_db[uid] except KeyError: return self.response_factory.not_found(errors=['Resource with UID {} does not exist!']) record['name'] = resource_data.get('name') return self.response_factory.ok(data=...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete(self, uid): """Example DELETE method. """
try: record = resource_db[uid].copy() except KeyError: return self.response_factory.not_found(errors=['Resource with UID {} does not exist!']) del resource_db[uid] return self.response_factory.ok(data=record)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_pages(url): """ Return the 'pages' from the starting url Technically, look for the 'next 50' link, yield and download it, repeat """
while True: yield url doc = html.parse(url).find("body") links = [a for a in doc.findall(".//a") if a.text and a.text.startswith("next ")] if not links: break url = urljoin(url, links[0].get('href'))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_article_urls(url): """ Return the articles from a page Technically, look for a div with class mw-search-result-heading and get the first link from this d...
doc = html.parse(url).getroot() for div in doc.cssselect("div.mw-search-result-heading"): href = div.cssselect("a")[0].get('href') if ":" in href: continue # skip Category: links href = urljoin(url, href) yield href
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_article(url): """ Return a single article as a 'amcat-ready' dict Uses the 'export' function of wikinews to get an xml article """
a = html.parse(url).getroot() title = a.cssselect(".firstHeading")[0].text_content() date = a.cssselect(".published")[0].text_content() date = datetime.datetime.strptime(date, "%A, %B %d, %Y").isoformat() paras = a.cssselect("#mw-content-text p") paras = paras[1:] # skip first paragraph, which ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def scrape_wikinews(conn, project, articleset, query): """ Scrape wikinews articles from the given query @param conn: The AmcatAPI object @param articleset: The ...
url = "http://en.wikinews.org/w/index.php?search={}&limit=50".format(query) logging.info(url) for page in get_pages(url): urls = get_article_urls(page) arts = list(get_articles(urls)) logging.info("Adding {} articles to set {}:{}" .format(len(arts), project, art...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pub(self, topic=b'', embed_topic=False): """ Returns a callable that can be used to transmit a message, with a given ``topic``, in a publisher-subscriber fas...
if not isinstance(topic, bytes): error = 'Topic must be bytes' log.error(error) raise TypeError(error) sock = self.__sock(zmq.PUB) return self.__send_function(sock, topic, embed_topic)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sub(self, topics=(b'',)): """ Returns an iterable that can be used to iterate over incoming messages, that were published with one of the topics specified in...
sock = self.__sock(zmq.SUB) for topic in topics: if not isinstance(topic, bytes): error = 'Topics must be a list of bytes' log.error(error) raise TypeError(error) sock.setsockopt(zmq.SUBSCRIBE, topic) return self.__recv_g...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def push(self): """ Returns a callable that can be used to transmit a message in a push-pull fashion. Note that the sender function has a ``print`` like signatur...
sock = self.__sock(zmq.PUSH) return self.__send_function(sock)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pull(self): """ Returns an iterable that can be used to iterate over incoming messages, that were pushed by a push socket. Note that the iterable returns as ...
sock = self.__sock(zmq.PULL) return self.__recv_generator(sock)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def connect(self, ip, port): """ Connects to a server at the specified ip and port. :param ip: an IP address :type ip: str or unicode :param port: port number fr...
_check_valid_port_range(port) address = (ip, port) if address in self._addresses: error = 'Already connected to {0} on port {1}'.format(ip, port) log.exception(error) raise ValueError(error) self._addresses.append(address) if self._is_read...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def disconnect(self, ip, port): """ Disconnects from a server at the specified ip and port. :param ip: an IP address :type ip: str or unicode :param port: port n...
_check_valid_port_range(port) address = (ip, port) try: self._addresses.remove(address) except ValueError: error = 'There was no connection to {0} on port {1}'.format(ip, port) log.exception(error) raise ValueError(error) if self...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_exponent(d): """Remove exponent."""
return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def millify(n, precision=0, drop_nulls=True, prefixes=[]): """Humanize number."""
millnames = ['', 'k', 'M', 'B', 'T', 'P', 'E', 'Z', 'Y'] if prefixes: millnames = [''] millnames.extend(prefixes) n = float(n) millidx = max(0, min(len(millnames) - 1, int(math.floor(0 if n == 0 else math.log10(abs(n)) / 3)))) result = '{:.{precision}f}'.for...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prettify(amount, separator=','): """Separate with predefined separator."""
orig = str(amount) new = re.sub("^(-?\d+)(\d{3})", "\g<1>{0}\g<2>".format(separator), str(amount)) if orig == new: return new else: return prettify(new)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_json(json_data, decoder=None): """ Load data from json string :param json_data: Stringified json object :type json_data: str | unicode :param decoder: U...
if decoder is None: decoder = DateTimeDecoder return json.loads(json_data, object_hook=decoder.decode)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save_json(val, pretty=False, sort=True, encoder=None): """ Save data to json string :param val: Value or struct to save :type val: None | int | float | str |...
if encoder is None: encoder = DateTimeEncoder if pretty: data = json.dumps( val, indent=4, separators=(',', ': '), sort_keys=sort, cls=encoder ) else: data = json.dumps( val, separators=(',',...