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 download_local_file(filename, download_to_file): """ Copies a local file to Invenio's temporary directory. @param filename: the name of the file to copy @type filename: string @param download_to_file: the path to save the file to @type download_to_file: string @return: the path of the temporary file created @rtype: string @raise StandardError: if something went wrong """
# Try to copy. try: path = urllib2.urlparse.urlsplit(urllib.unquote(filename))[2] if os.path.abspath(path) != path: msg = "%s is not a normalized path (would be %s)." \ % (path, os.path.normpath(path)) raise InvenioFileCopyError(msg) allowed_path_list = current_app.config.get( 'CFG_BIBUPLOAD_FFT_ALLOWED_LOCAL_PATHS', [] ) allowed_path_list.append(current_app.config['CFG_TMPSHAREDDIR']) for allowed_path in allowed_path_list: if path.startswith(allowed_path): shutil.copy(path, download_to_file) if os.path.getsize(download_to_file) == 0: os.remove(download_to_file) msg = "%s seems to be empty" % (filename,) raise InvenioFileCopyError(msg) break else: msg = "%s is not in one of the allowed paths." % (path,) raise InvenioFileCopyError() except Exception as e: msg = "Impossible to copy the local file '%s' to %s: %s" % \ (filename, download_to_file, str(e)) raise InvenioFileCopyError(msg) return download_to_file
<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_mkstemp(suffix, prefix='filedownloadutils_'): """Create a temporary filename that don't have any '.' inside a part from the suffix."""
tmpfd, tmppath = tempfile.mkstemp( suffix=suffix, prefix=prefix, dir=current_app.config['CFG_TMPSHAREDDIR'] ) # Close the file and leave the responsability to the client code to # correctly open/close it. os.close(tmpfd) if '.' not in suffix: # Just in case format is empty return tmppath while '.' in os.path.basename(tmppath)[:-len(suffix)]: os.remove(tmppath) tmpfd, tmppath = tempfile.mkstemp( suffix=suffix, prefix=prefix, dir=current_app.config['CFG_TMPSHAREDDIR'] ) os.close(tmpfd) return tmppath
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def open_url(url, headers=None): """ Opens a URL. If headers are passed as argument, no check is performed and the URL will be opened. @param url: the URL to open @type url: string @param headers: the headers to use @type headers: dictionary @return: a file-like object as returned by urllib2.urlopen. """
request = urllib2.Request(url) if headers: for key, value in headers.items(): request.add_header(key, value) return URL_OPENER.open(request)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def get_json(self, url, timeout=30, astext=False, exceptions=False): """Get URL and parse JSON from text."""
try: with async_timeout.timeout(timeout): res = await self._aio_session.get(url) if res.status != 200: _LOGGER.error("QSUSB returned %s [%s]", res.status, url) return None res_text = await res.text() except (aiohttp.client_exceptions.ClientError, asyncio.TimeoutError) as exc: if exceptions: raise exc return None if astext: return res_text try: return json.loads(res_text) except json.decoder.JSONDecodeError: if res_text.strip(" ") == "": return None _LOGGER.error("Could not decode %s [%s]", res_text, url)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stop(self): """Stop listening."""
self._running = False if self._sleep_task: self._sleep_task.cancel() self._sleep_task = None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def _async_listen(self, callback=None): """Listen loop."""
while True: if not self._running: return try: packet = await self.get_json( URL_LISTEN.format(self._url), timeout=30, exceptions=True) except asyncio.TimeoutError: continue except aiohttp.client_exceptions.ClientError as exc: _LOGGER.warning("ClientError: %s", exc) self._sleep_task = self.loop.create_task(asyncio.sleep(30)) try: await self._sleep_task except asyncio.CancelledError: pass self._sleep_task = None continue if isinstance(packet, dict) and QS_CMD in packet: _LOGGER.debug("callback( %s )", packet) try: callback(packet) except Exception as err: # pylint: disable=broad-except _LOGGER.error("Exception in callback\nType: %s: %s", type(err), err) else: _LOGGER.debug("unknown packet? %s", packet)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def attowiki_distro_path(): """return the absolute complete path where attowiki is located .. todo:: use pkg_resources ? """
attowiki_path = os.path.abspath(__file__) if attowiki_path[-1] != '/': attowiki_path = attowiki_path[:attowiki_path.rfind('/')] else: attowiki_path = attowiki_path[:attowiki_path[:-1].rfind('/')] return attowiki_path
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_command(self): """Build out the crontab command"""
return cron_utils.cronify("crontab -l | {{ cat; echo \"{} {} {} {} {} CJOBID='{}' MAILTO='' {}\"; }} | crontab - > /dev/null".format(self._minute, self._hour, self._day_of_month, self._month_of_year, self._day_of_week, self._jobid, self._command))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def infer_format(filename:str) -> str: """Return extension identifying format of given filename"""
_, ext = os.path.splitext(filename) return ext
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reversed_graph(graph:dict) -> dict: """Return given graph reversed"""
ret = defaultdict(set) for node, succs in graph.items(): for succ in succs: ret[succ].add(node) return dict(ret)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def have_cycle(graph:dict) -> frozenset: """Perform a topologic sort to detect any cycle. Return the set of unsortable nodes. If at least one item, then there is cycle in given graph. """
# topological sort walked = set() # walked nodes nodes = frozenset(it.chain(it.chain.from_iterable(graph.values()), graph.keys())) # all nodes of the graph preds = reversed_graph(graph) # succ: preds last_walked_len = -1 while last_walked_len != len(walked): last_walked_len = len(walked) for node in nodes - walked: if len(preds.get(node, set()) - walked) == 0: walked.add(node) return frozenset(nodes - walked)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def file_lines(bblfile:str) -> iter: """Yield lines found in given file"""
with open(bblfile) as fd: yield from (line.rstrip() for line in fd if line.rstrip())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def line_type(line:str) -> str: """Give type of input line, as defined in LINE_TYPES 'IN' 'EMPTY' """
for regex, ltype in LINE_TYPES.items(): if re.fullmatch(regex, line): return ltype raise ValueError("Input line \"{}\" is not bubble formatted".format(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 line_data(line:str) -> tuple: """Return groups found in given line ('IN', 'a', 'b') () """
for regex, _ in LINE_TYPES.items(): match = re.fullmatch(regex, line) if match: return match.groups() raise ValueError("Input line \"{}\" is not bubble formatted".format(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 _initBuffer(self, bufferColorMode, bufferSize): """! \~english Initialize the buffer object instance, use PIL Image as for buffer @param bufferColorMode: "RGB" or "1" @param bufferSize: (width, height) \~chinese 初始化缓冲区对象实例,使用PIL Image作为缓冲区 @param bufferColorMode: 色彩模式, 取值: "RGB" 或 "1" @param bufferSize: 缓存大小 (width, height),例如: (128, 64) """
# super(SSScreenBase)._initBuffer(bufferColorMode, bufferSize) self._buffer_color_mode = bufferColorMode #create screen image buffer and canvas if bufferSize==None: self._buffer = Image.new( bufferColorMode , self._display_size ) else: self._buffer = Image.new( bufferColorMode , bufferSize ) self.Canvas = ImageDraw.Draw( self._buffer ) #creare screen view self.View = SSRect( 0, 0, self._display_size[0], self._display_size[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 clearCanvas(self, fillColor = 0 ): """! \~engliash Clear up canvas and fill color at same time @param fillColor: a color value @note The fillColor value range depends on the setting of _buffer_color_mode. * If it is SS_COLOR_MODE_MONO ("1") monochrome mode, it can only select 0: black and 1: white * If it is SS_COLOR_MODE_RGB ("RGB") color mode, RGB color values can be used \~chinese 清除画布并同时填充颜色 @param fillColor: 颜色值 @note fillColor 取值范围取决于 _buffer_color_mode 的设定。 * 如果是 SS_COLOR_MODE_MONO ("1") 单色模式,只能选择 0:黑色 和 1:白色 * 如果是 SS_COLOR_MODE_RGB ("RGB") 彩色模式,可以使用 RGB 色彩值 """
self.Canvas.rectangle((0, 0, self._display_size[0], self._display_size[1]), outline=0, fill=fillColor)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resize(self, newWidth = 0, newHeight = 0): """! \~english Resize width and height of rectangles @param newWidth: new width value @param newHeight: new height value \~chinese 重新设定矩形高宽 @param newWidth: 新宽度 @param newHeight: 新高度 """
self.height = newHeight self.width = newWidth
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rotateDirection(self, displayDirection): """! \~english rotate screen direction @param displayDirection: Screen Direction. value can be chosen: 0, 90, 180, 270 \~chinese 旋转显示屏方向 @param displayDirection: 显示屏方向。可选值: 0, 90, 180, 270 \~ @note \~english after rotate the View resize to screen size \~chinese 改变方向后,默认的 View 大小会更新为当前 Screen 的大小 \~\n """
if self._needSwapWH(self._display_direction, displayDirection): self._display_size = ( self._display_size[1], self._display_size[0] ) if self.redefineBuffer( { "size":self._display_size, "color_mode":self._buffer_color_mode } ): self.View.resize(self._display_size[0], self._display_size[1]) self._display_direction = displayDirection
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def autodiscover_modules(packages, related_name_re='.+', ignore_exceptions=False): """Autodiscover function follows the pattern used by Celery. :param packages: List of package names to auto discover modules in. :type packages: list of str :param related_name_re: Regular expression used to match modules names. :type related_name_re: str :param ignore_exceptions: Ignore exception when importing modules. :type ignore_exceptions: bool """
warnings.warn('autodiscover_modules has been deprecated. ' 'Use Flask-Registry instead.', DeprecationWarning) global _RACE_PROTECTION if _RACE_PROTECTION: return [] _RACE_PROTECTION = True modules = [] try: tmp = [find_related_modules(pkg, related_name_re, ignore_exceptions) for pkg in packages] for l in tmp: for m in l: if m is not None: modules.append(m) # Workaround for finally-statement except: _RACE_PROTECTION = False raise _RACE_PROTECTION = False return modules
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_related_modules(package, related_name_re='.+', ignore_exceptions=False): """Find matching modules using a package and a module name pattern."""
warnings.warn('find_related_modules has been deprecated.', DeprecationWarning) package_elements = package.rsplit(".", 1) try: if len(package_elements) == 2: pkg = __import__(package_elements[0], globals(), locals(), [ package_elements[1]]) pkg = getattr(pkg, package_elements[1]) else: pkg = __import__(package_elements[0], globals(), locals(), []) pkg_path = pkg.__path__ except AttributeError: return [] # Find all modules named according to related_name p = re.compile(related_name_re) modules = [] for name in find_modules(package, include_packages=True): if p.match(name.split('.')[-1]): try: modules.append(import_string(name, silent=ignore_exceptions)) except Exception as e: if not ignore_exceptions: raise e return modules
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def import_related_module(package, pkg_path, related_name, ignore_exceptions=False): """Import module from given path."""
try: imp.find_module(related_name, pkg_path) except ImportError: return try: return getattr( __import__('%s' % (package), globals(), locals(), [related_name]), related_name ) except Exception as e: if ignore_exceptions: current_app.logger.exception( 'Can not import "{}" package'.format(package) ) else: raise e
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ansi(string, *args): """ Convenience function to chain multiple ColorWrappers to a string """
ansi = '' for arg in args: arg = str(arg) if not re.match(ANSI_PATTERN, arg): raise ValueError('Additional arguments must be ansi strings') ansi += arg return ansi + string + colorama.Style.RESET_ALL
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def puts(*args, **kwargs): """ Full feature printing function featuring trimming and padding for both files and ttys """
# parse kwargs trim = kwargs.pop('trim', False) padding = kwargs.pop('padding', None) stream = kwargs.pop('stream', sys.stdout) # HACK: check if stream is IndentedFile indent = getattr(stream, 'indent', 0) # stringify args args = [str(i) for i in args] # helpers def trimstr(ansi, width): string = ''; size = 0; i = 0 while i < len(ansi): mobj = re.match(ANSI_PATTERN, ansi[i:]) if mobj: # append ansi code string = string + mobj.group(0) i += len(mobj.group(0)) else: # loop for more ansi codes even at max width size += 1 if size > width: break # append normal char string = string + ansi[i] i += 1 return (string, size) # process strings if not stream.isatty(): # remove ansi codes and print for string in args: stream.write(re.sub(ANSI_PATTERN, '', string) + '\n') else: # get terminal width try: curses.setupterm() except: trim = False padding = None else: width = curses.tigetnum('cols') - indent for string in args: if trim or padding: trimmed, size = trimstr(string, width) # trim string if trim: if len(trimmed) < len(string): trimmed = trimstr(string, width - 3)[0] + colorama.Style.RESET_ALL + '...' string = trimmed # add padding if padding: string += padding * (width - size) # print final string stream.write(string + '\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 char_between(lower, upper, func_name): '''return current char and step if char is between lower and upper, where @test: a python function with one argument, which tests on one char and return True or False @test must be registered with register_function''' function = register_function(func_name, lambda char: lower<=char<=upper) return char_on_predicate(function)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def char_in(string, func_name): '''return current char and step if char is in string, where @test: a python function with one argument, which tests on one char and return True or False @test must be registered with register_function''' function = register_function(func_name, lambda char: char in string) return char_on_predicate(function)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def update_version(self, version, step=1): "Compute an new version and write it as a tag" # update the version based on the flags passed. if self.config.patch: version.patch += step if self.config.minor: version.minor += step if self.config.major: version.major += step if self.config.build: version.build_number += step if self.config.build_number: version.build_number = self.config.build_number # create a new tag in the repo with the new version. if self.config.dry_run: log.info('Not updating repo to version {0}, because of --dry-run'.format(version)) else: version = self.call_plugin_function('set_version', version) return version
<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_id(self): """Getter because using the id property from within was not working"""
ret = None row = self.row if row: ret = row["id"] return ret
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def time_pipeline(iterable, *steps): ''' This times the steps in a pipeline. Give it an iterable to test against followed by the steps of the pipeline seperated in individual functions. Example Usage: ``` from random import choice, randint l = [randint(0,50) for i in range(100)] step1 = lambda iterable:(i for i in iterable if i%5==0) step2 = lambda iterable:(i for i in iterable if i%8==3) step3 = lambda iterable:sorted((1.0*i)/50 for i in iterable) step4 = lambda iterable:(float(float(float(float(i*3)))) for i in iterable) print('filter first') time_pipeline(l, step1, step2, step3, step4) print('process first') time_pipeline(l, step3, step4, step1, step2) print('filter, process, filter, process') time_pipeline(l, step1, step3, step2, step4) ``` Outputs: filter first step 1 | 2.0427s | step1 = lambda iterable:(i for i in iterable if i%5==0) step 2 | 2.0510s | step2 = lambda iterable:(i for i in iterable if i%8==3) step 3 | 2.4839s | step3 = lambda iterable:sorted((1.0*i)/50 for i in iterable) step 4 | 2.8446s | step4 = lambda iterable:(float(float(float(float(i*3)))) for i in iterable) process first step 1 | 7.5291s | step3 = lambda iterable:sorted((1.0*i)/50 for i in iterable) step 2 | 20.6732s | step4 = lambda iterable:(float(float(float(float(i*3)))) for i in iterable) step 3 | 16.8470s | step1 = lambda iterable:(i for i in iterable if i%5==0) step 4 | 16.8269s | step2 = lambda iterable:(i for i in iterable if i%8==3) filter, process, filter, process step 1 | 2.0528s | step1 = lambda iterable:(i for i in iterable if i%5==0) step 2 | 3.3039s | step3 = lambda iterable:sorted((1.0*i)/50 for i in iterable) step 3 | 3.1385s | step2 = lambda iterable:(i for i in iterable if i%8==3) step 4 | 3.1489s | step4 = lambda iterable:(float(float(float(float(i*3)))) for i in iterable) ''' if callable(iterable): try: iter(iterable()) callable_base = True except: raise TypeError('time_pipeline needs the first argument to be an iterable or a function that produces an iterable.') else: try: iter(iterable) callable_base = False except: raise TypeError('time_pipeline needs the first argument to be an iterable or a function that produces an iterable.') # if iterable is not a function, load the whole thing # into a list so it can be ran over multiple times if not callable_base: iterable = tuple(iterable) # these store timestamps for time calculations durations = [] results = [] for i,_ in enumerate(steps): current_tasks = steps[:i+1] #print('testing',current_tasks) duration = 0.0 # run this test x number of times for t in range(100000): # build the generator test_generator = iter(iterable()) if callable_base else iter(iterable) # time its execution start = ts() for task in current_tasks: test_generator = task(test_generator) for i in current_tasks[-1](test_generator): pass duration += ts() - start durations.append(duration) if len(durations) == 1: results.append(durations[0]) #print(durations[0],durations[0]) else: results.append(durations[-1]-durations[-2]) #print(durations[-1]-durations[-2],durations[-1]) #print(results) #print(durations) assert sum(results) > 0 resultsum = sum(results) ratios = [i/resultsum for i in results] #print(ratios) for i in range(len(ratios)): try: s = getsource(steps[i]).splitlines()[0].strip() except: s = repr(steps[i]).strip() print('step {} | {:2.4f}s | {}'.format(i+1, durations[i], s))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def runs_per_second(generator, seconds=3): ''' use this function as a profiler for both functions and generators to see how many iterations or cycles they can run per second Example usage for timing simple operations/functions: ``` print(runs_per_second(lambda:1+2)) # 2074558 print(runs_per_second(lambda:1-2)) # 2048523 print(runs_per_second(lambda:1/2)) # 2075186 print(runs_per_second(lambda:1*2)) # 2101722 print(runs_per_second(lambda:1**2)) # 2104572 ``` Example usage for timing iteration speed of generators: ``` def counter(): c = 0 while 1: yield c c+=1 print(runs_per_second(counter())) # 1697328 print(runs_per_second((i for i in range(2000)))) # 1591301 ``` ''' assert isinstance(seconds, int), 'runs_per_second needs seconds to be an int, not {}'.format(repr(seconds)) assert seconds>0, 'runs_per_second needs seconds to be positive, not {}'.format(repr(seconds)) # if generator is a function, turn it into a generator for testing if callable(generator) and not any(i in ('next', '__next__', '__iter__') for i in dir(generator)): try: # get the output of the function output = generator() except: # if the function crashes without any arguments raise Exception('runs_per_second needs a working function that accepts no arguments') else: # this usage of iter infinitely calls a function until the second argument is the output # so I set the second argument to something that isnt what output was. generator = iter(generator, (1 if output is None else None)) del output c=0 # run counter, keep this one short for performance reasons entire_test_time_used = False start = ts() end = start+seconds for _ in generator: if ts()>end: entire_test_time_used = True break else: c += 1 duration = (ts())-start # the ( ) around ts ensures that it will be the first thing calculated return int(c/(seconds if entire_test_time_used else duration))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fermion_avg(efermi, norm_hopping, func): """calcules for every slave it's average over the desired observable"""
if func == 'ekin': func = bethe_ekin_zeroT elif func == 'ocupation': func = bethe_filling_zeroT return np.asarray([func(ef, tz) for ef, tz in zip(efermi, norm_hopping)])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def spinflipandhop(slaves): """Calculates the interaction term of a spin flip and pair hopping"""
Sdw = [csr_matrix(spin_gen(slaves, i, 0)) for i in range(slaves)] Sup = [mat.T for mat in Sdw] sfh = np.zeros_like(Sup[0]) orbitals = slaves//2 for n in range(orbitals): for m in range(n+1, orbitals): sfh += Sup[2*n ] * Sdw[2*n + 1] * Sup[2*m + 1] * Sdw[2*m ] sfh += Sup[2*n+1] * Sdw[2*n ] * Sup[2*m ] * Sdw[2*m+1] sfh += Sup[2*n] * Sup[2*n + 1] * Sdw[2*m] * Sdw[2*m+1] sfh += Sup[2*m] * Sup[2*m + 1] * Sdw[2*n] * Sdw[2*n+1] return sfh
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def spin_z_op(param, oper): """Generates the required Sz operators, given the system parameter setup and the operator dictionary"""
slaves = param['slaves'] oper['Sz'] = np.array([spin_z(slaves, spin) for spin in range(slaves)]) oper['Sz+1/2'] = oper['Sz'] + 0.5*np.eye(2**slaves) oper['sumSz2'] = oper['Sz'].sum(axis=0)**2 # because Sz is diagonal Sz_mat_shape = oper['Sz'].reshape(param['orbitals'], 2, 2**slaves, 2**slaves) oper['sumSz-sp2'] = (Sz_mat_shape.sum(axis=1)**2).sum(axis=0) oper['sumSz-or2'] = (Sz_mat_shape.sum(axis=0)**2).sum(axis=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 spin_gen_op(oper, gauge): """Generates the generic spin matrices for the system"""
slaves = len(gauge) oper['O'] = np.array([spin_gen(slaves, i, c) for i, c in enumerate(gauge)]) oper['O_d'] = np.transpose(oper['O'], (0, 2, 1)) oper['O_dO'] = np.einsum('...ij,...jk->...ik', oper['O_d'], oper['O']) oper['Sfliphop'] = spinflipandhop(slaves)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_filling(self, populations): """Sets the orbital enenergies for on the reference of the free case. By setting the desired local populations on every orbital. Then generate the necesary operators to respect such configuraion"""
populations = np.asarray(populations) # # self.param['orbital_e'] -= bethe_findfill_zeroT( \ # self.param['avg_particles'], # self.param['orbital_e'], # self.param['hopping']) efermi = - bethe_find_crystalfield( populations, self.param['hopping']) self.param['populations'] = populations # fermion_avg(efermi, self.param['hopping'], 'ocupation') self.param['ekin'] = fermion_avg(efermi, self.param['hopping'], 'ekin') spin_gen_op(self.oper, estimate_gauge(populations))
<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, populations, lag, mu, u_int, j_coup, mean_f): """Resets the system into the last known state as given by the input values"""
self.set_filling(populations) self.param['lambda'] = lag self.param['orbital_e'] = mu self.selfconsistency(u_int, j_coup, mean_f)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_H(self, mean_field, l): """Updates the spin hamiltonian and recalculates its eigenbasis"""
self.H_s = self.spin_hamiltonian(mean_field, l) try: self.eig_energies, self.eig_states = diagonalize(self.H_s) except np.linalg.linalg.LinAlgError: np.savez('errorhamil', H=self.H_s, fiel=mean_field, lamb=l) raise except ValueError: np.savez('errorhamil', H=self.H_s, fiel=mean_field, lamb=l) print(mean_field, l) raise
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def spin_hamiltonian(self, h, l): """Constructs the single site spin Hamiltonian"""
h_spin = np.einsum('i,ijk', h[1], self.oper['O']) h_spin += np.einsum('i,ijk', h[0], self.oper['O_d']) h_spin += np.einsum('i,ijk', l, self.oper['Sz+1/2']) h_spin += self.oper['Hint'] return h_spin
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def inter_spin_hamiltonian(self, u_int, J_coup): """Calculates the interaction Hamiltonian. The Hund coupling is a fraction of the coulom interaction"""
J_coup *= u_int h_int = (u_int - 2*J_coup)/2.*self.oper['sumSz2'] h_int += J_coup*self.oper['sumSz-sp2'] h_int -= J_coup/2.*self.oper['sumSz-or2'] h_int -= J_coup*self.oper['Sfliphop'] return h_int
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def expected(self, observable, beta=1e5): """Wrapper to the expected_value function to fix the eigenbasis"""
return expected_value(observable, self.eig_energies, self.eig_states, beta)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def quasiparticle_weight(self): """Calculates quasiparticle weight"""
return np.array([self.expected(op)**2 for op in self.oper['O']])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mean_field(self): """Calculates mean field"""
mean_field = [] for sp_oper in [self.oper['O'], self.oper['O_d']]: avgO = np.array([self.expected(op) for op in sp_oper]) avgO[abs(avgO) < 1e-10] = 0. mean_field.append(avgO*self.param['ekin']) return np.array(mean_field)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def selfconsistency(self, u_int, J_coup, mean_field_prev=None): """Iterates over the hamiltonian to get the stable selfcosistent one"""
if mean_field_prev is None: mean_field_prev = np.array([self.param['ekin']]*2) hlog = [mean_field_prev] self.oper['Hint'] = self.inter_spin_hamiltonian(u_int, J_coup) converging = True half_fill = (self.param['populations'] == 0.5).all() while converging: if half_fill: self.update_H(hlog[-1], self.param['lambda']) else: res = root(self.restriction, self.param['lambda'], (hlog[-1]))#, method='lm') if not res.success: res.x = res.x * 0.5 + 0.5*self.param['lambda'] self.update_H(self.mean_field()*0.5 + 0.5*hlog[-1], res.x) print('fail', self.param['populations'][3:5]) if (self.quasiparticle_weight() < 0.001).all(): return hlog self.param['lambda'] = res.x hlog.append(self.mean_field()) converging = (abs(hlog[-1] - hlog[-2]) > self.param['tol']).all() \ or (abs(self.restriction(self.param['lambda'], hlog[-1])) > self.param['tol']).all() return hlog
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def restriction(self, lam, mean_field): """Lagrange multiplier in lattice slave spin"""
self.update_H(mean_field, lam) restric = np.array([self.expected(op) - n for op, n in zip(self.oper['Sz+1/2'], self.param['populations'])]) return restric
<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_cmd(cmd, out=os.path.devnull, err=os.path.devnull): """Runs an external command :param list cmd: Command to run. :param str out: Output file :param str err: Error file :raises: RuntimeError """
logger.debug(' '.join(cmd)) with open(out, 'w') as hout: proc = subprocess.Popen(cmd, stdout=hout, stderr=subprocess.PIPE) err_msg = proc.communicate()[1].decode() with open(err, 'w') as herr: herr.write(str(err_msg)) msg = '({}) {}'.format(' '.join(cmd), err_msg) if proc.returncode != 0: logger.error(msg) raise RuntimeError(msg)
<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_cmd_if_file_missing(cmd, fname, out=os.path.devnull, err=os.path.devnull): """Runs an external command if file is absent. :param list cmd: Command to run. :param str fname: Path to the file, which existence is being checked. :param str out: Output file :param str err: Error file :return: True if cmd was executed, False otherwise :rtype: boolean """
if fname is None or not os.path.exists(fname): run_cmd(cmd, out, err) return True else: return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def merge_files(sources, destination): """Copy content of multiple files into a single file. :param list(str) sources: source file names (paths) :param str destination: destination file name (path) :return: """
with open(destination, 'w') as hout: for f in sources: if os.path.exists(f): with open(f) as hin: shutil.copyfileobj(hin, hout) else: logger.warning('File is missing: {}'.format(f))
<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_path(self, path): """ Adds a new path to the list of searchable paths :param path: new path """
if os.path.exists(path): self.paths.add(path) return path else: #logger.debug('Path {} doesn\'t exist'.format(path)) 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 get(self, name): """ Looks for a name in the path. :param name: file name :return: path to the file """
for d in self.paths: if os.path.exists(d) and name in os.listdir(d): return os.path.join(d, name) logger.debug('File not found {}'.format(name)) 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 __handle_request(self, request, *args, **kw): """ Intercept the request and response. This function lets `HttpStatusCodeError`s fall through. They are caught and transformed into HTTP responses by the caller. :return: ``HttpResponse`` """
self._authenticate(request) self._check_permission(request) method = self._get_method(request) data = self._get_input_data(request) data = self._clean_input_data(data, request) response = self._exec_method(method, request, data, *args, **kw) return self._process_response(response, request)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _exec_method(self, method, request, data, *args, **kw): """ Execute appropriate request handler. """
if self._is_data_method(request): return method(data, request, *args, **kw) else: return method(request, *args, **kw)
<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_response(self, request, response): """ Format response using appropriate datamapper. Take the devil response and turn it into django response, ready to be returned to the client. """
res = datamapper.format(request, response, self) # data is now formatted, let's check if the status_code is set if res.status_code is 0: res.status_code = 200 # apply headers self._add_resposne_headers(res, response) return res
<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_resposne_headers(self, django_response, devil_response): """ Add response headers. Add HTTP headers from devil's response to django's response. """
try: headers = devil_response.headers except AttributeError: # ok, there was no devil_response pass else: for k, v in headers.items(): django_response[k] = v return django_response
<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_input_data(self, request): """ If there is data, parse it, otherwise return None. """
# only PUT and POST should provide data if not self._is_data_method(request): return None content = [row for row in request.read()] content = ''.join(content) if content else None return self._parse_input_data(content, request) if content else 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 _clean_input_data(self, data, request): """ Clean input data. """
# sanity check if not self._is_data_method(request): # this is not PUT or POST -> return return data # do cleaning try: if self.representation: # representation defined -> perform validation self._validate_input_data(data, request) if self.factory: # factory defined -> create object return self._create_object(data, request) else: # no factory nor representation -> return the same data back return data except ValidationError, exc: return self._input_validation_failed(exc, data, request)
<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_input_validator(self, request): """ Return appropriate input validator. For POST requests, ``self.post_representation`` is returned if it is present, ``self.representation`` otherwise. """
method = request.method.upper() if method != 'POST': return self.representation elif self.post_representation: return self.post_representation else: return self.representation
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _validate_input_data(self, data, request): """ Validate input data. :param request: the HTTP request :param data: the parsed data :return: if validation is performed and succeeds the data is converted into whatever format the validation uses (by default Django's Forms) If not, the data is returned unchanged. :raises: HttpStatusCodeError if data is not valid """
validator = self._get_input_validator(request) if isinstance(data, (list, tuple)): return map(validator.validate, data) else: return validator.validate(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 _validate_output_data( self, original_res, serialized_res, formatted_res, request): """ Validate the response data. :param response: ``HttpResponse`` :param data: payload data. This implementation assumes dict or list of dicts. :raises: `HttpStatusCodeError` if data is not valid """
validator = self.representation # when not to validate... if not validator: return try: if isinstance(serialized_res, (list, tuple)): map(validator.validate, serialized_res) else: validator.validate(serialized_res) except ValidationError, exc: self._output_validation_failed(exc, serialized_res, request)
<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_object(self, data, request): """ Create a python object from the given data. This will use ``self.factory`` object's ``create()`` function to create the data. If no factory is defined, this will simply return the same data that was given. """
if request.method.upper() == 'POST' and self.post_factory: fac_func = self.post_factory.create else: fac_func = self.factory.create if isinstance(data, (list, tuple)): return map(fac_func, data) else: return fac_func(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 _serialize_object(self, response_data, request): """ Create a python datatype from the given python object. This will use ``self.factory`` object's ``serialize()`` function to convert the object into dictionary. If no factory is defined, this will simply return the same data that was given. :param response_data: data returned by the resource """
if not self.factory: return response_data if isinstance(response_data, (list, tuple)): return map( lambda item: self.factory.serialize(item, request), response_data) else: return self.factory.serialize(response_data, request)
<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_unknown_error_response(self, request, exc): """ Generate HttpResponse for unknown exceptions. todo: this should be more informative.. """
logging.getLogger('devil').error( 'while doing %s on %s with [%s], devil caught: %s' % ( request.method, request.path_info, str(request.GET), str(exc)), exc_info=True) if settings.DEBUG: raise else: return HttpResponse(status=codes.INTERNAL_SERVER_ERROR[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_error_response(self, exc): """ Generate HttpResponse based on the HttpStatusCodeError. """
if exc.has_code(codes.UNAUTHORIZED): return self._get_auth_challenge(exc) else: if exc.has_code(codes.INTERNAL_SERVER_ERROR): logging.getLogger('devil').error('devil caught http error: ' + str(exc), exc_info=True) else: logging.getLogger('devil').error('devil caught http error: ' + str(exc)) content = exc.content or '' return HttpResponse(content=content, status=exc.get_code_num())
<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_auth_challenge(self, exc): """ Returns HttpResponse for the client. """
response = HttpResponse(content=exc.content, status=exc.get_code_num()) response['WWW-Authenticate'] = 'Basic realm="%s"' % REALM return response
<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_method(self, request): """ Figure out the requested method and return the callable. """
methodname = request.method.lower() method = getattr(self, methodname, None) if not method or not callable(method): raise errors.MethodNotAllowed() return method
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _authenticate(self, request): """ Perform authentication. """
def ensure_user_obj(): """ Make sure that request object has user property. If `request.user` is not present or is `None`, it is created and initialized with `AnonymousUser`. """ try: if request.user: return except AttributeError: pass request.user = AnonymousUser() def anonymous_access(exc_obj): """ Determine what to do with unauthenticated requests. If the request has already been authenticated, does nothing. :param exc_obj: exception object to be thrown if anonymous access is not permitted. """ if request.user and request.user.is_authenticated(): # request is already authenticated pass elif self.allow_anonymous: request.user = AnonymousUser() else: raise exc_obj # first, make sure that the request carries `user` attribute ensure_user_obj() if self.authentication: # authentication handler is configured try: self.authentication.authenticate(request) except errors.Unauthorized, exc: # http request doesn't carry any authentication information anonymous_access(exc) else: # no authentication configured anonymous_access(errors.Forbidden())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def print_item_callback(item): """Print an item callback, used by &listen."""
print('&listen [{}, {}={}]'.format( item.get('cmd', ''), item.get('id', ''), item.get('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 main(): """Quick test for QSUsb class."""
import argparse parser = argparse.ArgumentParser() parser.add_argument('--url', help='QSUSB URL [http://127.0.0.1:2020]', default='http://127.0.0.1:2020') parser.add_argument('--file', help='a test file from /&devices') parser.add_argument('--test_ids', help='List of test IDs', default='@0c2700,@0ac2f0') args = parser.parse_args() if args.file: with open(args.file) as data_file: data = json.load(data_file) qsusb = pyqwikswitch.QSDevices( print_devices_change_callback, print_devices_change_callback) print_bad_data(data) qsusb.set_qs_values(data) return print('Execute a basic test on server: {}\n'.format(args.url)) def qs_to_value(key, new): print(" --> New value: {}={}".format(key, new)) qsusb = QSUsb(args.url, 1, qs_to_value) print('Version: ' + qsusb.version()) qsusb.set_qs_values() qsusb.listen(print_item_callback, timeout=5) print("Started listening") try: # Do some test while listening if args.test_ids and len(args.test_ids) > 0: test_devices_set(qsusb.devices, args.test_ids.split(',')) print("\n\nListening for 60 seconds (test buttons now)\n") sleep(60) except KeyboardInterrupt: pass finally: qsusb.stop() # Close all threads print("Stopped listening")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get(self): """Called to get the asset values and if it is valid """
with self._lock: now = datetime.now() active = [] for i, vef in enumerate(self.futures): # has expired if (vef[1] or datetime.max) <= now: self.futures.pop(i) continue # in future elif (vef[2] or datetime.min) >= now: continue else: active.append(i) if active: # this will evict values old values # because new ones are "more recent" via future value, _e, _f = self.futures[active[-1]] for i in active[:-1]: self.futures.pop(i) return value raise ValueError("dicttime: no current value, however future has (%d) values" % len(self.futures))
<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_node(node, **kwds): """add_node from Sphinx """
nodes._add_node_class_names([node.__name__]) for key, val in kwds.iteritems(): try: visit, depart = val except ValueError: raise ValueError('Value for key %r must be a ' '(visit, depart) function tuple' % key) if key == 'html': from docutils.writers.html4css1 import HTMLTranslator as translator elif key == 'latex': from docutils.writers.latex2e import LaTeXTranslator as translator else: # ignore invalid keys for compatibility continue setattr(translator, 'visit_'+node.__name__, visit) if depart: setattr(translator, 'depart_'+node.__name__, depart)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def retrieve(self, *args, **kwargs): """Retrieve the permsission function for the provided things. """
lookup, key = self._lookup(*args, **kwargs) return lookup[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 has_rabf_motif(self): """Checks if the sequence has enough RabF motifs within the G domain If there exists more than one G domain in the sequence enough RabF motifs is required in at least one of those domains to classify the sequence as a Rab. """
if self.rabf_motifs: for gdomain in self.gdomain_regions: beg, end = map(int, gdomain.split('-')) motifs = [x for x in self.rabf_motifs if x[1] >= beg and x[2] <= end] if motifs: matches = int(pairwise2.align.globalxx('12345', ''.join(str(x[0]) for x in motifs))[0][2]) if matches >= self.motif_number: return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def summarize(self): """ G protein annotation summary in a text format :return: A string summary of the annotation :rtype: str """
data = [ ['Sequence ID', self.seqrecord.id], ['G domain', ' '.join(self.gdomain_regions) if self.gdomain_regions else None], ['E-value vs rab db', self.evalue_bh_rabs], ['E-value vs non-rab db', self.evalue_bh_non_rabs], ['RabF motifs', ' '.join(map(str, self.rabf_motifs)) if self.rabf_motifs else None], ['Is Rab?', self.is_rab()] ] summary = '' for name, value in data: summary += '{:25s}{}\n'.format(name, value) if self.is_rab(): summary += '{:25s}{}\n'.format('Top 5 subfamilies', ', '.join('{:s} ({:.2g})'.format(name, score) for name, score in self.rab_subfamily_top5)) return summary
<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(self): """Write sequences predicted to be Rabs as a fasta file. :return: Number of written sequences :rtype: int """
rabs = [x.seqrecord for x in self.gproteins.values() if x.is_rab()] return SeqIO.write(rabs, self.tmpfname + '.phase2', 'fasta')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check(self): """ Check if data and third party tools, necessary to run the classification, are available :raises: RuntimeError """
pathfinder = Pathfinder(True) if pathfinder.add_path(pathfinder['superfamily']) is None: raise RuntimeError("'superfamily' data directory is missing") for tool in ('hmmscan', 'phmmer', 'mast', 'blastp', 'ass3.pl', 'hmmscan.pl'): if not pathfinder.exists(tool): raise RuntimeError('Dependency {} is missing'.format(tool))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def filter_(*permissions, **kwargs): """ Constructs a clause to filter all bearers or targets for a given berarer or target. """
bearer = kwargs['bearer'] target = kwargs.get('target') bearer_cls = type_for(bearer) # We need a query object. There are many ways to get one, Either we can # be passed one, or we can make one from the session. We can either be # passed the session, or we can grab the session from the bearer passed. if 'query' in kwargs: query = kwargs['query'] elif 'session' in kwargs: query = kwargs['session'].query(target) else: query = object_session(bearer).query(target) getter = functools.partial( registry.retrieve, bearer=bearer_cls, target=target) try: # Generate a hash of {rulefn: permission} that we can use later # to collect all of the rules. if len(permissions): rules = {getter(permission=x): x for x in permissions} else: rules = {getter(): None} except KeyError: # No rules defined. Default to no permission. return query.filter(sql.false()) # Invoke all the rules and collect the results # Abusing reduce here to invoke each rule and send the return value (query) # from one rule to the next one. In this way the query becomes # increasingly decorated as it marches through the system. # q == query # r = (rulefn, permission) reducer = lambda q, r: r[0](permission=r[1], query=q, bearer=bearer) return reduce(reducer, six.iteritems(rules), query)
<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_app(application, request_class=Request): """ Create a WSGI application out of the given Minion app. Arguments: application (Application): a minion app request_class (callable): a class to use for constructing incoming requests out of the WSGI environment. It will be passed a single arg, the environ. By default, this is :class:`minion.request.WSGIRequest` if unprovided. """
def wsgi(environ, start_response): response = application.serve( request=request_class(environ), path=environ.get("PATH_INFO", ""), ) start_response( response.status, [ (name, b",".join(values)) for name, values in response.headers.canonicalized() ], ) return [response.content] return wsgi
<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_documentation(self, request, *args, **kw): """ Generate the documentation. """
ret = dict() ret['resource'] = self.name() ret['urls'] = self._get_url_doc() ret['description'] = self.__doc__ ret['representation'] = self._get_representation_doc() ret['methods'] = self._get_method_doc() return ret
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _serialize_object(self, response_data, request): """ Override to not serialize doc responses. """
if self._is_doc_request(request): return response_data else: return super(DocumentedResource, self)._serialize_object( response_data, request)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _validate_output_data( self, original_res, serialized_res, formatted_res, request): """ Override to not validate doc output. """
if self._is_doc_request(request): return else: return super(DocumentedResource, self)._validate_output_data( original_res, serialized_res, formatted_res, request)
<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_method(self, request): """ Override to check if this is a documentation request. """
if self._is_doc_request(request): return self.get_documentation else: return super(DocumentedResource, self)._get_method(request)
<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_representation_doc(self): """ Return documentation for the representation of the resource. """
if not self.representation: return 'N/A' fields = {} for name, field in self.representation.fields.items(): fields[name] = self._get_field_doc(field) return fields
<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_field_doc(self, field): """ Return documentation for a field in the representation. """
fieldspec = dict() fieldspec['type'] = field.__class__.__name__ fieldspec['required'] = field.required fieldspec['validators'] = [{validator.__class__.__name__: validator.__dict__} for validator in field.validators] return fieldspec
<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_doc(self): """ Return a list of URLs that map to this resource. """
resolver = get_resolver(None) possibilities = resolver.reverse_dict.getlist(self) urls = [possibility[0] for possibility in possibilities] return urls
<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_method_doc(self): """ Return method documentations. """
ret = {} for method_name in self.methods: method = getattr(self, method_name, None) if method: ret[method_name] = method.__doc__ return ret
<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_process(self, command, shell=True, stdout=None, stderr=None, env=None): """ Execute a process using subprocess.Popen, setting the backend's DISPLAY """
env = env if env is not None else dict(os.environ) env['DISPLAY'] = self.display return subprocess.Popen(command, shell=shell, stdout=stdout, stderr=stderr, env=env)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pause(self, instance_id, keep_provisioned=True): """shuts down the instance without destroying it. The AbstractCloudProvider class uses 'stop' to refer to destroying a VM, so use 'pause' to mean powering it down while leaving it allocated. :param str instance_id: instance identifier :return: None """
try: if self._paused: log.debug("node %s is already paused", instance_id) return self._paused = True post_shutdown_action = 'Stopped' if keep_provisioned else \ 'StoppedDeallocated' result = self._subscription._sms.shutdown_role( service_name=self._cloud_service._name, deployment_name=self._cloud_service._name, role_name=self._qualified_name, post_shutdown_action=post_shutdown_action) self._subscription._wait_result(result) except Exception as exc: log.error("error pausing instance %s: %s", instance_id, exc) raise log.debug('paused instance(instance_id=%s)', instance_id)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def restart(self, instance_id): """restarts a paused instance. :param str instance_id: instance identifier :return: None """
try: if not self._paused: log.debug("node %s is not paused, can't restart", instance_id) return self._paused = False result = self._subscription._sms.start_role( service_name=self._cloud_service._name, deployment_name=self._cloud_service._name, role_name=instance_id) self._subscription._wait_result(result) except Exception as exc: log.error('error restarting instance %s: %s', instance_id, exc) raise log.debug('restarted instance(instance_id=%s)', instance_id)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _save_or_update(self): """Save or update the private state needed by the cloud provider. """
with self._resource_lock: if not self._config or not self._config._storage_path: raise Exception("self._config._storage path is undefined") if not self._config._base_name: raise Exception("self._config._base_name is undefined") if not os.path.exists(self._config._storage_path): os.makedirs(self._config._storage_path) path = self._get_cloud_provider_storage_path() with open(path, 'wb') as storage: pickle.dump(self._config, storage, pickle.HIGHEST_PROTOCOL) pickle.dump(self._subscriptions, storage, pickle.HIGHEST_PROTOCOL)
<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_path(root, path, default=_UNSET): """Retrieve a value from a nested object via a tuple representing the lookup path. 3 The path format is intentionally consistent with that of :func:`remap`. One of get_path's chief aims is improved error messaging. EAFP is great, but the error messages are not. For instance, ``root['a']['b']['c'][2][1]`` gives back ``IndexError: list index out of range`` What went out of range where? get_path currently raises ``PathAccessError: could not access 2 from path ('a', 'b', 'c', 2, 1), got error: IndexError('list index out of range',)``, a subclass of IndexError and KeyError. You can also pass a default that covers the entire operation, should the lookup fail at any level. Args: root: The target nesting of dictionaries, lists, or other objects supporting ``__getitem__``. path (tuple): A list of strings and integers to be successively looked up within *root*. default: The value to be returned should any ``PathAccessError`` exceptions be raised. """
if isinstance(path, basestring): path = path.split('.') cur = root try: for seg in path: try: cur = cur[seg] except (KeyError, IndexError) as exc: raise PathAccessError(exc, seg, path) except TypeError as exc: # either string index in a list, or a parent that # doesn't support indexing try: seg = int(seg) cur = cur[seg] except (ValueError, KeyError, IndexError, TypeError): if not is_iterable(cur): exc = TypeError('%r object is not indexable' % type(cur).__name__) raise PathAccessError(exc, seg, path) except PathAccessError: if default is _UNSET: raise return default return cur
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __query(p, k, v, accepted_keys=None, required_values=None, path=None, exact=True): """ Query function given to visit method :param p: visited path in tuple form :param k: visited key :param v: visited value :param accepted_keys: list of keys where one must match k to satisfy query. :param required_values: list of values where one must match v to satisfy query :param path: exact path in tuple form that must match p to satisfy query :param exact: if True then key and value match uses contains function instead of == :return: True if all criteria are satisfied, otherwise False """
# if not k: # print '__query p k:', p, k # print p, k, accepted_keys, required_values, path, exact def as_values_iterable(v): if isinstance(v, dict): return v.values() elif isinstance(v, six.string_types): return [v] else: # assume is already some iterable type return v if path and path != p: return False if accepted_keys: if isinstance(accepted_keys, six.string_types): accepted_keys = [accepted_keys] if len([akey for akey in accepted_keys if akey == k or (not exact and akey in k)]) == 0: return False if required_values: if isinstance(required_values, six.string_types): required_values = [required_values] # Find all terms in the vfilter that have a match somewhere in the values of the v dict. If the # list is shorter than vfilter then some terms did not match and this v fails the test. if len(required_values) > len([term for term in required_values for nv in as_values_iterable(v) if term == nv or (not exact and term in nv)]): return False return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_image_url(self, image_id): """Gets the url for the specified image. Unfortunatly this only works for images uploaded by the user. The images provided by google will not be found. :param str image_id: image identifier :return: str - api url of the image """
gce = self._connect() filter = "name eq %s" % image_id request = gce.images().list(project=self._project_id, filter=filter) response = self._execute_request(request) response = self._wait_until_done(response) image_url = None if "items" in response: image_url = response["items"][0]["selfLink"] if image_url: return image_url else: raise ImageError("Could not find given image id `%s`" % image_id)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def execute(self): """ Load the cluster and build a GC3Pie configuration snippet. """
creator = make_creator(self.params.config, storage_path=self.params.storage) cluster_name = self.params.cluster try: cluster = creator.load_cluster(cluster_name) except (ClusterNotFound, ConfigurationError) as ex: log.error("Listing nodes from cluster %s: %s\n" % (cluster_name, ex)) return from elasticluster.gc3pie_config import create_gc3pie_config_snippet if self.params.append: path = os.path.expanduser(self.params.append) try: fd = open(path, 'a') fd.write(create_gc3pie_config_snippet(cluster)) fd.close() except IOError as ex: log.error("Unable to write configuration to file %s: %s", path, ex) else: print(create_gc3pie_config_snippet(cluster))
<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_xml(self, outfile, encoding="UTF-8"): """Write the Media RSS Feed's XML representation to the given file."""
# we add the media namespace if we see any media items if any([key for item in self.items for key in vars(item) if key.startswith('media_') and getattr(item, key)]): self.rss_attrs["xmlns:media"] = "http://search.yahoo.com/mrss/" self.generator = _generator_name super(MediaRSS2, self).write_xml(outfile, encoding)
<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_attribute(self, name, value, allowed_values=None): """Add an attribute to the MediaContent element."""
if value and value != 'none': if isinstance(value, (int, bool)): value = str(value) if allowed_values and value not in allowed_values: raise TypeError( "Attribute '" + name + "' must be one of " + str( allowed_values) + " but is '" + str(value) + "'") self.element_attrs[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 check_complicance(self): """Check compliance with Media RSS Specification, Version 1.5.1. see http://www.rssboard.org/media-rss Raises AttributeError on error. """
# check Media RSS requirement: one of the following elements is # required: media_group | media_content | media_player | media_peerLink # | media_location. We do the check only if any media_... element is # set to allow non media feeds if(any([ma for ma in vars(self) if ma.startswith('media_') and getattr(self, ma)]) and not self.media_group and not self.media_content and not self.media_player and not self.media_peerLink and not self.media_location ): raise AttributeError( "Using media elements requires the specification of at least " "one of the following elements: 'media_group', " "'media_content', 'media_player', 'media_peerLink' or " "'media_location'.") # check Media RSS requirement: if media:player is missing all # media_content elements need to have url attributes. if not self.media_player: if self.media_content: # check if all media_content elements have a URL set if isinstance(self.media_content, list): if not all([False for mc in self.media_content if 'url' not in mc.element_attrs]): raise AttributeError( "MediaRSSItems require a media_player attribute " "if a media_content has no url set.") else: if not self.media_content.element_attrs['url']: raise AttributeError( "MediaRSSItems require a media_player attribute " "if a media_content has no url set.") pass elif self.media_group: # check media groups without player if its media_content # elements have a URL set raise NotImplementedError( "MediaRSSItem: media_group check not implemented yet.")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def publish_extensions(self, handler): """Publish the Media RSS Feed elements as XML."""
if isinstance(self.media_content, list): [PyRSS2Gen._opt_element(handler, "media:content", mc_element) for mc_element in self.media_content] else: PyRSS2Gen._opt_element(handler, "media:content", self.media_content) if hasattr(self, 'media_title'): PyRSS2Gen._opt_element(handler, "media:title", self.media_title) if hasattr(self, 'media_text'): PyRSS2Gen._opt_element(handler, "media:text", self.media_text)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_conversations(self): """ Returns list of Conversation objects """
cs = self.data["data"] res = [] for c in cs: res.append(Conversation(c)) return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _accumulate(iterable, func=(lambda a,b:a+b)): # this was from the itertools documentation 'Return running totals' # accumulate([1,2,3,4,5]) --> 1 3 6 10 15 # accumulate([1,2,3,4,5], operator.mul) --> 1 2 6 24 120 it = iter(iterable) try: total = next(it) except StopIteration: return yield total for element in it: total = func(total, element) yield total
<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_methods(methods_to_add): ''' use this to bulk add new methods to Generator ''' for i in methods_to_add: try: Generator.add_method(*i) except Exception as ex: raise Exception('issue adding {} - {}'.format(repr(i), ex))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dirsize_get(l_filesWithoutPath, **kwargs): """ Sample callback that determines a directory size. """
str_path = "" for k,v in kwargs.items(): if k == 'path': str_path = v d_ret = {} l_size = [] size = 0 for f in l_filesWithoutPath: str_f = '%s/%s' % (str_path, f) if not os.path.islink(str_f): try: size += os.path.getsize(str_f) except: pass str_size = pftree.sizeof_fmt(size) return { 'status': True, 'diskUsage_raw': size, 'diskUsage_human': str_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 inputReadCallback(self, *args, **kwargs): """ Test for inputReadCallback This method does not actually "read" the input files, but simply returns the passed file list back to caller """
b_status = True filesRead = 0 for k, v in kwargs.items(): if k == 'l_file': l_file = v if k == 'path': str_path = v if len(args): at_data = args[0] str_path = at_data[0] l_file = at_data[1] self.dp.qprint("reading (in path %s):\n%s" % (str_path, self.pp.pformat(l_file)), level = 5) filesRead = len(l_file) if not len(l_file): b_status = False return { 'status': b_status, 'l_file': l_file, 'str_path': str_path, 'filesRead': filesRead }