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 add_config(): """ Prompts user for API keys, adds them in an .ini file stored in the same location as that of the script """
genius_key = input('Enter Genius key : ') bing_key = input('Enter Bing key : ') CONFIG['keys']['bing_key'] = bing_key CONFIG['keys']['genius_key'] = genius_key with open(config_path, 'w') as configfile: CONFIG.write(configfile)
<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_tracks_from_album(album_name): ''' Gets tracks from an album using Spotify's API ''' spotify = spotipy.Spotify() album = spotify.search(q='album:' + album_name, limit=1) album_id = album['tracks']['items'][0]['album']['id'] results = spotify.album_tracks(album_id=str(album_id)) songs = [] for items in results['items']: songs.append(items['name']) return songs
<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_url(song_input, auto): ''' Provides user with a list of songs to choose from returns the url of chosen song. ''' youtube_list = OrderedDict() num = 0 # List of songs index html = requests.get("https://www.youtube.com/results", params={'search_query': song_input}) soup = BeautifulSoup(html.text, 'html.parser') # In all Youtube Search Results for i in soup.findAll('a', {'rel': YOUTUBECLASS}): song_url = 'https://www.youtube.com' + (i.get('href')) song_title = (i.get('title')) # Adds title and song url to dictionary youtube_list.update({song_title: song_url}) if not auto: print('(%s) %s' % (str(num + 1), song_title)) # Prints list num = num + 1 elif auto: print(song_title) return list(youtube_list.values())[0], list(youtube_list.keys())[0] # Checks if YouTube search return no results if youtube_list == {}: log.log_error('No match found!') exit() # Gets the demanded song title and url song_url, song_title = prompt(youtube_list) return song_url, song_title
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def prompt(youtube_list): ''' Prompts for song number from list of songs ''' option = int(input('\nEnter song number > ')) try: song_url = list(youtube_list.values())[option - 1] song_title = list(youtube_list.keys())[option - 1] except IndexError: log.log_error('Invalid Input') exit() system('clear') print('Download Song: ') print(song_title) print('Y/n?') confirm = input('>') if confirm == '' or confirm.lower() == 'y': pass elif confirm.lower() == 'n': exit() else: log.log_error('Invalid Input') exit() return song_url, song_title
<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(): ''' Starts here, handles arguments ''' system('clear') # Must be system('cls') for windows setup() parser = argparse.ArgumentParser( description='Download songs with album art and metadata!') parser.add_argument('-c', '--config', action='store_true', help='Set your API keys') parser.add_argument('-m', '--multiple', action='store', dest='multiple_file', help='Download multiple songs from a text file list') parser.add_argument('-a', '--auto', action='store_true', help='Automatically chooses top result') parser.add_argument('--album', action='store_true', help='Downloads all songs from an album') args = parser.parse_args() arg_multiple = args.multiple_file or None arg_auto = args.auto or None arg_album = args.album or None arg_config = args.config if arg_config: add_config() elif arg_multiple and arg_album: log.log_error("Can't do both!") elif arg_album: album_name = input('Enter album name : ') try: tracks = get_tracks_from_album(album_name) for songs in tracks: print(songs) confirm = input( '\nAre these the songs you want to download? (Y/n)\n> ') except IndexError: log.log_error("Couldn't find album") exit() if confirm == '' or confirm.lower() == ('y'): for track_name in tracks: track_name = track_name + ' song' song_url, file_name = get_url(track_name, arg_auto) download_song(song_url, file_name) system('clear') repair.fix_music(file_name + '.mp3') elif confirm.lower() == 'n': log.log_error("Sorry, if appropriate results weren't found") exit() else: log.log_error('Invalid Input') exit() elif arg_multiple: with open(arg_multiple, "r") as f: file_names = [] for line in f: file_names.append(line.rstrip('\n')) for files in file_names: files = files + ' song' song_url, file_name = get_url(files, arg_auto) download_song(song_url, file_name) system('clear') repair.fix_music(file_name + '.mp3') else: query = input('Enter Song Name : ') song_url, file_name = get_url(query, arg_auto) # Gets YT url download_song(song_url, file_name) # Saves as .mp3 file system('clear') repair.fix_music(file_name + '.mp3')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getRawReportDescriptor(self): """ Return a binary string containing the raw HID report descriptor. """
descriptor = _hidraw_report_descriptor() size = ctypes.c_uint() self._ioctl(_HIDIOCGRDESCSIZE, size, True) descriptor.size = size self._ioctl(_HIDIOCGRDESC, descriptor, True) return ''.join(chr(x) for x in descriptor.value[:size.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 getName(self, length=512): """ Returns device name as an unicode object. """
name = ctypes.create_string_buffer(length) self._ioctl(_HIDIOCGRAWNAME(length), name, True) return name.value.decode('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 getPhysicalAddress(self, length=512): """ Returns device physical address as a string. See hidraw documentation for value signification, as it depends on device's bus type. """
name = ctypes.create_string_buffer(length) self._ioctl(_HIDIOCGRAWPHYS(length), name, True) return name.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 sendFeatureReport(self, report, report_num=0): """ Send a feature report. """
length = len(report) + 1 buf = bytearray(length) buf[0] = report_num buf[1:] = report self._ioctl( _HIDIOCSFEATURE(length), (ctypes.c_char * length).from_buffer(buf), 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 every(coro, iterable, limit=1, loop=None): """ Returns `True` if every element in a given iterable satisfies the coroutine asynchronous test. If any iteratee coroutine call returns `False`, the process is inmediately stopped, and `False` will be returned. You can increase the concurrency limit for a fast race condition scenario. This function is a coroutine. This function can be composed in a pipeline chain with ``|`` operator. Arguments: coro (coroutine function): coroutine function to call with values to reduce. iterable (iterable): an iterable collection yielding coroutines functions. limit (int): max concurrency execution limit. Use ``0`` for no limit. loop (asyncio.BaseEventLoop): optional event loop to use. Raises: TypeError: if input arguments are not valid. Returns: bool: `True` if all the values passes the test, otherwise `False`. Usage:: async def gt_10(num): return num > 10 await paco.every(gt_10, [1, 2, 3, 11]) # => False await paco.every(gt_10, [11, 12, 13]) # => True """
assert_corofunction(coro=coro) assert_iter(iterable=iterable) # Reduced accumulator value passes = True # Handle empty iterables if len(iterable) == 0: return passes # Create concurrent executor pool = ConcurrentExecutor(limit=limit, loop=loop) # Tester function to guarantee the file is canceled. @asyncio.coroutine def tester(element): nonlocal passes if not passes: return None if not (yield from coro(element)): # Flag as not test passed passes = False # Force ignoring pending coroutines pool.cancel() # Iterate and attach coroutine for defer scheduling for element in iterable: pool.add(partial(tester, element)) # Wait until all coroutines finish yield from pool.run() return passes
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gather(*coros_or_futures, limit=0, loop=None, timeout=None, preserve_order=False, return_exceptions=False): """ Return a future aggregating results from the given coroutine objects with a concurrency execution limit. If all the tasks are done successfully, the returned future’s result is the list of results (in the order of the original sequence, not necessarily the order of results arrival). If return_exceptions is `True`, exceptions in the tasks are treated the same as successful results, and gathered in the result list; otherwise, the first raised exception will be immediately propagated to the returned future. All futures must share the same event loop. This functions is mostly compatible with Python standard ``asyncio.gather``, but providing ordered results and concurrency control flow. This function is a coroutine. Arguments: *coros_or_futures (coroutines|list): an iterable collection yielding coroutines functions or futures. limit (int): max concurrency limit. Use ``0`` for no limit. timeout can be used to control the maximum number of seconds to wait before returning. timeout can be an int or float. If timeout is not specified or None, there is no limit to the wait time. preserve_order (bool): preserves results order. return_exceptions (bool): returns exceptions as valid results. loop (asyncio.BaseEventLoop): optional event loop to use. Returns: list: coroutines returned results. Usage:: async def sum(x, y): return x + y await paco.gather( sum(1, 2), sum(None, 'str'), return_exceptions=True) # => [3, TypeError("unsupported operand type(s) for +: 'NoneType' and 'str'")] # noqa """
# If no coroutines to schedule, return empty list (as Python stdlib) if len(coros_or_futures) == 0: return [] # Support iterable as first argument for better interoperability if len(coros_or_futures) == 1 and isiter(coros_or_futures[0]): coros_or_futures = coros_or_futures[0] # Pre-initialize results results = [None] * len(coros_or_futures) if preserve_order else [] # Create concurrent executor pool = ConcurrentExecutor(limit=limit, loop=loop) # Iterate and attach coroutine for defer scheduling for index, coro in enumerate(coros_or_futures): # Validate coroutine object if asyncio.iscoroutinefunction(coro): coro = coro() if not asyncio.iscoroutine(coro): raise TypeError( 'paco: only coroutines or coroutine functions allowed') # Add coroutine to the executor pool pool.add(collect(coro, index, results, preserve_order=preserve_order, return_exceptions=return_exceptions)) # Wait until all the tasks finishes yield from pool.run(timeout=timeout, return_exceptions=return_exceptions) # Returns aggregated results return results
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def timeout(coro, timeout=None, loop=None): """ Wraps a given coroutine function, that when executed, if it takes more than the given timeout in seconds to execute, it will be canceled and raise an `asyncio.TimeoutError`. This function is equivalent to Python standard `asyncio.wait_for()` function. This function can be used as decorator. Arguments: coro (coroutinefunction|coroutine): coroutine to wrap. timeout (int|float): max wait timeout in seconds. loop (asyncio.BaseEventLoop): optional event loop to use. Raises: TypeError: if coro argument is not a coroutine function. Returns: coroutinefunction: wrapper coroutine function. Usage:: await paco.timeout(coro, timeout=10) """
@asyncio.coroutine def _timeout(coro): return (yield from asyncio.wait_for(coro, timeout, loop=loop)) @asyncio.coroutine def wrapper(*args, **kw): return (yield from _timeout(coro(*args, **kw))) return _timeout(coro) if asyncio.iscoroutine(coro) else 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 race(iterable, loop=None, timeout=None, *args, **kw): """ Runs coroutines from a given iterable concurrently without waiting until the previous one has completed. Once any of the tasks completes, the main coroutine is immediately resolved, yielding the first resolved value. All coroutines will be executed in the same loop. This function is a coroutine. Arguments: iterable (iterable): an iterable collection yielding coroutines functions or coroutine objects. *args (mixed): mixed variadic arguments to pass to coroutines. loop (asyncio.BaseEventLoop): optional event loop to use. timeout (int|float): timeout can be used to control the maximum number of seconds to wait before returning. timeout can be an int or float. If timeout is not specified or None, there is no limit to the wait time. *args (mixed): optional variadic argument to pass to coroutine function, if provided. Raises: TypeError: if ``iterable`` argument is not iterable. asyncio.TimoutError: if wait timeout is exceeded. Returns: filtered values (list): ordered list of resultant values. Usage:: async def coro1(): await asyncio.sleep(2) return 1 async def coro2(): return 2 async def coro3(): await asyncio.sleep(1) return 3 await paco.race([coro1, coro2, coro3]) # => 2 """
assert_iter(iterable=iterable) # Store coros and internal state coros = [] resolved = False result = None # Resolve first yielded data from coroutine and stop pending ones @asyncio.coroutine def resolver(index, coro): nonlocal result nonlocal resolved value = yield from coro if not resolved: resolved = True # Flag as not test passed result = value # Force canceling pending coroutines for _index, future in enumerate(coros): if _index != index: future.cancel() # Iterate and attach coroutine for defer scheduling for index, coro in enumerate(iterable): # Validate yielded object isfunction = asyncio.iscoroutinefunction(coro) if not isfunction and not asyncio.iscoroutine(coro): raise TypeError( 'paco: coro must be a coroutine or coroutine function') # Init coroutine function, if required if isfunction: coro = coro(*args, **kw) # Store future tasks coros.append(ensure_future(resolver(index, coro))) # Run coroutines concurrently yield from asyncio.wait(coros, timeout=timeout, loop=loop) 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 overload(fn): """ Overload a given callable object to be used with ``|`` operator overloading. This is especially used for composing a pipeline of transformation over a single data set. Arguments: fn (function): target function to decorate. Raises: TypeError: if function or coroutine function is not provided. Returns: function: decorated function """
if not isfunction(fn): raise TypeError('paco: fn must be a callable object') spec = getargspec(fn) args = spec.args if not spec.varargs and (len(args) < 2 or args[1] != 'iterable'): raise ValueError('paco: invalid function signature or arity') @functools.wraps(fn) def decorator(*args, **kw): # Check function arity if len(args) < 2: return PipeOverloader(fn, args, kw) # Otherwise, behave like a normal wrapper return fn(*args, **kw) return decorator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def consume(generator): # pragma: no cover """ Helper function to consume a synchronous or asynchronous generator. Arguments: generator (generator|asyncgenerator): generator to consume. Returns: list """
# If synchronous generator, just consume and return as list if hasattr(generator, '__next__'): return list(generator) if not PY_35: raise RuntimeError( 'paco: asynchronous iterator protocol not supported') # If asynchronous generator, consume it generator protocol manually buf = [] while True: try: buf.append((yield from generator.__anext__())) except StopAsyncIteration: # noqa break return buf
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def isfunc(x): """ Returns `True` if the given value is a function or method object. Arguments: x (mixed): value to check. Returns: bool """
return any([ inspect.isfunction(x) and not asyncio.iscoroutinefunction(x), inspect.ismethod(x) and not asyncio.iscoroutinefunction(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 assert_corofunction(**kw): """ Asserts if a given values are a coroutine function. Arguments: **kw (mixed): value to check if it is an iterable. Raises: TypeError: if assertion fails. """
for name, value in kw.items(): if not asyncio.iscoroutinefunction(value): raise TypeError( 'paco: {} must be a coroutine function'.format(name))
<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_iter(**kw): """ Asserts if a given values implements a valid iterable interface. Arguments: **kw (mixed): value to check if it is an iterable. Raises: TypeError: if assertion fails. """
for name, value in kw.items(): if not isiter(value): raise TypeError( 'paco: {} must be an iterable object'.format(name))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def interval(coro, interval=1, times=None, loop=None): """ Schedules the execution of a coroutine function every `x` amount of seconds. The function returns an `asyncio.Task`, which implements also an `asyncio.Future` interface, allowing the user to cancel the execution cycle. This function can be used as decorator. Arguments: coro (coroutinefunction): coroutine function to defer. interval (int/float): number of seconds to repeat the coroutine execution. times (int): optional maximum time of executions. Infinite by default. loop (asyncio.BaseEventLoop, optional): loop to run. Defaults to asyncio.get_event_loop(). Raises: TypeError: if coro argument is not a coroutine function. Returns: future (asyncio.Task): coroutine wrapped as task future. Useful for cancellation and state checking. Usage:: # Usage as function future = paco.interval(coro, 1) await asyncio.sleep(5) future.cancel() # Usage as decorator @paco.interval(10) async def metrics(): await send_metrics() future = await metrics() """
assert_corofunction(coro=coro) # Store maximum allowed number of calls times = int(times or 0) or float('inf') @asyncio.coroutine def schedule(times, *args, **kw): while times > 0: # Decrement times counter times -= 1 # Schedule coroutine yield from coro(*args, **kw) yield from asyncio.sleep(interval) def wrapper(*args, **kw): return ensure_future(schedule(times, *args, **kw), loop=loop) 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 addRule(self, doc, func, _preprocess=True): """Add a grammar rules to _self.rules_, _self.rule2func_, and _self.rule2name_ Comments, lines starting with # and blank lines are stripped from doc. We also allow limited form of * and + when there it is of the RHS has a single item, e.g. stmts ::= stmt+ """
fn = func # remove blanks lines and comment lines, e.g. lines starting with "#" doc = os.linesep.join([s for s in doc.splitlines() if s and not re.match("^\s*#", s)]) rules = doc.split() index = [] for i in range(len(rules)): if rules[i] == '::=': index.append(i-1) index.append(len(rules)) for i in range(len(index)-1): lhs = rules[index[i]] rhs = rules[index[i]+2:index[i+1]] rule = (lhs, tuple(rhs)) if _preprocess: rule, fn = self.preprocess(rule, func) # Handle a stripped-down form of *, +, and ?: # allow only one nonterminal on the right-hand side if len(rule[1]) == 1: if rule[1][0] == rule[0]: raise TypeError("Complete recursive rule %s" % rule2str(rule)) repeat = rule[1][-1][-1] if repeat in ('*', '+', '?'): nt = rule[1][-1][:-1] if repeat == '?': new_rule_pair = [rule[0], list((nt,))] self.optional_nt.add(rule[0]) else: self.list_like_nt.add(rule[0]) new_rule_pair = [rule[0], [rule[0]] + list((nt,))] new_rule = rule2str(new_rule_pair) self.addRule(new_rule, func, _preprocess) if repeat == '+': second_rule_pair = (lhs, (nt,)) else: second_rule_pair = (lhs, tuple()) new_rule = rule2str(second_rule_pair) self.addRule(new_rule, func, _preprocess) continue if lhs in self.rules: if rule in self.rules[lhs]: if 'dups' in self.debug and self.debug['dups']: self.duplicate_rule(rule) continue self.rules[lhs].append(rule) else: self.rules[lhs] = [ rule ] self.rule2func[rule] = fn self.rule2name[rule] = func.__name__[2:] self.ruleschanged = True # Note: In empty rules, i.e. len(rule[1] == 0, we don't # call reductions on explicitly. Instead it is computed # implicitly. if self.profile_info is not None and len(rule[1]) > 0: rule_str = self.reduce_string(rule) if rule_str not in self.profile_info: self.profile_info[rule_str] = 0 pass return
<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_rules(self, doc): """Remove a grammar rules from _self.rules_, _self.rule2func_, and _self.rule2name_ """
# remove blanks lines and comment lines, e.g. lines starting with "#" doc = os.linesep.join([s for s in doc.splitlines() if s and not re.match("^\s*#", s)]) rules = doc.split() index = [] for i in range(len(rules)): if rules[i] == '::=': index.append(i-1) index.append(len(rules)) for i in range(len(index)-1): lhs = rules[index[i]] rhs = rules[index[i]+2:index[i+1]] rule = (lhs, tuple(rhs)) if lhs not in self.rules: return if rule in self.rules[lhs]: self.rules[lhs].remove(rule) del self.rule2func[rule] del self.rule2name[rule] self.ruleschanged = True # If we are profiling, remove this rule from that as well if self.profile_info is not None and len(rule[1]) > 0: rule_str = self.reduce_string(rule) if rule_str and rule_str in self.profile_info: del self.profile_info[rule_str] pass pass pass return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def errorstack(self, tokens, i, full=False): """Show the stacks of completed symbols. We get this by inspecting the current transitions possible and from that extracting the set of states we are in, and from there we look at the set of symbols before the "dot". If full is True, we show the entire rule with the dot placement. Otherwise just the rule up to the dot. """
print("\n-- Stacks of completed symbols:") states = [s for s in self.edges.values() if s] # States now has the set of states we are in state_stack = set() for state in states: # Find rules which can follow, but keep only # the part before the dot for rule, dot in self.states[state].items: lhs, rhs = rule if dot > 0: if full: state_stack.add( "%s ::= %s . %s" % (lhs, ' '.join(rhs[:dot]), ' '.join(rhs[dot:]))) else: state_stack.add( "%s ::= %s" % (lhs, ' '.join(rhs[:dot]))) pass pass pass for stack in sorted(state_stack): print(stack)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse(self, tokens, debug=None): """This is the main entry point from outside. Passing in a debug dictionary changes the default debug setting. """
self.tokens = tokens if debug: self.debug = debug sets = [ [(1, 0), (2, 0)] ] self.links = {} if self.ruleschanged: self.computeNull() self.newrules = {} self.new2old = {} self.makeNewRules() self.ruleschanged = False self.edges, self.cores = {}, {} self.states = { 0: self.makeState0() } self.makeState(0, self._BOF) for i in range(len(tokens)): sets.append([]) if sets[i] == []: break self.makeSet(tokens, sets, i) else: sets.append([]) self.makeSet(None, sets, len(tokens)) finalitem = (self.finalState(tokens), 0) if finalitem not in sets[-2]: if len(tokens) > 0: if self.debug.get('errorstack', False): self.errorstack(tokens, i-1, str(self.debug['errorstack']) == 'full') self.error(tokens, i-1) else: self.error(None, None) if self.profile_info is not None: self.dump_profile_info() return self.buildTree(self._START, finalitem, tokens, len(sets)-2)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dump_grammar(self, out=sys.stdout): """ Print grammar rules """
for rule in sorted(self.rule2name.items()): out.write("%s\n" % rule2str(rule[0])) return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def profile_rule(self, rule): """Bump count of the number of times _rule_ was used"""
rule_str = self.reduce_string(rule) if rule_str not in self.profile_info: self.profile_info[rule_str] = 1 else: self.profile_info[rule_str] += 1
<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_profile_info(self): """Show the accumulated results of how many times each rule was used"""
return sorted(self.profile_info.items(), key=lambda kv: kv[1], reverse=False) return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def partial(coro, *args, **kw): """ Partial function implementation designed for coroutines, allowing variadic input arguments. This function can be used as decorator. arguments: coro (coroutinefunction): coroutine function to wrap. *args (mixed): mixed variadic arguments for partial application. Raises: TypeError: if ``coro`` is not a coroutine function. Returns: coroutinefunction Usage:: async def pow(x, y): return x ** y pow_2 = paco.partial(pow, 2) await pow_2(4) # => 16 """
assert_corofunction(coro=coro) @asyncio.coroutine def wrapper(*_args, **_kw): call_args = args + _args kw.update(_kw) return (yield from coro(*call_args, **kw)) 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 eval_expr(expr_str, show_tokens=False, showast=False, showgrammar=False, compile_mode='exec'): """ evaluate simple expression """
parser_debug = {'rules': False, 'transition': False, 'reduce': showgrammar, 'errorstack': True, 'context': True } parsed = parse_expr(expr_str, show_tokens=show_tokens, parser_debug=parser_debug) if showast: print(parsed) assert parsed == 'expr', 'Should have parsed grammar start' evaluator = ExprEvaluator() # What we've been waiting for: Generate source from AST! return evaluator.traverse(parsed)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setup(): """ Gathers all configs """
global CONFIG, BING_KEY, GENIUS_KEY, config_path, LOG_FILENAME, LOG_LINE_SEPERATOR LOG_FILENAME = 'musicrepair_log.txt' LOG_LINE_SEPERATOR = '........................\n' CONFIG = configparser.ConfigParser() config_path = realpath(__file__).replace(basename(__file__),'') config_path = config_path + 'config.ini' CONFIG.read(config_path) GENIUS_KEY = CONFIG['keys']['genius_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 matching_details(song_name, song_title, artist): ''' Provides a score out of 10 that determines the relevance of the search result ''' match_name = difflib.SequenceMatcher(None, song_name, song_title).ratio() match_title = difflib.SequenceMatcher(None, song_name, artist + song_title).ratio() if max(match_name,match_title) >= 0.55: return True, max(match_name,match_title) else: return False, (match_name + match_title) / 2
<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_lyrics_letssingit(song_name): ''' Scrapes the lyrics of a song since spotify does not provide lyrics takes song title as arguement ''' lyrics = "" url = "http://search.letssingit.com/cgi-exe/am.cgi?a=search&artist_id=&l=archive&s=" + \ quote(song_name.encode('utf-8')) html = urlopen(url).read() soup = BeautifulSoup(html, "html.parser") link = soup.find('a', {'class': 'high_profile'}) try: link = link.get('href') link = urlopen(link).read() soup = BeautifulSoup(link, "html.parser") try: lyrics = soup.find('div', {'id': 'lyrics'}).text lyrics = lyrics[3:] except AttributeError: lyrics = "" except: lyrics = "" return lyrics
<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_details_letssingit(song_name): ''' Gets the song details if song details not found through spotify ''' song_name = improvename.songname(song_name) url = "http://search.letssingit.com/cgi-exe/am.cgi?a=search&artist_id=&l=archive&s=" + \ quote(song_name.encode('utf-8')) html = urlopen(url).read() soup = BeautifulSoup(html, "html.parser") link = soup.find('a', {'class': 'high_profile'}) try: link = link.get('href') link = urlopen(link).read() soup = BeautifulSoup(link, "html.parser") album_div = soup.find('div', {'id': 'albums'}) title_div = soup.find('div', {'id': 'content_artist'}).find('h1') try: lyrics = soup.find('div', {'id': 'lyrics'}).text lyrics = lyrics[3:] except AttributeError: lyrics = "" log.log_error("* Couldn't find lyrics", indented=True) try: song_title = title_div.contents[0] song_title = song_title[1:-8] except AttributeError: log.log_error("* Couldn't reset song title", indented=True) song_title = song_name try: artist = title_div.contents[1].getText() except AttributeError: log.log_error("* Couldn't find artist name", indented=True) artist = "Unknown" try: album = album_div.find('a').contents[0] album = album[:-7] except AttributeError: log.log_error("* Couldn't find the album name", indented=True) album = artist except AttributeError: log.log_error("* Couldn't find song details", indented=True) album = song_name song_title = song_name artist = "Unknown" lyrics = "" match_bool, score = matching_details(song_name, song_title, artist) return artist, album, song_title, lyrics, match_bool, score
<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_albumart(albumart, song_title): ''' Adds the album art to the song ''' try: img = urlopen(albumart) # Gets album art from url except Exception: log.log_error("* Could not add album art", indented=True) return None audio = EasyMP3(song_title, ID3=ID3) try: audio.add_tags() except _util.error: pass audio.tags.add( APIC( encoding=3, # UTF-8 mime='image/png', type=3, # 3 is for album art desc='Cover', data=img.read() # Reads and adds album art ) ) audio.save() log.log("> Added album 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 add_details(file_name, title, artist, album, lyrics=""): ''' Adds the details to song ''' tags = EasyMP3(file_name) tags["title"] = title tags["artist"] = artist tags["album"] = album tags.save() tags = ID3(file_name) uslt_output = USLT(encoding=3, lang=u'eng', desc=u'desc', text=lyrics) tags["USLT::'eng'"] = uslt_output tags.save(file_name) log.log("> Adding properties") log.log_indented("[*] Title: %s" % title) log.log_indented("[*] Artist: %s" % artist) log.log_indented("[*] Album: %s " % album)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def map(coro, iterable, limit=0, loop=None, timeout=None, return_exceptions=False, *args, **kw): """ Concurrently maps values yielded from an iterable, passing then into an asynchronous coroutine function. Mapped values will be returned as list. Items order will be preserved based on origin iterable order. Concurrency level can be configurable via ``limit`` param. This function is the asynchronous equivalent port Python built-in `map()` function. This function is a coroutine. This function can be composed in a pipeline chain with ``|`` operator. Arguments: coro (coroutinefunction): map coroutine function to use. iterable (iterable|asynchronousiterable): an iterable collection yielding coroutines functions. limit (int): max concurrency limit. Use ``0`` for no limit. loop (asyncio.BaseEventLoop): optional event loop to use. timeout (int|float): timeout can be used to control the maximum number of seconds to wait before returning. timeout can be an int or float. If timeout is not specified or None, there is no limit to the wait time. return_exceptions (bool): returns exceptions as valid results. *args (mixed): optional variadic arguments to be passed to the coroutine map function. Returns: list: ordered list of values yielded by coroutines Usage:: async def mul_2(num): return num * 2 await paco.map(mul_2, [1, 2, 3, 4, 5]) # => [2, 4, 6, 8, 10] """
# Call each iterable but collecting yielded values return (yield from each(coro, iterable, limit=limit, loop=loop, timeout=timeout, collect=True, return_exceptions=return_exceptions))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def img_search_bing(album): ''' Bing image search ''' setup() album = album + " Album Art" api_key = "Key" endpoint = "https://api.cognitive.microsoft.com/bing/v5.0/images/search" links_dict = {} headers = {'Ocp-Apim-Subscription-Key': str(BING_KEY)} param = {'q': album, 'count': '1'} response = requests.get(endpoint, headers=headers, params=param) response = response.json() key = 0 try: for i in response['value']: links_dict[str(key)] = str((i['contentUrl'])) key = key + 1 return links_dict["0"] except KeyError: return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decorate(fn): """ Generic decorator for coroutines helper functions allowing multiple variadic initialization arguments. This function is intended to be used internally. Arguments: fn (function): target function to decorate. Raises: TypeError: if function or coroutine function is not provided. Returns: function: decorated function. """
if not isfunction(fn): raise TypeError('paco: fn must be a callable object') @functools.wraps(fn) def decorator(*args, **kw): # If coroutine object is passed for arg in args: if iscoro_or_corofunc(arg): return fn(*args, **kw) # Explicit argument must be at least a coroutine if len(args) and args[0] is None: raise TypeError('paco: first argument cannot be empty') def wrapper(coro, *_args, **_kw): # coro must be a valid type if not iscoro_or_corofunc(coro): raise TypeError('paco: first argument must be a ' 'coroutine or coroutine function') # Merge call arguments _args = ((coro,) + (args + _args)) kw.update(_kw) # Trigger original decorated function return fn(*_args, **kw) return wrapper return decorator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def throttle(coro, limit=1, timeframe=1, return_value=None, raise_exception=False): """ Creates a throttled coroutine function that only invokes ``coro`` at most once per every time frame of seconds or milliseconds. Provide options to indicate whether func should be invoked on the leading and/or trailing edge of the wait timeout. Subsequent calls to the throttled coroutine return the result of the last coroutine invocation. This function can be used as decorator. Arguments: coro (coroutinefunction): coroutine function to wrap with throttle strategy. limit (int): number of coroutine allowed execution in the given time frame. timeframe (int|float): throttle limit time frame in seconds. return_value (mixed): optional return if the throttle limit is reached. Returns the latest returned value by default. raise_exception (bool): raise exception if throttle limit is reached. Raises: RuntimeError: if cannot throttle limit reached (optional). Returns: coroutinefunction Usage:: async def mul_2(num): return num * 2 # Use as simple wrapper throttled = paco.throttle(mul_2, limit=1, timeframe=2) await throttled(2) # => 4 await throttled(3) # ignored! # => 4 await asyncio.sleep(2) await throttled(3) # executed! # => 6 # Use as decorator @paco.throttle(limit=1, timeframe=2) async def mul_2(num): return num * 2 await mul_2(2) # => 4 await mul_2(3) # ignored! # => 4 await asyncio.sleep(2) await mul_2(3) # executed! # => 6 """
assert_corofunction(coro=coro) # Store execution limits limit = max(int(limit), 1) remaning = limit # Turn seconds in milliseconds timeframe = timeframe * 1000 # Keep call state last_call = now() # Cache latest retuned result result = None def stop(): if raise_exception: raise RuntimeError('paco: coroutine throttle limit exceeded') if return_value: return return_value return result def elapsed(): return now() - last_call @asyncio.coroutine def wrapper(*args, **kw): nonlocal result nonlocal remaning nonlocal last_call if elapsed() > timeframe: # Reset reamining calls counter remaning = limit # Update last call time last_call = now() elif elapsed() < timeframe and remaning <= 0: return stop() # Decrease remaining limit remaning -= 1 # Schedule coroutine passing arguments and cache result result = yield from coro(*args, **kw) return result 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 whilst(coro, coro_test, assert_coro=None, *args, **kw): """ Repeatedly call `coro` coroutine function while `coro_test` returns `True`. This function is the inverse of `paco.until()`. This function is a coroutine. Arguments: coro (coroutinefunction): coroutine function to execute. coro_test (coroutinefunction): coroutine function to test. assert_coro (coroutinefunction): optional assertion coroutine used to determine if the test passed or not. *args (mixed): optional variadic arguments to pass to `coro` function. Raises: TypeError: if input arguments are invalid. Returns: list: result values returned by `coro`. Usage:: calls = 0 async def task(): nonlocal calls calls += 1 return calls async def calls_lt_4(): return calls > 4 await paco.until(task, calls_lt_4) # => [1, 2, 3, 4, 5] """
assert_corofunction(coro=coro, coro_test=coro_test) # Store yielded values by coroutine results = [] # Set assertion coroutine assert_coro = assert_coro or assert_true # Execute coroutine until a certain while (yield from assert_coro((yield from coro_test()))): results.append((yield from coro(*args, **kw))) return results
<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_csv(ctx, model, path, header=None, header_exclude=None, **fmtparams): """Load a CSV from a file path. :param ctx: Anthem context :param model: Odoo model name or model klass from env :param path: absolute or relative path to CSV file. If a relative path is given you must provide a value for `ODOO_DATA_PATH` in your environment or set `--odoo-data-path` option. :param header: whitelist of CSV columns to load :param header_exclude: blacklist of CSV columns to not load :param fmtparams: keyword params for `csv_unireader` Usage example:: from pkg_resources import Requirement, resource_string req = Requirement.parse('my-project') load_csv(ctx, ctx.env['res.users'], resource_string(req, 'data/users.csv'), delimiter=',') """
if not os.path.isabs(path): if ctx.options.odoo_data_path: path = os.path.join(ctx.options.odoo_data_path, path) else: raise AnthemError( 'Got a relative path. ' 'Please, provide a value for `ODOO_DATA_PATH` ' 'in your environment or set `--odoo-data-path` option.' ) with open(path, 'rb') as data: load_csv_stream(ctx, model, data, header=header, header_exclude=header_exclude, **fmtparams)
<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_csv_stream(ctx, model, data, header=None, header_exclude=None, **fmtparams): """Load a CSV from a stream. :param ctx: current anthem context :param model: model name as string or model klass :param data: csv data to load :param header: csv fieldnames whitelist :param header_exclude: csv fieldnames blacklist Usage example:: from pkg_resources import Requirement, resource_stream req = Requirement.parse('my-project') load_csv_stream(ctx, ctx.env['res.users'], resource_stream(req, 'data/users.csv'), delimiter=',') """
_header, _rows = read_csv(data, **fmtparams) header = header if header else _header if _rows: # check if passed header contains all the fields if header != _header and not header_exclude: # if not, we exclude the rest of the fields header_exclude = [x for x in _header if x not in header] if header_exclude: # exclude fields from header as well as respective values header = [x for x in header if x not in header_exclude] # we must loop trough all the rows too to pop values # since odoo import works only w/ reader and not w/ dictreader pop_idxs = [_header.index(x) for x in header_exclude] rows = [] for i, row in enumerate(_rows): rows.append( [x for j, x in enumerate(row) if j not in pop_idxs] ) else: rows = list(_rows) if rows: load_rows(ctx, model, header, rows)
<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_python2_stmts(python_stmts, show_tokens=False, showast=False, showgrammar=False, compile_mode='exec'): """ formats python2 statements """
parser_debug = {'rules': False, 'transition': False, 'reduce': showgrammar, 'errorstack': True, 'context': True, 'dups': True } parsed = parse_python2(python_stmts, show_tokens=show_tokens, parser_debug=parser_debug) assert parsed == 'file_input', 'Should have parsed grammar start' formatter = Python2Formatter() if showast: print(parsed) # What we've been waiting for: Generate source from AST! python2_formatted_str = formatter.traverse(parsed) return python2_formatted_str
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def songname(song_name): ''' Improves file name by removing crap words ''' try: song_name = splitext(song_name)[0] except IndexError: pass # Words to omit from song title for better results through spotify's API chars_filter = "()[]{}-:_/=+\"\'" words_filter = ('official', 'lyrics', 'audio', 'remixed', 'remix', 'video', 'full', 'version', 'music', 'mp3', 'hd', 'hq', 'uploaded') # Replace characters to filter with spaces song_name = ''.join(map(lambda c: " " if c in chars_filter else c, song_name)) # Remove crap words song_name = re.sub('|'.join(re.escape(key) for key in words_filter), "", song_name, flags=re.IGNORECASE) # Remove duplicate spaces song_name = re.sub(' +', ' ', song_name) return song_name.strip()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def document(info=None, input=None, output=None): """ Add extra information about request handler and its params """
def wrapper(func): if info is not None: setattr(func, "_swg_info", info) if input is not None: setattr(func, "_swg_input", input) if output is not None: setattr(func, "_swg_output", output) return func 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 thunk(coro): """ A thunk is a subroutine that is created, often automatically, to assist a call to another subroutine. Creates a thunk coroutine which returns coroutine function that accepts no arguments and when invoked it schedules the wrapper coroutine and returns the final result. See Wikipedia page for more information about Thunk subroutines: https://en.wikipedia.org/wiki/Thunk Arguments: value (coroutinefunction): wrapped coroutine function to invoke. Returns: coroutinefunction Usage:: async def task(): return 'foo' coro = paco.thunk(task) await coro() # => 'foo' await coro() # => 'foo' """
assert_corofunction(coro=coro) @asyncio.coroutine def wrapper(): return (yield from coro()) 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 reduce(coro, iterable, initializer=None, limit=1, right=False, loop=None): """ Apply function of two arguments cumulatively to the items of sequence, from left to right, so as to reduce the sequence to a single value. Reduction will be executed sequentially without concurrency, so passed values would be in order. This function is the asynchronous coroutine equivalent to Python standard `functools.reduce()` function. This function is a coroutine. This function can be composed in a pipeline chain with ``|`` operator. Arguments: coro (coroutine function): reducer coroutine binary function. iterable (iterable|asynchronousiterable): an iterable collection yielding coroutines functions. initializer (mixed): initial accumulator value used in the first reduction call. limit (int): max iteration concurrency limit. Use ``0`` for no limit. right (bool): reduce iterable from right to left. loop (asyncio.BaseEventLoop): optional event loop to use. Raises: TypeError: if input arguments are not valid. Returns: mixed: accumulated final reduced value. Usage:: async def reducer(acc, num): return acc + num await paco.reduce(reducer, [1, 2, 3, 4, 5], initializer=0) # => 15 """
assert_corofunction(coro=coro) assert_iter(iterable=iterable) # Reduced accumulator value acc = initializer # If interable is empty, just return the initializer value if len(iterable) == 0: return initializer # Create concurrent executor pool = ConcurrentExecutor(limit=limit, loop=loop) # Reducer partial function for deferred coroutine execution def reducer(element): @asyncio.coroutine def wrapper(): nonlocal acc acc = yield from coro(acc, element) return wrapper # Support right reduction if right: iterable.reverse() # Iterate and attach coroutine for defer scheduling for element in iterable: pool.add(reducer(element)) # Wait until all coroutines finish yield from pool.run(ignore_empty=True) # Returns final reduced value return acc
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def times(coro, limit=1, raise_exception=False, return_value=None): """ Wraps a given coroutine function to be executed only a certain amount of times. If the execution limit is exceeded, the last execution return value will be returned as result. You can optionally define a custom return value on exceeded via `return_value` param. This function can be used as decorator. arguments: coro (coroutinefunction): coroutine function to wrap. limit (int): max limit of coroutine executions. raise_exception (bool): raise exception if execution times exceeded. return_value (mixed): value to return when execution times exceeded. Raises: TypeError: if coro argument is not a coroutine function. RuntimeError: if max execution excedeed (optional). Returns: coroutinefunction Usage:: async def mul_2(num): return num * 2 timed = paco.times(mul_2, 3) await timed(2) # => 4 await timed(3) # => 6 await timed(4) # => 8 await timed(5) # ignored! # => 8 """
assert_corofunction(coro=coro) # Store call times limit = max(limit, 1) times = limit # Store result from last execution result = None @asyncio.coroutine def wrapper(*args, **kw): nonlocal limit nonlocal result # Check execution limit if limit == 0: if raise_exception: raise RuntimeError(ExceptionMessage.format(times)) if return_value: return return_value return result # Decreases counter limit -= 1 # If return_value is present, do not memoize result if return_value: return (yield from coro(*args, **kw)) # Schedule coroutine and memoize result result = yield from coro(*args, **kw) return result 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 log(func=None, name=None, timing=True, timestamp=False): """ Decorator to show a description of the running function By default, it outputs the first line of the docstring. If the docstring is empty, it displays the name of the function. Alternatively, if a ``name`` is specified, it will display that only. It can be called as ``@log`` or as ``@log(name='abc, timing=True, timestamp=True)``. """
# support to be called as @log or as @log(name='') if func is None: return functools.partial(log, name=name, timing=timing, timestamp=timestamp) @functools.wraps(func) def decorated(*args, **kwargs): assert len(args) > 0 and hasattr(args[0], 'log'), \ "The first argument of the decorated function must be a Context" ctx = args[0] message = name if message is None: if func.__doc__: message = func.__doc__.splitlines()[0].strip() if message is None: message = func.__name__ with ctx.log(message, timing=timing, timestamp=timestamp): return func(*args, **kwargs) return decorated
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def constant(value, delay=None): """ Returns a coroutine function that when called, always returns the provided value. This function has an alias: `paco.identity`. Arguments: value (mixed): value to constantly return when coroutine is called. delay (int/float): optional return value delay in seconds. Returns: coroutinefunction Usage:: coro = paco.constant('foo') await coro() # => 'foo' await coro() # => 'foo' """
@asyncio.coroutine def coro(): if delay: yield from asyncio.sleep(delay) return value return coro
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dropwhile(coro, iterable, loop=None): """ Make an iterator that drops elements from the iterable as long as the predicate is true; afterwards, returns every element. Note, the iterator does not produce any output until the predicate first becomes false, so it may have a lengthy start-up time. This function is pretty much equivalent to Python standard `itertools.dropwhile()`, but designed to be used with async coroutines. This function is a coroutine. This function can be composed in a pipeline chain with ``|`` operator. Arguments: coro (coroutine function): coroutine function to call with values to reduce. iterable (iterable|asynchronousiterable): an iterable collection yielding coroutines functions. loop (asyncio.BaseEventLoop): optional event loop to use. Raises: TypeError: if coro argument is not a coroutine function. Returns: filtered values (list): ordered list of resultant values. Usage:: async def filter(num): return num < 4 await paco.dropwhile(filter, [1, 2, 3, 4, 5, 1]) # => [4, 5, 1] """
drop = False @asyncio.coroutine def assert_fn(element): nonlocal drop if element and not drop: return False if not element and not drop: drop = True return True if drop else element @asyncio.coroutine def filter_fn(element): return (yield from coro(element)) return (yield from filter(filter_fn, iterable, assert_fn=assert_fn, limit=1, loop=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 add_xmlid(ctx, record, xmlid, noupdate=False): """ Add a XMLID on an existing record """
try: ref_id, __, __ = ctx.env['ir.model.data'].xmlid_lookup(xmlid) except ValueError: pass # does not exist, we'll create a new one else: return ctx.env['ir.model.data'].browse(ref_id) if '.' in xmlid: module, name = xmlid.split('.') else: module = '' name = xmlid return ctx.env['ir.model.data'].create({ 'name': name, 'module': module, 'model': record._name, 'res_id': record.id, 'noupdate': noupdate, })
<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_or_update(ctx, model, xmlid, values): """ Create or update a record matching xmlid with values """
if isinstance(model, basestring): model = ctx.env[model] record = ctx.env.ref(xmlid, raise_if_not_found=False) if record: record.update(values) else: record = model.create(values) add_xmlid(ctx, record, xmlid) return 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 safe_record(ctx, item): """Make sure we get a record instance even if we pass an xmlid."""
if isinstance(item, basestring): return ctx.env.ref(item) return item
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def switch_company(ctx, company): """Context manager to switch current company. Accepts both company record and xmlid. """
current_company = ctx.env.user.company_id ctx.env.user.company_id = safe_record(ctx, company) yield ctx ctx.env.user.company_id = current_company
<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(coro, *args, **kw): """ Creates a continuation coroutine function with some arguments already applied. Useful as a shorthand when combined with other control flow functions. Any arguments passed to the returned function are added to the arguments originally passed to apply. This is similar to `paco.partial()`. This function can be used as decorator. arguments: coro (coroutinefunction): coroutine function to wrap. *args (mixed): mixed variadic arguments for partial application. *kwargs (mixed): mixed variadic keyword arguments for partial application. Raises: TypeError: if coro argument is not a coroutine function. Returns: coroutinefunction: wrapped coroutine function. Usage:: async def hello(name, mark='!'): print('Hello, {name}{mark}'.format(name=name, mark=mark)) hello_mike = paco.apply(hello, 'Mike') await hello_mike() # => Hello, Mike! hello_mike = paco.apply(hello, 'Mike', mark='?') await hello_mike() # => Hello, Mike? """
assert_corofunction(coro=coro) @asyncio.coroutine def wrapper(*_args, **_kw): # Explicitely ignore wrapper arguments return (yield from coro(*args, **kw)) 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 run(coro, loop=None): """ Convenient shortcut alias to ``loop.run_until_complete``. Arguments: coro (coroutine): coroutine object to schedule. loop (asyncio.BaseEventLoop): optional event loop to use. Defaults to: ``asyncio.get_event_loop()``. Returns: mixed: returned value by coroutine. Usage:: async def mul_2(num): return num * 2 paco.run(mul_2(4)) # => 8 """
loop = loop or asyncio.get_event_loop() return loop.run_until_complete(coro)
<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(*coros_or_futures, limit=0, timeout=None, loop=None, return_exceptions=False, return_when='ALL_COMPLETED'): """ Wait for the Futures and coroutine objects given by the sequence futures to complete, with optional concurrency limit. Coroutines will be wrapped in Tasks. ``timeout`` can be used to control the maximum number of seconds to wait before returning. timeout can be an int or float. If timeout is not specified or None, there is no limit to the wait time. If ``return_exceptions`` is True, exceptions in the tasks are treated the same as successful results, and gathered in the result list; otherwise, the first raised exception will be immediately propagated to the returned future. ``return_when`` indicates when this function should return. It must be one of the following constants of the concurrent.futures module. All futures must share the same event loop. This functions is mostly compatible with Python standard ``asyncio.wait()``. Arguments: *coros_or_futures (iter|list): an iterable collection yielding coroutines functions. limit (int): optional concurrency execution limit. Use ``0`` for no limit. timeout (int/float): maximum number of seconds to wait before returning. return_exceptions (bool): exceptions in the tasks are treated the same as successful results, instead of raising them. return_when (str): indicates when this function should return. loop (asyncio.BaseEventLoop): optional event loop to use. *args (mixed): optional variadic argument to pass to the coroutines function. Returns: tuple: Returns two sets of Future: (done, pending). Raises: TypeError: in case of invalid coroutine object. ValueError: in case of empty set of coroutines or futures. TimeoutError: if execution takes more than expected. Usage:: async def sum(x, y): return x + y done, pending = await paco.wait( sum(1, 2), sum(3, 4)) [task.result() for task in done] # => [3, 7] """
# Support iterable as first argument for better interoperability if len(coros_or_futures) == 1 and isiter(coros_or_futures[0]): coros_or_futures = coros_or_futures[0] # If no coroutines to schedule, return empty list # Mimics asyncio behaviour. if len(coros_or_futures) == 0: raise ValueError('paco: set of coroutines/futures is empty') # Create concurrent executor pool = ConcurrentExecutor(limit=limit, loop=loop, coros=coros_or_futures) # Wait until all the tasks finishes return (yield from pool.run(timeout=timeout, return_when=return_when, return_exceptions=return_exceptions))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def series(*coros_or_futures, timeout=None, loop=None, return_exceptions=False): """ Run the given coroutine functions in series, each one running once the previous execution has completed. If any coroutines raises an exception, no more coroutines are executed. Otherwise, the coroutines returned values will be returned as `list`. ``timeout`` can be used to control the maximum number of seconds to wait before returning. timeout can be an int or float. If timeout is not specified or None, there is no limit to the wait time. If ``return_exceptions`` is True, exceptions in the tasks are treated the same as successful results, and gathered in the result list; otherwise, the first raised exception will be immediately propagated to the returned future. All futures must share the same event loop. This functions is basically the sequential execution version of ``asyncio.gather()``. Interface compatible with ``asyncio.gather()``. This function is a coroutine. Arguments: *coros_or_futures (iter|list): an iterable collection yielding coroutines functions. timeout (int/float): maximum number of seconds to wait before returning. return_exceptions (bool): exceptions in the tasks are treated the same as successful results, instead of raising them. loop (asyncio.BaseEventLoop): optional event loop to use. *args (mixed): optional variadic argument to pass to the coroutines function. Returns: list: coroutines returned results. Raises: TypeError: in case of invalid coroutine object. ValueError: in case of empty set of coroutines or futures. TimeoutError: if execution takes more than expected. Usage:: async def sum(x, y): return x + y await paco.series( sum(1, 2), sum(2, 3), sum(3, 4)) # => [3, 5, 7] """
return (yield from gather(*coros_or_futures, loop=loop, limit=1, timeout=timeout, return_exceptions=return_exceptions))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def repeat(coro, times=1, step=1, limit=1, loop=None): """ Executes the coroutine function ``x`` number of times, and accumulates results in order as you would use with ``map``. Execution concurrency is configurable using ``limit`` param. This function is a coroutine. Arguments: coro (coroutinefunction): coroutine function to schedule. times (int): number of times to execute the coroutine. step (int): increment iteration step, as with ``range()``. limit (int): concurrency execution limit. Defaults to 10. loop (asyncio.BaseEventLoop): optional event loop to use. Raises: TypeError: if coro is not a coroutine function. Returns: list: accumulated yielded values returned by coroutine. Usage:: async def mul_2(num): return num * 2 await paco.repeat(mul_2, times=5) # => [2, 4, 6, 8, 10] """
assert_corofunction(coro=coro) # Iterate and attach coroutine for defer scheduling times = max(int(times), 1) iterable = range(1, times + 1, step) # Run iterable times return (yield from map(coro, iterable, limit=limit, loop=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 once(coro, raise_exception=False, return_value=None): """ Wrap a given coroutine function that is restricted to one execution. Repeated calls to the coroutine function will return the value of the first invocation. This function can be used as decorator. arguments: coro (coroutinefunction): coroutine function to wrap. raise_exception (bool): raise exception if execution times exceeded. return_value (mixed): value to return when execution times exceeded, instead of the memoized one from last invocation. Raises: TypeError: if coro argument is not a coroutine function. Returns: coroutinefunction Usage:: async def mul_2(num): return num * 2 once = paco.once(mul_2) await once(2) # => 4 await once(3) # => 4 once = paco.once(mul_2, return_value='exceeded') await once(2) # => 4 await once(3) # => 'exceeded' """
return times(coro, limit=1, return_value=return_value, raise_exception=raise_exception)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def defer(coro, delay=1): """ Returns a coroutine function wrapper that will defer the given coroutine execution for a certain amount of seconds in a non-blocking way. This function can be used as decorator. Arguments: coro (coroutinefunction): coroutine function to defer. delay (int/float): number of seconds to defer execution. Raises: TypeError: if coro argument is not a coroutine function. Returns: filtered values (list): ordered list of resultant values. Usage:: # Usage as function await paco.defer(coro, delay=1) await paco.defer(coro, delay=0.5) # Usage as decorator @paco.defer(delay=1) async def mul_2(num): return num * 2 await mul_2(2) # => 4 """
assert_corofunction(coro=coro) @asyncio.coroutine def wrapper(*args, **kw): # Wait until we're done yield from asyncio.sleep(delay) return (yield from coro(*args, **kw)) 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 safe_run(coro, return_exceptions=False): """ Executes a given coroutine and optionally catches exceptions, returning them as value. This function is intended to be used internally. """
try: result = yield from coro except Exception as err: if return_exceptions: result = err else: raise err 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 collect(coro, index, results, preserve_order=False, return_exceptions=False): """ Collect is used internally to execute coroutines and collect the returned value. This function is intended to be used internally. """
result = yield from safe_run(coro, return_exceptions=return_exceptions) if preserve_order: results[index] = result else: results.append(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 reset(self): """ Resets the executer scheduler internal state. Raises: RuntimeError: is the executor is still running. """
if self.running: raise RuntimeError('paco: executor is still running') self.pool.clear() self.observer.clear() self.semaphore = asyncio.Semaphore(self.limit, loop=self.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 add(self, coro, *args, **kw): """ Adds a new coroutine function with optional variadic argumetns. Arguments: coro (coroutine function): coroutine to execute. *args (mixed): optional variadic arguments Raises: TypeError: if the coro object is not a valid coroutine Returns: future: coroutine wrapped future """
# Create coroutine object if a function is provided if asyncio.iscoroutinefunction(coro): coro = coro(*args, **kw) # Verify coroutine if not asyncio.iscoroutine(coro): raise TypeError('paco: coro must be a coroutine object') # Store coroutine with arguments for deferred execution index = max(len(self.pool), 0) task = Task(index, coro) # Append the coroutine data to the pool self.pool.append(task) return coro
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self, timeout=None, return_when=None, return_exceptions=None, ignore_empty=None): """ Executes the registered coroutines in the executor queue. Arguments: timeout (int/float): max execution timeout. No limit by default. return_exceptions (bool): in case of coroutine exception. return_when (str): sets when coroutine should be resolved. See `asyncio.wait`_ for supported values. ignore_empty (bool, optional): do not raise an exception if there are no coroutines to schedule are empty. Returns: asyncio.Future (tuple): two sets of Futures: ``(done, pending)`` Raises: ValueError: if there is no coroutines to schedule. RuntimeError: if executor is still running. TimeoutError: if execution takes more than expected. .. _asyncio.wait: https://docs.python.org/3/library/asyncio-task.html#asyncio.wait # noqa """
# Only allow 1 concurrent execution if self.running: raise RuntimeError('paco: executor is already running') # Overwrite ignore empty behaviour, if explicitly defined ignore_empty = (self.ignore_empty if ignore_empty is None else ignore_empty) # Check we have coroutines to schedule if len(self.pool) == 0: # If ignore empty mode enabled, just return an empty tuple if ignore_empty: return (tuple(), tuple()) # Othwerise raise an exception raise ValueError('paco: pool of coroutines is empty') # Set executor state to running self.running = True # Configure return exceptions if return_exceptions is not None: self.return_exceptions = return_exceptions if return_exceptions is False and return_when is None: return_when = 'FIRST_EXCEPTION' if return_when is None: return_when = 'ALL_COMPLETED' # Trigger pre-execution event yield from self.observer.trigger('start', self) # Sequential coroutines execution if self.limit == 1: done, pending = yield from self._run_sequentially() # Concurrent execution based on configured limit if self.limit != 1: done, pending = yield from self._run_concurrently( timeout=timeout, return_when=return_when) # Reset internal state and queue self.running = False # Raise exception, if needed if self.return_exceptions is False and self.errors: err = self.errors[0] err.errors = self.errors[1:] raise err # Trigger pre-execution event yield from self.observer.trigger('finish', self) # Reset executor state to defaults after each execution self.reset() # Return resultant futures in two tuples return done, pending
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def next_interval(self, interval): """ Given a value of an interval, this function returns the next interval value """
index = np.where(self.intervals == interval) if index[0][0] + 1 < len(self.intervals): return self.intervals[index[0][0] + 1] else: raise IndexError("Ran out of intervals!")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nearest_interval(self, interval): """ This function returns the nearest interval to any given interval. """
thresh_range = 25 # in cents if interval < self.intervals[0] - thresh_range or interval > self.intervals[-1] + thresh_range: raise IndexError("The interval given is beyond " + str(thresh_range) + " cents over the range of intervals defined.") index = find_nearest_index(self.intervals, interval) return self.intervals[index]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def brent_optimise(node1, node2, min_brlen=0.001, max_brlen=10, verbose=False): """ Optimise ML distance between two partials. min and max set brackets """
from scipy.optimize import minimize_scalar wrapper = BranchLengthOptimiser(node1, node2, (min_brlen + max_brlen) / 2.) n = minimize_scalar(lambda x: -wrapper(x)[0], method='brent', bracket=(min_brlen, max_brlen))['x'] if verbose: logger.info(wrapper) if n < min_brlen: n = min_brlen wrapper(n) return n, -1 / wrapper.get_d2lnl(n)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pairdists(alignment, subs_model, alpha=None, ncat=4, tolerance=1e-6, verbose=False): """ Load an alignment, calculate all pairwise distances and variances model parameter must be a Substitution model type from phylo_utils """
# Check if not isinstance(subs_model, phylo_utils.models.Model): raise ValueError("Can't handle this model: {}".format(model)) if alpha is None: alpha = 1.0 ncat = 1 # Set up markov model tm = TransitionMatrix(subs_model) gamma_rates = discrete_gamma(alpha, ncat) partials = alignment_to_partials(alignment) seqnames = alignment.get_names() nseq = len(seqnames) distances = np.zeros((nseq, nseq)) variances = np.zeros((nseq, nseq)) # Check the model has the appropriate size if not subs_model.size == partials[seqnames[0]].shape[1]: raise ValueError("Model {} expects {} states, but the alignment has {}".format(model.name, model.size, partials[seqnames[0]].shape[1])) nodes = [phylo_utils.likelihood.LnlModel(tm) for seq in range(nseq)] for node, header in zip(nodes, seqnames): node.set_partials(partials[header]) # retrieve partial likelihoods from partials dictionary for i, j in itertools.combinations(range(nseq), 2): brlen, var = brent_optimise(nodes[i], nodes[j], verbose=verbose) distances[i, j] = distances[j, i] = brlen variances[i, j] = variances[j, i] = var dm = DistanceMatrix.from_array(distances, names=seqnames) vm = DistanceMatrix.from_array(variances, names=seqnames) return dm, vm
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_alignment(self, filename, file_format, interleaved=None): """ Write the alignment to file using Bio.AlignIO """
if file_format == 'phylip': file_format = 'phylip-relaxed' AlignIO.write(self._msa, filename, file_format)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def simulate(self, nsites, transition_matrix, tree, ncat=1, alpha=1): """ Return sequences simulated under the transition matrix's model """
sim = SequenceSimulator(transition_matrix, tree, ncat, alpha) return list(sim.simulate(nsites).items())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bootstrap(self): """ Return a new Alignment that is a bootstrap replicate of self """
new_sites = sorted(sample_wr(self.get_sites())) seqs = list(zip(self.get_names(), (''.join(seq) for seq in zip(*new_sites)))) return self.__class__(seqs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def simulate(self, n): """ Evolve multiple sites during one tree traversal """
self.tree._tree.seed_node.states = self.ancestral_states(n) categories = np.random.randint(self.ncat, size=n).astype(np.intc) for node in self.tree.preorder(skip_seed=True): node.states = self.evolve_states(node.parent_node.states, categories, node.pmats) if node.is_leaf(): self.sequences[node.taxon.label] = node.states return self.sequences_to_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 ancestral_states(self, n): """ Generate ancestral sequence states from the equilibrium frequencies """
anc = np.empty(n, dtype=np.intc) _weighted_choices(self.state_indices, self.freqs, anc) return anc
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sequences_to_string(self): """ Convert state indices to a string of characters """
return {k: ''.join(self.states[v]) for (k, v) in self.sequences.items()}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def crc_srec(hexstr): """Calculate the CRC for given Motorola S-Record hexstring. """
crc = sum(bytearray(binascii.unhexlify(hexstr))) crc &= 0xff crc ^= 0xff return crc
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def crc_ihex(hexstr): """Calculate the CRC for given Intel HEX hexstring. """
crc = sum(bytearray(binascii.unhexlify(hexstr))) crc &= 0xff crc = ((~crc + 1) & 0xff) return crc
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pack_srec(type_, address, size, data): """Create a Motorola S-Record record of given data. """
if type_ in '0159': line = '{:02X}{:04X}'.format(size + 2 + 1, address) elif type_ in '268': line = '{:02X}{:06X}'.format(size + 3 + 1, address) elif type_ in '37': line = '{:02X}{:08X}'.format(size + 4 + 1, address) else: raise Error( "expected record type 0..3 or 5..9, but got '{}'".format(type_)) if data: line += binascii.hexlify(data).decode('ascii').upper() return 'S{}{}{:02X}'.format(type_, line, crc_srec(line))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unpack_srec(record): """Unpack given Motorola S-Record record into variables. """
# Minimum STSSCC, where T is type, SS is size and CC is crc. if len(record) < 6: raise Error("record '{}' too short".format(record)) if record[0] != 'S': raise Error( "record '{}' not starting with an 'S'".format(record)) size = int(record[2:4], 16) type_ = record[1:2] if type_ in '0159': width = 4 elif type_ in '268': width = 6 elif type_ in '37': width = 8 else: raise Error( "expected record type 0..3 or 5..9, but got '{}'".format(type_)) data_offset = (4 + width) crc_offset = (4 + 2 * size - 2) address = int(record[4:data_offset], 16) data = binascii.unhexlify(record[data_offset:crc_offset]) actual_crc = int(record[crc_offset:], 16) expected_crc = crc_srec(record[2:crc_offset]) if actual_crc != expected_crc: raise Error( "expected crc '{:02X}' in record {}, but got '{:02X}'".format( expected_crc, record, actual_crc)) return (type_, address, size - 1 - width // 2, 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 pack_ihex(type_, address, size, data): """Create a Intel HEX record of given data. """
line = '{:02X}{:04X}{:02X}'.format(size, address, type_) if data: line += binascii.hexlify(data).decode('ascii').upper() return ':{}{:02X}'.format(line, crc_ihex(line))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unpack_ihex(record): """Unpack given Intel HEX record into variables. """
# Minimum :SSAAAATTCC, where SS is size, AAAA is address, TT is # type and CC is crc. if len(record) < 11: raise Error("record '{}' too short".format(record)) if record[0] != ':': raise Error("record '{}' not starting with a ':'".format(record)) size = int(record[1:3], 16) address = int(record[3:7], 16) type_ = int(record[7:9], 16) if size > 0: data = binascii.unhexlify(record[9:9 + 2 * size]) else: data = b'' actual_crc = int(record[9 + 2 * size:], 16) expected_crc = crc_ihex(record[1:9 + 2 * size]) if actual_crc != expected_crc: raise Error( "expected crc '{:02X}' in record {}, but got '{:02X}'".format( expected_crc, record, actual_crc)) return (type_, address, size, 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 chunks(self, size=32, alignment=1): """Return chunks of the data aligned as given by `alignment`. `size` must be a multiple of `alignment`. Each chunk is returned as a named two-tuple of its address and data. """
if (size % alignment) != 0: raise Error( 'size {} is not a multiple of alignment {}'.format( size, alignment)) address = self.address data = self.data # First chunk may be shorter than `size` due to alignment. chunk_offset = (address % alignment) if chunk_offset != 0: first_chunk_size = (alignment - chunk_offset) yield self._Chunk(address, data[:first_chunk_size]) address += (first_chunk_size // self._word_size_bytes) data = data[first_chunk_size:] else: first_chunk_size = 0 for offset in range(0, len(data), size): yield self._Chunk(address + offset // self._word_size_bytes, data[offset:offset + size])
<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_data(self, minimum_address, maximum_address, data, overwrite): """Add given data to this segment. The added data must be adjacent to the current segment data, otherwise an exception is thrown. """
if minimum_address == self.maximum_address: self.maximum_address = maximum_address self.data += data elif maximum_address == self.minimum_address: self.minimum_address = minimum_address self.data = data + self.data elif (overwrite and minimum_address < self.maximum_address and maximum_address > self.minimum_address): self_data_offset = minimum_address - self.minimum_address # Prepend data. if self_data_offset < 0: self_data_offset *= -1 self.data = data[:self_data_offset] + self.data del data[:self_data_offset] self.minimum_address = minimum_address # Overwrite overlapping part. self_data_left = len(self.data) - self_data_offset if len(data) <= self_data_left: self.data[self_data_offset:self_data_offset + len(data)] = data data = bytearray() else: self.data[self_data_offset:] = data[:self_data_left] data = data[self_data_left:] # Append data. if len(data) > 0: self.data += data self.maximum_address = maximum_address else: raise AddDataError( 'data added to a segment must be adjacent to or overlapping ' 'with the original segment 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 remove_data(self, minimum_address, maximum_address): """Remove given data range from this segment. Returns the second segment if the removed data splits this segment in two. """
if ((minimum_address >= self.maximum_address) and (maximum_address <= self.minimum_address)): raise Error('cannot remove data that is not part of the segment') if minimum_address < self.minimum_address: minimum_address = self.minimum_address if maximum_address > self.maximum_address: maximum_address = self.maximum_address remove_size = maximum_address - minimum_address part1_size = minimum_address - self.minimum_address part1_data = self.data[0:part1_size] part2_data = self.data[part1_size + remove_size:] if len(part1_data) and len(part2_data): # Update this segment and return the second segment. self.maximum_address = self.minimum_address + part1_size self.data = part1_data return _Segment(maximum_address, maximum_address + len(part2_data), part2_data, self._word_size_bytes) else: # Update this segment. if len(part1_data) > 0: self.maximum_address = minimum_address self.data = part1_data elif len(part2_data) > 0: self.minimum_address = maximum_address self.data = part2_data else: self.maximum_address = self.minimum_address self.data = bytearray()
<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(self, segment, overwrite=False): """Add segments by ascending address. """
if self._list: if segment.minimum_address == self._current_segment.maximum_address: # Fast insertion for adjacent segments. self._current_segment.add_data(segment.minimum_address, segment.maximum_address, segment.data, overwrite) else: # Linear insert. for i, s in enumerate(self._list): if segment.minimum_address <= s.maximum_address: break if segment.minimum_address > s.maximum_address: # Non-overlapping, non-adjacent after. self._list.append(segment) elif segment.maximum_address < s.minimum_address: # Non-overlapping, non-adjacent before. self._list.insert(i, segment) else: # Adjacent or overlapping. s.add_data(segment.minimum_address, segment.maximum_address, segment.data, overwrite) segment = s self._current_segment = segment self._current_segment_index = i # Remove overwritten and merge adjacent segments. while self._current_segment is not self._list[-1]: s = self._list[self._current_segment_index + 1] if self._current_segment.maximum_address >= s.maximum_address: # The whole segment is overwritten. del self._list[self._current_segment_index + 1] elif self._current_segment.maximum_address >= s.minimum_address: # Adjacent or beginning of the segment overwritten. self._current_segment.add_data( self._current_segment.maximum_address, s.maximum_address, s.data[self._current_segment.maximum_address - s.minimum_address:], overwrite=False) del self._list[self._current_segment_index+1] break else: # Segments are not overlapping, nor adjacent. break else: self._list.append(segment) self._current_segment = segment self._current_segment_index = 0
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def chunks(self, size=32, alignment=1): """Iterate over all segments and return chunks of the data aligned as given by `alignment`. `size` must be a multiple of `alignment`. Each chunk is returned as a named two-tuple of its address and data. """
if (size % alignment) != 0: raise Error( 'size {} is not a multiple of alignment {}'.format( size, alignment)) for segment in self: for chunk in segment.chunks(size, alignment): yield chunk
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def minimum_address(self): """The minimum address of the data, or ``None`` if the file is empty. """
minimum_address = self._segments.minimum_address if minimum_address is not None: minimum_address //= self.word_size_bytes return minimum_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 maximum_address(self): """The maximum address of the data, or ``None`` if the file is empty. """
maximum_address = self._segments.maximum_address if maximum_address is not None: maximum_address //= self.word_size_bytes return maximum_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 add(self, data, overwrite=False): """Add given data string by guessing its format. The format must be Motorola S-Records, Intel HEX or TI-TXT. Set `overwrite` to ``True`` to allow already added data to be overwritten. """
if is_srec(data): self.add_srec(data, overwrite) elif is_ihex(data): self.add_ihex(data, overwrite) elif is_ti_txt(data): self.add_ti_txt(data, overwrite) else: raise UnsupportedFileFormatError()
<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_srec(self, records, overwrite=False): """Add given Motorola S-Records string. Set `overwrite` to ``True`` to allow already added data to be overwritten. """
for record in StringIO(records): type_, address, size, data = unpack_srec(record.strip()) if type_ == '0': self._header = data elif type_ in '123': address *= self.word_size_bytes self._segments.add(_Segment(address, address + size, bytearray(data), self.word_size_bytes), overwrite) elif type_ in '789': self.execution_start_address = 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 add_ihex(self, records, overwrite=False): """Add given Intel HEX records string. Set `overwrite` to ``True`` to allow already added data to be overwritten. """
extended_segment_address = 0 extended_linear_address = 0 for record in StringIO(records): type_, address, size, data = unpack_ihex(record.strip()) if type_ == IHEX_DATA: address = (address + extended_segment_address + extended_linear_address) address *= self.word_size_bytes self._segments.add(_Segment(address, address + size, bytearray(data), self.word_size_bytes), overwrite) elif type_ == IHEX_END_OF_FILE: pass elif type_ == IHEX_EXTENDED_SEGMENT_ADDRESS: extended_segment_address = int(binascii.hexlify(data), 16) extended_segment_address *= 16 elif type_ == IHEX_EXTENDED_LINEAR_ADDRESS: extended_linear_address = int(binascii.hexlify(data), 16) extended_linear_address <<= 16 elif type_ in [IHEX_START_SEGMENT_ADDRESS, IHEX_START_LINEAR_ADDRESS]: self.execution_start_address = int(binascii.hexlify(data), 16) else: raise Error("expected type 1..5 in record {}, but got {}".format( record, type_))
<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_ti_txt(self, lines, overwrite=False): """Add given TI-TXT string `lines`. Set `overwrite` to ``True`` to allow already added data to be overwritten. """
address = None eof_found = False for line in StringIO(lines): # Abort if data is found after end of file. if eof_found: raise Error("bad file terminator") line = line.strip() if len(line) < 1: raise Error("bad line length") if line[0] == 'q': eof_found = True elif line[0] == '@': try: address = int(line[1:], 16) except ValueError: raise Error("bad section address") else: # Try to decode the data. try: data = bytearray(binascii.unhexlify(line.replace(' ', ''))) except (TypeError, binascii.Error): raise Error("bad data") size = len(data) # Check that there are correct number of bytes per # line. There should TI_TXT_BYTES_PER_LINE. Only # exception is last line of section which may be # shorter. if size > TI_TXT_BYTES_PER_LINE: raise Error("bad line length") if address is None: raise Error("missing section address") self._segments.add(_Segment(address, address + size, data, self.word_size_bytes), overwrite) if size == TI_TXT_BYTES_PER_LINE: address += size else: address = None if not eof_found: raise Error("missing file terminator")
<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_binary(self, data, address=0, overwrite=False): """Add given data at given address. Set `overwrite` to ``True`` to allow already added data to be overwritten. """
address *= self.word_size_bytes self._segments.add(_Segment(address, address + len(data), bytearray(data), self.word_size_bytes), overwrite)
<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_file(self, filename, overwrite=False): """Open given file and add its data by guessing its format. The format must be Motorola S-Records, Intel HEX or TI-TXT. Set `overwrite` to ``True`` to allow already added data to be overwritten. """
with open(filename, 'r') as fin: self.add(fin.read(), overwrite)
<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_srec_file(self, filename, overwrite=False): """Open given Motorola S-Records file and add its records. Set `overwrite` to ``True`` to allow already added data to be overwritten. """
with open(filename, 'r') as fin: self.add_srec(fin.read(), overwrite)
<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_ihex_file(self, filename, overwrite=False): """Open given Intel HEX file and add its records. Set `overwrite` to ``True`` to allow already added data to be overwritten. """
with open(filename, 'r') as fin: self.add_ihex(fin.read(), overwrite)
<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_ti_txt_file(self, filename, overwrite=False): """Open given TI-TXT file and add its contents. Set `overwrite` to ``True`` to allow already added data to be overwritten. """
with open(filename, 'r') as fin: self.add_ti_txt(fin.read(), overwrite)
<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_binary_file(self, filename, address=0, overwrite=False): """Open given binary file and add its contents. Set `overwrite` to ``True`` to allow already added data to be overwritten. """
with open(filename, 'rb') as fin: self.add_binary(fin.read(), address, overwrite)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def as_srec(self, number_of_data_bytes=32, address_length_bits=32): """Format the binary file as Motorola S-Records records and return them as a string. `number_of_data_bytes` is the number of data bytes in each record. `address_length_bits` is the number of address bits in each record. S32500000100214601360121470136007EFE09D219012146017E17C20001FF5F16002148011973 S32500000120194E79234623965778239EDA3F01B2CA3F0156702B5E712B722B73214601342199 S5030002FA """
header = [] if self._header is not None: record = pack_srec('0', 0, len(self._header), self._header) header.append(record) type_ = str((address_length_bits // 8) - 1) if type_ not in '123': raise Error("expected data record type 1..3, but got {}".format( type_)) data = [pack_srec(type_, address, len(data), data) for address, data in self._segments.chunks(number_of_data_bytes)] number_of_records = len(data) if number_of_records <= 0xffff: footer = [pack_srec('5', number_of_records, 0, None)] elif number_of_records <= 0xffffff: footer = [pack_srec('6', number_of_records, 0, None)] else: raise Error('too many records {}'.format(number_of_records)) # Add the execution start address. if self.execution_start_address is not None: if type_ == '1': record = pack_srec('9', self.execution_start_address, 0, None) elif type_ == '2': record = pack_srec('8', self.execution_start_address, 0, None) else: record = pack_srec('7', self.execution_start_address, 0, None) footer.append(record) return '\n'.join(header + data + footer) + '\n'