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 connect_to_ipykernel(self, service_name, timeout=10): """Connect to an IPython kernel as soon as its message is logged."""
kernel_json_file = self.wait_for_ipykernel(service_name, timeout=10) self.start_interactive_mode() subprocess.check_call([ sys.executable, "-m", "IPython", "console", "--existing", kernel_json_file ]) self.stop_interactive_mode()
<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_class_graph(modules, klass=None, graph=None): """ Builds up a graph of the DictCell subclass structure """
if klass is None: class_graph = nx.DiGraph() for name, classmember in inspect.getmembers(modules, inspect.isclass): if issubclass(classmember, Referent) and classmember is not Referent: TaxonomyCell.build_class_graph(modules, classmember, class_graph) return class_graph else: parents = getattr(klass, '__bases__') for parent in parents: if parent != Referent: graph.add_edge(parent.__name__, klass.__name__) # store pointer to classes in property 'class' graph.node[parent.__name__]['class'] = parent graph.node[klass.__name__]['class'] = klass if issubclass(parent, Referent): TaxonomyCell.build_class_graph(modules, parent, graph)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cells_from_defaults(clz, jsonobj): """ Creates a referent instance of type `json.kind` and initializes it to default values. """
# convert strings to dicts if isinstance(jsonobj, (str, unicode)): jsonobj = json.loads(jsonobj) assert 'cells' in jsonobj, "No cells in object" domain = TaxonomyCell.get_domain() cells = [] for num, cell_dna in enumerate(jsonobj['cells']): assert 'kind' in cell_dna, "No type definition" classgenerator = domain.node[cell_dna['kind']]['class'] cell = classgenerator() cell['num'].merge(num) for attr, val in cell_dna.items(): if not attr in ['kind']: cell[attr].merge(val) cells.append(cell) return cells
<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_element_types(obj, **kwargs): """Get element types as a set."""
max_iterable_length = kwargs.get('max_iterable_length', 10000) consume_generator = kwargs.get('consume_generator', False) if not isiterable(obj): return None if isgenerator(obj) and not consume_generator: return None t = get_types(obj, **kwargs) if not t['too_big']: if t['types']: return "Element types: {}".format(', '.join([extract_type(t) for t in t['types']])) else: return None else: return "Element types: {}".format(', '.join([extract_type(t) for t in t['types']])) + " (based on first {} elements.)".format(max_iterable_length)
<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_dir(self, base_dir): """ Creates stats directory for storing stat files. `base_dir` Base directory. """
stats_dir = self._sdir(base_dir) if not os.path.isdir(stats_dir): try: os.mkdir(stats_dir) except OSError: raise errors.DirectorySetupFail()
<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_task(self, task): """ Logs task record to file. `task` ``Task`` instance. """
if not task.duration: return self._setup_dir(task.base_dir) stats_dir = self._sdir(task.base_dir) duration = task.duration while duration > 0: # build filename date = (datetime.datetime.now() - datetime.timedelta(minutes=duration)) date_str = date.strftime('%Y%m%d') filename = os.path.join(stats_dir, '{0}.json'.format(date_str)) with open(filename, 'a+') as file_: # fetch any existing data try: file_.seek(0) data = json.loads(file_.read()) except (ValueError, OSError): data = {} if not task.name in data: data[task.name] = 0 # how much total time for day try: total_time = sum(int(x) for x in data.values()) if total_time > MINS_IN_DAY: total_time = MINS_IN_DAY except ValueError: total_time = 0 # constrain to single day amount = duration if amount + total_time > MINS_IN_DAY: amount = MINS_IN_DAY - total_time # invalid or broken state, bail if amount <= 0: break data[task.name] += amount duration -= amount # write file try: file_.seek(0) file_.truncate(0) file_.write(json.dumps(data)) except (ValueError, OSError): pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _fuzzy_time_parse(self, value): """ Parses a fuzzy time value into a meaningful interpretation. `value` String value to parse. """
value = value.lower().strip() today = datetime.date.today() if value in ('today', 't'): return today else: kwargs = {} if value in ('y', 'yesterday'): kwargs['days'] = -1 elif value in ('w', 'wk', 'week', 'last week'): kwargs['days'] = -7 else: # match days match = re.match(r'(\d+)\s*(d|day|days)\s*(ago)?$', value) if match: kwargs['days'] = -int(match.groups(1)[0]) else: # match weeks match = re.match(r'(\d+)\s*(w|wk|week|weeks)\s*(ago)?$', value) if match: kwargs['weeks'] = -int(match.groups(1)[0]) if kwargs: return today + datetime.timedelta(**kwargs) 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_stats(self, task, start_date): """ Fetches statistic information for given task and start range. """
stats = [] stats_dir = self._sdir(task.base_dir) date = start_date end_date = datetime.date.today() delta = datetime.timedelta(days=1) while date <= end_date: date_str = date.strftime('%Y%m%d') filename = os.path.join(stats_dir, '{0}.json'.format(date_str)) if os.path.exists(filename): try: # fetch stats content with open(filename, 'r') as file_: data = json.loads(file_.read()) # sort descending by time stats.append((date, sorted(data.iteritems(), key=lambda x: x[1], reverse=True))) except (json.JSONDecodeError, OSError): pass date += delta # next day return stats
<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_stats(self, env, stats): """ Prints statistic information using io stream. `env` ``Environment`` object. `stats` Tuple of task stats for each date. """
def _format_time(mins): """ Generates formatted time string. """ mins = int(mins) if mins < MINS_IN_HOUR: time_str = '0:{0:02}'.format(mins) else: hours = mins // MINS_IN_HOUR mins %= MINS_IN_HOUR if mins > 0: time_str = '{0}:{1:02}'.format(hours, mins) else: time_str = '{0}'.format(hours) return time_str if not stats: env.io.write('No stats found.') return for date, tasks in stats: env.io.write('') total_mins = float(sum(v[1] for v in tasks)) env.io.write('[ {0} ]'.format(date.strftime('%Y-%m-%d'))) env.io.write('') for name, mins in tasks: # format time time_str = _format_time(mins) # generate stat line line = ' {0:>5}'.format(time_str) line += ' ({0:2.0f}%) - '.format(mins * 100.0 / total_mins) if len(name) > 55: name = name[:55] + '...' line += name env.io.write(line) # generate total line env.io.write('_' * len(line)) time_str = _format_time(total_mins) env.io.write(' {0:>5} (total)'.format(time_str)) env.io.write('')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(self): """called to create the work space"""
self.logger.log(logging.DEBUG, 'os.mkdir %s', self.name) os.mkdir(self.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 bodycomp(mass, tbw, method='reilly', simulate=False, n_rand=1000): '''Create dataframe with derived body composition values Args ---- mass: ndarray Mass of the seal (kg) tbw: ndarray Total body water (kg) method: str name of method used to derive composition values simulate: bool switch for generating values with random noise n_rand: int number of density values to simulate Returns ------- field: pandas.Dataframe dataframe containing columns for each body composition value References ---------- Reilly, J.J., Fedak, M.A., 1990. Measurement of the body composition of living gray seals by hydrogen isotope dilution. Journal of Applied Physiology 69, 885–891. Gales, R., Renouf, D., Noseworthy, E., 1994. Body composition of harp seals. Canadian journal of zoology 72, 545–551. ''' import numpy import pandas if len(mass) != len(tbw): raise SystemError('`mass` and `tbw` arrays must be the same length') bc = pandas.DataFrame(index=range(len(mass))) rnorm = lambda n, mu, sigma: numpy.random.normal(mu, sigma, n) if method == 'reilly': if simulate is True: bc['ptbw'] = 100 * (tbw / mass) bc['ptbf'] = 105.1 - (1.47 * bc['ptbw']) + rnorm(n_rand, 0, 1.1) bc['ptbp'] = (0.42 * bc['ptbw']) - 4.75 + rnorm(n_rand, 0, 0.8) bc['tbf'] = mass * (bc['ptbf'] / 100) bc['tbp'] = mass * (bc['ptbp'] / 100) bc['tba'] = 0.1 - (0.008 * mass) + \ (0.05 * tbw) + rnorm(0, 0.3, n_rand) bc['tbge'] = (40.8 * mass) - (48.5 * tbw) - \ 0.4 + rnorm(0, 17.2, n_rand) else: bc['ptbw'] = 100 * (tbw / mass) bc['ptbf'] = 105.1 - (1.47 * bc['ptbw']) bc['ptbp'] = (0.42 * bc['ptbw']) - 4.75 bc['tbf'] = mass * (bc['ptbf'] / 100) bc['tbp'] = mass * (bc['ptbp'] / 100) bc['tba'] = 0.1 - (0.008 * mass) + (0.05 * tbw) bc['tbge'] = (40.8 * mass) - (48.5 * tbw) - 0.4 elif method == 'gales': if simulate is True: raise ValueError('Random error simulation is currently only ' 'implemented for `method` `reilly`. `simulate` must be passed ' 'as `False` when using `method` `gales`.') else: bc['ptbw'] = 100 * (tbw / mass) bc['tbf'] = mass - (1.37 * tbw) bc['tbp'] = 0.27 * (mass - bc['tbf']) bc['tbge'] = (40.8 * mass) - (48.5 * tbw) - 0.4 bc['ptbf'] = 100 * (bc['tbf'] / mass) bc['ptbp'] = 100 * (bc['tbp'] / mass) else: raise ValueError('`method` must be either `reilly` or `gales`, not ' '`{}`'.format(method)) return bc
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def perc_bc_from_lipid(perc_lipid, perc_water=None): '''Calculate body composition component percentages based on % lipid Calculation of percent protein and percent ash are based on those presented in Reilly and Fedak (1990). Args ---- perc_lipid: float or ndarray 1D array of percent lipid values from which to calculate body composition perc_water: float or ndarray 1D array of percent water values from which to calculate body composition (Default `None`). If no values are passed, calculations are performed with values from Biuw et al. (2003). Returns ------- perc_water: float or ndarray 1D array of percent water values perc_protein: float or ndarray 1D array of percent protein values perc_ash: float or ndarray 1D array of percent ash values References ---------- Biuw, M., 2003. Blubber and buoyancy: monitoring the body condition of free-ranging seals using simple dive characteristics. Journal of Experimental Biology 206, 3405–3423. doi:10.1242/jeb.00583 Reilly, J.J., Fedak, M.A., 1990. Measurement of the body composition of living gray seals by hydrogen isotope dilution. Journal of Applied Physiology 69, 885–891. ''' import numpy # Cast iterables to numpy arrays if numpy.iterable(perc_lipid): perc_lipid = numpy.asarray(perc_lipid) if numpy.iterable(perc_water): perc_water = numpy.asarray(perc_water) if not perc_water: # TODO check where `perc_water` values come from perc_water = 71.4966 - (0.6802721 * perc_lipid) perc_protein = (0.42 * perc_water) - 4.75 perc_ash = 100 - (perc_lipid + perc_water + perc_protein) return perc_water, perc_protein, perc_ash
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def lip2dens(perc_lipid, dens_lipid=0.9007, dens_prot=1.34, dens_water=0.994, dens_ash=2.3): '''Derive tissue density from lipids The equation calculating animal density is from Biuw et al. (2003), and default values for component densities are from human studies collected in the book by Moore et al. (1963). Args ---- perc_lipid: float or ndarray Percent lipid of body composition dens_lipid: float Density of lipid in animal (Default 0.9007 g/cm^3) dens_prot: float Density of protein in animal (Default 1.34 g/cm^3) dens_water: float Density of water in animal (Default 0.994 g/cm^3) dens_ash: float Density of ash in animal (Default 2.3 g/cm^3) Returns ------- dens_gcm3: float or ndarray Density of seal calculated from percent compositions and densities of components from Moore et al. (1963) References ---------- Biuw, M., 2003. Blubber and buoyancy: monitoring the body condition of free-ranging seals using simple dive characteristics. Journal of Experimental Biology 206, 3405–3423. doi:10.1242/jeb.00583 Moore FD, Oleson KH, McMurrery JD, Parker HV, Ball MR, Boyden CM. The Body Cell Mass and Its Supporting Environment - The Composition in Health and Disease. Philadelphia: W.B. Saunders Company; 1963. 535 p. ISBN:0-7216-6480-6 ''' import numpy # Cast iterables to numpy array if numpy.iterable(perc_lipid): perc_lipid = numpy.asarray(perc_lipid) perc_water, perc_protein, perc_ash = perc_bc_from_lipid(perc_lipid) dens_gcm3 = (dens_lipid * (0.01 * perc_lipid)) + \ (dens_prot * (0.01 * perc_protein)) + \ (dens_water * (0.01 * perc_water)) + \ (dens_ash * (0.01 * perc_ash)) return dens_gcm3
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def dens2lip(dens_gcm3, dens_lipid=0.9007, dens_prot=1.34, dens_water=0.994, dens_ash=2.3): '''Get percent composition of animal from body density The equation calculating animal density is from Biuw et al. (2003), and default values for component densities are from human studies collected in the book by Moore et al. (1963). Args ---- dens_gcm3: float or ndarray An array of seal densities (g/cm^3). The calculations only yield valid percents with densities between 0.888-1.123 with other parameters left as defaults. dens_lipid: float Density of lipid content in the animal (g/cm^3) dens_prot: float Density of protein content in the animal (g/cm^3) dens_water: float Density of water content in the animal (g/cm^3) dens_ash: float Density of ash content in the animal (g/cm^3) Returns ------- perc_all: pandas.DataFrame Dataframe of components of body composition References ---------- Biuw, M., 2003. Blubber and buoyancy: monitoring the body condition of free-ranging seals using simple dive characteristics. Journal of Experimental Biology 206, 3405–3423. doi:10.1242/jeb.00583 Moore FD, Oleson KH, McMurrery JD, Parker HV, Ball MR, Boyden CM. The Body Cell Mass and Its Supporting Environment - The Composition in Health and Disease. Philadelphia: W.B. Saunders Company; 1963. 535 p. ISBN:0-7216-6480-6 ''' import numpy # Cast iterables to numpy array if numpy.iterable(dens_gcm3): dens_gcm3 = numpy.asarray(dens_gcm3) # Numerators ad_num = -3.2248 * dens_ash pd_num = -25.2786 * dens_prot wd_num = -71.4966 * dens_water # Denominators ad_den = -0.034 * dens_ash pd_den = -0.2857 * dens_prot wd_den = -0.6803 * dens_water perc_lipid = ((100 * dens_gcm3) + ad_num + pd_num + wd_num) / \ (dens_lipid + ad_den + pd_den + wd_den) return perc_lipid
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def diff_speed(sw_dens=1.028, dens_gcm3=1.053, seal_length=300, seal_girth=200, Cd=0.09): '''Calculate terminal velocity of animal with a body size Args ---- sw_dens: float Density of seawater (g/cm^3) dens_gcm3: float Density of animal (g/cm^3) seal_length: float Length of animal (cm) seal_girth: float Girth of animal (cm) Cd: float Drag coefficient of object in fluid, unitless Returns ------- Vt: float Terminal velocity of animal with given body dimensions (m/s). References ---------- Biuw, M., 2003. Blubber and buoyancy: monitoring the body condition of free-ranging seals using simple dive characteristics. Journal of Experimental Biology 206, 3405–3423. doi:10.1242/jeb.00583 Vogel, S., 1994. Life in Moving Fluids: The Physical Biology of Flow. Princeton University Press. ''' import numpy surf, vol = surf_vol(seal_length, seal_girth) Fb = buoyant_force(dens_gcm3, vol, sw_dens) x = 2 * (Fb/(Cd * sw_dens * (surf*1000))) if x >= 0: Vt = numpy.sqrt(x) else: Vt = -numpy.sqrt(-x) return Vt
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def surf_vol(length, girth): '''Calculate the surface volume of an animal from its length and girth Args ---- length: float or ndarray Length of animal (m) girth: float or ndarray Girth of animal (m) Returns ------- surf: Surface area of animal (m^2) vol: float or ndarray Volume of animal (m^3) ''' import numpy a_r = 0.01 * girth / (2 * numpy.pi) stl_l = 0.01 * length c_r = stl_l / 2 e = numpy.sqrt(1-(a_r**2/c_r**2)) surf = ((2*numpy.pi * a_r**2) + \ (2*numpy.pi * ((a_r * c_r)/e)) * 1/(numpy.sin(e))) vol = (((4/3) * numpy.pi)*(a_r**2) * c_r) return surf, vol
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def calc_seal_volume(mass_kg, dens_kgm3, length=None, girth=None): '''Calculate an animal's volume from mass and density or length and girth Args ---- mass_kg: float or ndarray Mass of animal (kg) dens_kgm3: float or ndarray Density of animal (kg/m^3) length: float or None Length of animal. Default `None` (m) girth: float or None Girth of animal. Default `None` (m) Returns ------- vol_kgm3: float or ndarray Volume of animal (m^3) ''' if (length is not None) and (girth is not None): _, seal_vol = surf_vol(length, girth) else: seal_vol = mass_kg / dens_kgm3 return seal_vol
<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_new(self, hueobjecttype): ''' Starts a search for new Hue objects ''' assert hueobjecttype in ['lights', 'sensors'], \ 'Unsupported object type {}'.format(hueobjecttype) url = '{}/{}'.format(self.API, hueobjecttype) return self._request( method='POST', url=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 __get_new(self, hueobjecttype): ''' Get a list of newly found Hue object ''' assert hueobjecttype in ['lights', 'sensors'], \ 'Unsupported object type {}'.format(hueobjecttype) url = '{}/{}/new'.format(self.API, hueobjecttype) return self._request(url=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 get_context_manager(self, default): """A context manager for manipulating a default stack."""
try: self.stack.append(default) yield default finally: if self.enforce_nesting: if self.stack[-1] is not default: raise AssertionError( "Nesting violated for default stack of %s objects" % type(default)) self.stack.pop() else: self.stack.remove(default)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def args2body(self, parsed_args, body=None): """Add in conditional args and then return all conn info."""
if body is None: body = {} if parsed_args.dpd: vpn_utils.validate_dpd_dict(parsed_args.dpd) body['dpd'] = parsed_args.dpd if parsed_args.local_ep_group: _local_epg = neutronv20.find_resourceid_by_name_or_id( self.get_client(), 'endpoint_group', parsed_args.local_ep_group) body['local_ep_group_id'] = _local_epg if parsed_args.peer_ep_group: _peer_epg = neutronv20.find_resourceid_by_name_or_id( self.get_client(), 'endpoint_group', parsed_args.peer_ep_group) body['peer_ep_group_id'] = _peer_epg return {self.resource: body}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def copy_attribute_values(source, target, property_names): """Function to copy attributes from a source to a target object. This method copies the property values in a given list from a given source object to a target source object. :param source: The source object that is to be inspected for property values. :type source: type :param target: The target object that will be modified with values found in src. :type target: type :param property_names: List of property names whose values are to be copied from source to object. :type property_names: list, set :rtype: None :raises ValueError: If src is None. :raises ValueError: If target is None. :raises ValueError: If property list is not iterable or None. The *copy_attribute_values* method will only copy the values from src when a property name is found in the src. In cases where a property value is not found in the src object, then no change to the target object is made. :Example Usage: """
if source is None: raise ValueError('"source" must be provided.') if target is None: raise ValueError('"target" must be provided.') if property_names is None: raise ValueError('"property_list" must be provided.') if (not hasattr(property_names, '__iter__') or isinstance(property_names, str)): raise ValueError( '"property_names" must be a sequence type, such as list or set.') for property_name in property_names: if hasattr(source, property_name): setattr(target, property_name, getattr(source, property_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 _configure_logging(self): """This method configures the self.log entity for log handling. :return: None The method will cognate_configure the logging facilities for the derive service instance. This includes setting up logging to files and console. The configured log will be available to the service instance with `self.log` """
self.log_level = ComponentCore.LOG_LEVEL_MAP.get(self.log_level, logging.ERROR) # assign the windmill instance logger self.log = logging.getLogger(self.service_name) self.log.setLevel(self.log_level) # cognate_configure log file output if necessary if self.log_path: file_path = self.log_path if not self.log_path.endswith('.log'): file_path = os.path.join(self.log_path, self.service_name + '.log') file_handler = WatchedFileHandler(file_path) file_handler.setLevel(self.log_level) file_handler.setFormatter(self._log_formatter()) self.log.addHandler(file_handler) # if we are in verbose mode, the we send log output to console if self.verbose: # add the console logger for verbose mode console_handler = logging.StreamHandler() console_handler.setLevel(self.log_level) console_handler.setFormatter(self._log_formatter()) self.log.addHandler(console_handler) self.log.info('Logging configured for: %s', self.service_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 _execute_configuration(self, argv): """This method assigns an argument list to attributes assigned to self. :param argv: A list of arguments. :type argv: list<str> :return: None This is the work horse method that does the work of invoking *configuration_option* and *cognate_configure* methods on progenitor classes of *ComponentCore*. In addition it takes the resolved arguments from *argparse.ArgumentParser* and assigns them to `self`. """
if argv is None: argv = [] # just create an empty arg list # ensure that sys.argv is not modified in case it was passed. if argv is sys.argv: argv = list(sys.argv) # If this is the command line args directly passed, then we need to # remove the first argument which is the python execution command. # The first argument is the name of the executing python script. if len(argv) > 0 and argv[0].endswith('.py'): argv.pop(0) # execute configuration_option method on all child classes of # ComponentCore to gather all of the runtime options. arg_parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter) self.invoke_method_on_children(func_name='cognate_options', arg_parser=arg_parser) # resolve configuration options necessary for runtime execution property_list = [] # noinspection PyProtectedMember for action in arg_parser._get_positional_actions(): # pylint: disable=protected-access property_list.append(action.dest) # noinspection PyProtectedMember for action in arg_parser._get_optional_actions(): # pylint: disable=protected-access property_list.append(action.dest) property_list.remove('help') # remove the help option args = arg_parser.parse_args(argv) # map the properties to attributes assigned to self instance copy_attribute_values(source=args, target=self, property_names=property_list) # now execute the configuration call on each base class # in the class inheritance chain self.invoke_method_on_children(func_name='cognate_configure', args=args) self.log.debug( 'Component service configuration complete with argv: %s', args)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def invoke_method_on_children(self, func_name=None, *args, **kwargs): """This helper method will walk the primary base class hierarchy to invoke a method if it exists for a given child base class. :param func_name: The name of a function to search for invocation. :type func_name: str :param args: An argument list to pass to the target function. :type args: list :param kwargs: A dictionary of name/value pairs to pass to the target function as named arguments. :type kwargs: dict :return: None :raises ValueError: Thrown if no function name is provided. In an effort to explain, assume that a class hierarchy has been defined as in the image below: .. image:: images/invoke_method_on_children_class_hierarchy.png *invoke_method_on_children* will traverse the class hierarchy invoking target method *the_func* on each child class. This is different from normal python resolution, which will only invoke the first instance of the method defined in the class hierarchy, which would be *Child3.the_func*. .. image:: images/invoke_method_on_children.png .. note:: Mind the flow of invocation on the class hierarchy. Invocation of target *func_name* is from the *ComponentCore* class as the starting point, and the search continuing out toward the final ancestor class. ::Example Usage: To utilize this method, a function name must be provided. .. warning:: Beware mistyped method names. If a method name is supplied for a method that does not exist, the *invoke_method_on_children* will raise no exception. Traceback (most recent call last): ValueError: invoke_method_on_children:func_name parameter required In actual usage, declare a *ComponentCore* derived child class with a target function. It is possible to have more than one ancestor class with the target function defined. The *invoke_method_on_children* will execute the function on each of the child classes. With an instance of a *AttributeHelper* child class, we can invoke the method in two ways, as exampled below. ('a_key:', 'a_value') ('a_key:', 'value') """
if func_name is None: raise ValueError( 'invoke_method_on_children:func_name parameter required') class_stack = [] base = self.__class__ # The root class in the hierarchy. while base is not None and base is not object: class_stack.append(base) base = base.__base__ # iterate to the next base class while len(class_stack) is not 0: base = class_stack.pop() if func_name in base.__dict__: # check the func exist on class # instance func = getattr(base, func_name) func(self, *args, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def execute(action): """ Execute the given action. An action is any object with a ``forwards()`` and ``backwards()`` method. .. code-block:: python class CreateUser(object): def __init__(self, userinfo): self.userinfo = userinfo self.user_id = None def forwards(self): self.user_id = UserStore.create(userinfo) return self.user_id def backwards(self): if self.user_id is not None: # user_id will be None if creation failed UserStore.delete(self.user_id) If the ``forwards`` method succeeds, the action is considered successful. If the method fails, the ``backwards`` method is called to revert any effect it might have had on the system. In addition to defining classes, actions may be built using the :py:func:`reversible.action` decorator. Actions may be composed together using the :py:func:`reversible.gen` decorator. :param action: The action to execute. :returns: The value returned by the ``forwards()`` method of the action. :raises: The exception raised by the ``forwards()`` method if rollback succeeded. Otherwise, the exception raised by the ``backwards()`` method is raised. """
# TODO this should probably be a class to configure logging, etc. The # global execute can refer to the "default" instance of the executor. try: return action.forwards() except Exception: log.exception('%s failed to execute. Rolling back.', action) try: action.backwards() except Exception: log.exception('%s failed to roll back.', action) raise else: 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 action(forwards=None, context_class=None): """ Decorator to build functions. This decorator can be applied to a function to build actions. The decorated function becomes the ``forwards`` implementation of the action. The first argument of the ``forwards`` implementation is a context object that can be used to share state between the forwards and backwards implementations. This argument is passed implicitly by ``reversible`` and callers of the function shouldn't provide it. .. code-block:: python @reversible.action def create_order(context, order_details): order_id = OrderStore.put(order_details) context['order_id'] = order_id return order_id The ``.backwards`` attribute of the decorated function can itself be used as a decorator to specify the ``backwards`` implementation of the action. .. code-block:: python @create_order.backwards def delete_order(context, order_details): if 'order_id' in context: # order_id will be absent if create_order failed OrderStore.delete(context['order_id']) # Note that the context argument was not provided here. It's added # implicitly by the library. action = create_order(order_details) order_id = reversible.execute(action) Both, the ``forwards`` and ``backwards`` implementations will be called with the same arguments. Any information that needs to be sent from ``forwards`` to ``backwards`` must be added to the context object. The context object defaults to a dictionary. An alternative context constructor may be provided using the ``context_class`` argument. It will be called with no arguments to construct the context object. .. code-block:: python @reversible.action(context_class=UserInfo) def create_user(user_info, user_details): user_info.user_id = UserStore.put(user_details) return user_info Note that a backwards action is required. Attempts to use the action without specifying a way to roll back will fail. :param forwards: The function will be treated as the ``forwards`` implementation. :param context_class: Constructor for context objects. A single action call will have its own context object and that object will be implictly passed as the first argument to both, the ``forwards`` and the ``backwards`` implementations. :returns: If ``forwards`` was given, a partially constructed action is returned. The ``backwards`` method on that object can be used as a decorator to specify the rollback method for the action. If ``forwards`` was omitted, a decorator that accepts the ``forwards`` method is returned. """
context_class = context_class or dict def decorator(_forwards): return ActionBuilder(_forwards, context_class) if forwards is not None: return decorator(forwards) else: 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 backwards(self, backwards): """Decorator to specify the ``backwards`` action."""
if self._backwards is not None: raise ValueError('Backwards action already specified.') self._backwards = backwards return backwards
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sphere_volume(R, n): """Return the volume of a sphere in an arbitrary number of dimensions. Parameters R: array-like Radius. n: array-like The number of dimensions of the space in which the sphere lives. Returns ------- V: array-like Volume. """
return ((np.pi ** (n / 2.0)) / scipy.special.gamma(n / 2.0 + 1)) * R ** 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 sphere_radius(V, n): """Return the radius of a sphere in an arbitrary number of dimensions. Parameters V: array-like Volume. n: array-like The number of dimensions of the space in which the sphere lives. Returns ------- R: array-like Radius. """
return (((scipy.special.gamma(n / 2.0 + 1.0) * V) ** (1.0 / n)) / np.sqrt(np.pi))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def spheres_sep(ar, aR, br, bR): """Return the separation distance between two spheres. Parameters ar, br: array-like, shape (n,) in n dimensions Coordinates of the centres of the spheres `a` and `b`. aR, bR: float Radiuses of the spheres `a` and `b`. Returns ------- d: float Separation distance. A negative value means the spheres intersect each other. """
return vector.vector_mag(ar - br) - (aR + bR)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def spheres_intersect(ar, aR, br, bR): """Return whether or not two spheres intersect each other. Parameters ar, br: array-like, shape (n,) in n dimensions Coordinates of the centres of the spheres `a` and `b`. aR, bR: float Radiuses of the spheres `a` and `b`. Returns ------- intersecting: boolean True if the spheres intersect. """
return vector.vector_mag_sq(ar - br) < (aR + bR) ** 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 point_seg_sep(ar, br1, br2): """Return the minimum separation vector between a point and a line segment, in 3 dimensions. Parameters ar: array-like, shape (3,) Coordinates of a point. br1, br2: array-like, shape (3,) Coordinates for the points of a line segment Returns ------- sep: float array, shape (3,) Separation vector between point and line segment. """
v = br2 - br1 w = ar - br1 c1 = np.dot(w, v) if c1 <= 0.0: return ar - br1 c2 = np.sum(np.square(v)) if c2 <= c1: return ar - br2 b = c1 / c2 bc = br1 + b * v return ar - bc
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def readfile(filename, binary=False): """ Reads the contents of the specified file. `filename` Filename to read. `binary` Set to ``True`` to indicate a binary file. Returns string or ``None``. """
if not os.path.isfile(filename): return None try: flags = 'r' if not binary else 'rb' with open(filename, flags) as _file: return _file.read() except (OSError, IOError): 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 writefile(filename, data, binary=False): """ Write the provided data to the file. `filename` Filename to write. `data` Data buffer to write. `binary` Set to ``True`` to indicate a binary file. Returns boolean. """
try: flags = 'w' if not binary else 'wb' with open(filename, flags) as _file: _file.write(data) _file.flush() return True except (OSError, IOError): 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 which(name): """ Returns the full path to executable in path matching provided name. `name` String value. Returns string or ``None``. """
# we were given a filename, return it if it's executable if os.path.dirname(name) != '': if not os.path.isdir(name) and os.access(name, os.X_OK): return name else: return None # fetch PATH env var and split path_val = os.environ.get('PATH', None) or os.defpath # return the first match in the paths for path in path_val.split(os.pathsep): filename = os.path.join(path, name) if os.access(filename, os.X_OK): return filename 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 extract_app_paths(values, app_should_exist=True): """ Extracts application paths from the values provided. `values` List of strings to extract paths from. `app_should_exist` Set to ``True`` to check that application file exists. Returns list of strings. * Raises ``ValueError`` exception if value extraction fails. """
def _osx_app_path(name): """ Attempts to find the full application path for the name specified. `name` Application name. Returns string or ``None``. """ # we use find because it is faster to traverse the # hierachy for app dir. cmd = ('find /Applications -type d ' '-iname "{0}.app" -maxdepth 4'.format(name)) data = shell_process(cmd) if not data is None: lines = str(data).split('\n') if lines: bundle_dir = lines[0] path = os.path.join(bundle_dir, 'Contents', 'MacOS', name) if os.path.isfile(path) and os.access(path, os.X_OK): return path return None paths = set() for value in values: # split path into relevant tokens parts = list(shlex.split(value)) # program name name = parts[0] # just the name, search bin paths if os.path.dirname(name) == '': path = which(name) if not path: # MacOS X, maybe it's an application name; let's try to build # default application binary path errmsg = u'"{0}" command does not exist'.format(name) if IS_MACOSX: path = _osx_app_path(name) if not path: raise ValueError(errmsg) else: raise ValueError(errmsg) # no luck else: # relative to current working dir or full path path = os.path.realpath(name) if app_should_exist: # should be a file or link and be executable if os.path.isdir(path) or not os.access(path, os.X_OK): errmsg = u'"{0}" is not an executable file'.format(name) raise ValueError(errmsg) # update program path parts[0] = path # quote params with spaces in value parts[:] = ['"{0}"'.format(p.replace('"', '\\"')) if ' ' in p else p for p in parts] # add flattened path paths.add(' '.join(parts)) return list(paths)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shell_process(command, input_data=None, background=False, exitcode=False): """ Shells a process with the given shell command. `command` Shell command to spawn. `input_data` String to pipe to process as input. `background` Set to ``True`` to fork process into background. NOTE: This exits immediately with no result returned. `exitcode` Set to ``True`` to also return process exit status code. if `exitcode` is ``False``, then this returns output string from process or ``None`` if it failed. otherwise, this returns a tuple with output string from process or ``None`` if it failed and the exit status code. Example:: (``None``, 1) <-- failed ('Some data', 0) <-- success """
data = None try: # kick off the process kwargs = { 'shell': isinstance(command, basestring), 'stdout': subprocess.PIPE, 'stderr': subprocess.PIPE } if not input_data is None: kwargs['stdin'] = subprocess.PIPE proc = subprocess.Popen(command, **kwargs) # background exits without checking anything if not background: output, _ = proc.communicate(input_data) retcode = proc.returncode if retcode == 0: data = str(output).rstrip() else: retcode = None if input_data: raise TypeError(u'Backgrounded does not support input data.') except OSError as exc: retcode = -exc.errno if exitcode: return data, retcode else: return 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 to_utf8(buf, errors='replace'): """ Encodes a string into a UTF-8 compatible, ASCII string. `buf` string or unicode to convert. Returns string. * Raises a ``UnicodeEncodeError`` exception if encoding failed and `errors` isn't set to 'replace'. """
if isinstance(buf, unicode): return buf.encode('utf-8', errors) else: 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 from_utf8(buf, errors='replace'): """ Decodes a UTF-8 compatible, ASCII string into a unicode object. `buf` string or unicode string to convert. Returns unicode` string. * Raises a ``UnicodeDecodeError`` exception if encoding failed and `errors` isn't set to 'replace'. """
if isinstance(buf, unicode): return buf else: return unicode(buf, 'utf-8', errors)
<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, value, cfg=None): """ Returns value for this option from either cfg object or optparse option list, preferring the option list. """
if value is None and cfg: if self.option_type == 'list': value = cfg.get_list(self.name, None) else: value = cfg.get(self.name, None) if value is None: value = self.default else: parse_method = getattr(self, 'parse_%s' % (self.option_type), None) if parse_method: value = parse_method(value) return 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 add(self, *args): """Add a path template and handler. :param name: Optional. If specified, allows reverse path lookup with :meth:`reverse`. :param template: A string or :class:`~potpy.template.Template` instance used to match paths against. Strings will be wrapped in a Template instance. :param handler: A callable or :class:`~potpy.router.Route` instance which will handle calls for the given path. See :meth:`potpy.router.Router.add` for details. """
if len(args) > 2: name, template = args[:2] args = args[2:] else: name = None template = args[0] args = args[1:] if isinstance(template, tuple): template, type_converters = template template = Template(template, **type_converters) elif not isinstance(template, Template): template = Template(template) if name: self._templates[name] = template super(PathRouter, self).add(template, *args)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reverse(self, *args, **kwargs): """Look up a path by name and fill in the provided parameters. Example: '/posts/my-post' """
(name,) = args return self._templates[name].fill(**kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def match(self, methods, request_method): """Check for a method match. :param methods: A method or tuple of methods to match against. :param request_method: The method to check for a match. :returns: An empty :class:`dict` in the case of a match, or ``None`` if there is no matching handler for the given method. Example: {} """
if isinstance(methods, basestring): return {} if request_method == methods else None return {} if request_method in methods 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 coerce(self, value): """ Ensures that a value is a SetCell """
if hasattr(value, 'values') and hasattr(value, 'domain'): return value elif hasattr(value, '__iter__'): # if the values are consistent with the comparison's domains, then # copy them, otherwise, make a new domain with the values. if all(map(lambda x: x in self.domain, value)): return self._stem(self.domain, value) else: raise CellConstructionFailure("Cannot turn %s into a cell" % (value)) elif value in self.domain: return self._stem(self.domain, [value]) else: raise CellConstructionFailure("Cannot turn %s into a cell" % (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 same_domain(self, other): """ Cheap pointer comparison or symmetric difference operation to ensure domains are the same """
return self.domain == other.domain or \ len(self.domain.symmetric_difference(set(other.domain))) == 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 is_equal(self, other): """ True iff all members are the same """
other = self.coerce(other) return len(self.get_values().symmetric_difference(other.get_values())) == 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 get_indices(): """ Return a list of 3 integers representing EU indices for yesterday, today and tomorrow. """
doc = BeautifulSoup(urlopen(BASEURL)) divs = doc.select('.indices_txt') if not divs: return None sibling = divs[1].nextSibling if not sibling: return None data = sibling.nextSibling if not data: return None # the indices are in an HTML comment data = BeautifulSoup(data) divs = data.select('.selected') return map(lambda d: int(d.text), divs)
<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_dir(directory): """Create given directory, if doesn't exist. Parameters directory : string Directory path (can be relative or absolute) Returns ------- string Absolute directory path """
if not os.access(directory, os.F_OK): os.makedirs(directory) return os.path.abspath(directory)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def experiments_create(self, subject_id, image_group_id, properties): """Create an experiment object with subject, and image group. Objects are referenced by their unique identifiers. The API ensure that at time of creation all referenced objects exist. Referential consistency, however, is currently not enforced when objects are deleted. Expects experiment name in property list. Raises ValueError if no valid name is given. If any of the referenced objects do not exist a ValueError is thrown. Parameters subject_id : string Unique identifier of subject image_group_id : string Unique identifier of image group properties : Dictionary Set of experiment properties. Is required to contain at least the experiment name Returns ------- ExperimentHandle Handle for created experiment object in database """
# Ensure that reference subject exists if self.subjects_get(subject_id) is None: raise ValueError('unknown subject: ' + subject_id) # Ensure that referenced image group exists if self.image_groups_get(image_group_id) is None: raise ValueError('unknown image group: ' + image_group_id) return self.experiments.create_object(subject_id, image_group_id, properties)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def experiments_fmri_create(self, experiment_id, filename): """Create functional data object from given file and associate the object with the specified experiment. Parameters experiment_id : string Unique experiment identifier filename : File-type object Functional data file Returns ------- FMRIDataHandle Handle for created fMRI object or None if identified experiment is unknown """
# Get the experiment to ensure that it exist before we even create the # functional data object experiment = self.experiments_get(experiment_id) if experiment is None: return None # Create functional data object from given file fmri = self.funcdata.create_object(filename) # Update experiment to associate it with created fMRI object. Assign # result to experiment. Should the experiment have been deleted in # parallel the result will be None experiment = self.experiments.update_fmri_data(experiment_id, fmri.identifier) if experiment is None: # Delete fMRI object's data directory shutil.rmtree(fmri.directory) # Delete functional data object from databases self.funcdata.delete_object(fmri.identifier, erase=True) return None else: return funcdata.FMRIDataHandle(fmri, experiment_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 experiments_fmri_delete(self, experiment_id): """Delete fMRI data object associated with given experiment. Raises ValueError if an attempt is made to delete a read-only resource. Parameters experiment_id : string Unique experiment identifier Returns ------- FMRIDataHandle Handle for deleted data object or None if experiment is unknown or has no fMRI data object associated with it """
# Get experiment fMRI to ensure that it exists fmri = self.experiments_fmri_get(experiment_id) if fmri is None: return None # Delete reference fMRI data object and set reference in experiment to # None. If the result of delete fMRI object is None we return None. # Alternatively, throw an exception to signal invalid database state. fmri = self.funcdata.delete_object(fmri.identifier) if not fmri is None: self.experiments.update_fmri_data(experiment_id, None) return funcdata.FMRIDataHandle(fmri, experiment_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 experiments_fmri_download(self, experiment_id): """Download the fMRI data file associated with given experiment. Parameters experiment_id : string Unique experiment identifier Returns ------- FileInfo Information about fMRI file on disk or None if experiment is unknown or has no fMRI data associated with it """
# Get experiment fMRI to ensure that it exists fmri = self.experiments_fmri_get(experiment_id) if fmri is None: return None # Return information about fmRI data file return FileInfo( fmri.upload_file, fmri.properties[datastore.PROPERTY_MIMETYPE], fmri.properties[datastore.PROPERTY_FILENAME] )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def experiments_fmri_get(self, experiment_id): """Get fMRI data object that is associated with the given experiment. Parameters experiment_id : string unique experiment identifier Returns ------- FMRIDataHandle Handle for fMRI data object of None if (a) the experiment is unknown or (b) has no fMRI data object associated with it. """
# Get experiment to ensure that it exists experiment = self.experiments_get(experiment_id) if experiment is None: return None # Check if experiment has fMRI data if experiment.fmri_data_id is None: return None # Get functional data object handle from database. func_data = self.funcdata.get_object(experiment.fmri_data_id) # Create fMRI handle from functional data handle return funcdata.FMRIDataHandle(func_data, experiment_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 experiments_fmri_upsert_property(self, experiment_id, properties): """Upsert property of fMRI data object associated with given experiment. Raises ValueError if given property dictionary results in an illegal operation. Parameters experiment_id : string Unique experiment identifier properties : Dictionary() Dictionary of property names and their new values. Returns ------- FMRIDataHandle Handle for updated object of None if object doesn't exist """
# Get experiment fMRI to ensure that it exists. Needed to get fMRI # data object identifier for given experiment identifier fmri = self.experiments_fmri_get(experiment_id) if fmri is None: return None # Update properties for fMRI object using the object identifier return self.funcdata.upsert_object_property(fmri.identifier, properties)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def experiments_list(self, limit=-1, offset=-1): """Retrieve list of all experiments in the data store. Parameters limit : int Limit number of results in returned object listing offset : int Set offset in list (order as defined by object store) Returns ------- ObjectListing Listing of experiment handles """
return self.experiments.list_objects(limit=limit, offset=offset)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def experiments_predictions_attachments_download(self, experiment_id, run_id, resource_id): """Download a data file that has been attached with a successful model run. Parameters experiment_id : string Unique experiment identifier model_id : string Unique identifier of model to run resource_id : string Unique attachment identifier Returns ------- FileInfo Information about attachmed file on disk or None if attachment with given resource identifier exists """
# Get experiment to ensure that it exists if self.experiments_get(experiment_id) is None: return None attachment, mime_type = self.predictions.get_data_file_attachment( run_id, resource_id ) if attachment is None: return None # Return information about the result file return FileInfo(attachment, mime_type, os.path.basename(attachment))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def experiments_predictions_create(self, experiment_id, model_id, argument_defs, name, arguments=None, properties=None): """Create new model run for given experiment. Parameters experiment_id : string Unique experiment identifier model_id : string Unique identifier of model to run name : string User-provided name for the model run argument_defs : list(attribute.AttributeDefinition) Definition of valid arguments for the given model List of attribute instances properties : Dictionary, optional Set of model run properties. Returns ------- ModelRunHandle Handle for created model run or None if experiment is unknown """
# Get experiment to ensure that it exists if self.experiments_get(experiment_id) is None: return None # Return created model run return self.predictions.create_object( name, experiment_id, model_id, argument_defs, arguments=arguments, properties=properties )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def experiments_predictions_delete(self, experiment_id, run_id, erase=False): """Delete given prediction for experiment. Raises ValueError if an attempt is made to delete a read-only resource. Parameters experiment_id : string Unique experiment identifier run_id : string Unique model run identifier erase : Boolean, optional If true, the model run will be deleted from the database. Used in case the sco backend could not start a model run after the record had already been created in the database. Returns ------- ModelRunHandle Handle for deleted model run or None if unknown """
# Get model run to ensure that it exists model_run = self.experiments_predictions_get(experiment_id, run_id) if model_run is None: return None # Return resutl of deleting model run. Could also raise exception in # case of invalid database state (i.e., prediction does not exist) return self.predictions.delete_object(model_run.identifier, erase=erase)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def experiments_predictions_download(self, experiment_id, run_id): """Donwload the results of a prediction for a given experiment. Parameters experiment_id : string Unique experiment identifier run_id : string Unique model run identifier Returns ------- FileInfo Information about prediction result file on disk or None if prediction is unknown or has no result """
# Get model run to ensure that it exists model_run = self.experiments_predictions_get(experiment_id, run_id) if model_run is None: return None # Make sure the run has completed successfully if not model_run.state.is_success: return None # Get functional data object for result. Return None if this is None. # Alternatively throw an exception to signal invalid database state. funcdata = self.funcdata.get_object(model_run.state.model_output) if funcdata is None: return None # Return information about the result file return FileInfo( funcdata.upload_file, funcdata.properties[datastore.PROPERTY_MIMETYPE], funcdata.properties[datastore.PROPERTY_FILENAME] )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def experiments_predictions_get(self, experiment_id, run_id): """Get prediction object with given identifier for given experiment. Parameters experiment_id : string Unique experiment identifier run_id : string Unique model run identifier Returns ------- ModelRunHandle Handle for the model run or None if experiment or prediction is unknown """
# Get experiment to ensure that it exists if self.experiments_get(experiment_id) is None: return None # Get predition handle to ensure that it exists model_run = self.predictions.get_object(run_id) if model_run is None: return None # Perform additional check that prediction is for given experiment if experiment_id != model_run.experiment_id: return None # Return model run object return model_run
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def experiments_predictions_image_set_create(self, experiment_id, run_id, filename): """Create a prediction image set from a given tar archive that was produced as the result of a successful model run. Returns None if the specified model run does not exist or did not finish successfully. Raises a ValueError if the given file is invalid or model run. Parameters experiment_id : string Unique experiment identifier run_id : string Unique model run identifier filename : string Path to uploaded image set archive file Returns ------- PredictionImageSetHandle Handle for new prediction image set collection """
# Ensure that the model run exists and is in state SUCCESS model_run = self.experiments_predictions_get(experiment_id, run_id) if model_run is None: return None if not model_run.state.is_success: raise ValueError('invalid run state: ' + str(model_run.state)) # Check if the file is a valid tar archive (based on suffix). suffix = get_filename_suffix(filename, ARCHIVE_SUFFIXES) if suffix is None: # Not a valid file suffix raise ValueError('invalid file suffix: ' + os.path.basename(os.path.normpath(filename))) # Unpack the file to a temporary folder . temp_dir = tempfile.mkdtemp() try: tf = tarfile.open(name=filename, mode='r') tf.extractall(path=temp_dir) except (tarfile.ReadError, IOError) as err: # Clean up in case there is an error during extraction shutil.rmtree(temp_dir) raise ValueError(str(err)) # The list of prediction image sets image_sets = [] # Parse the CSV file. For each image file use: # img_obj = self.images.create_object(img_filename) # to create an image file object in the database. # Use file name as default object name name = os.path.basename(os.path.normpath(filename))[:-len(suffix)] # Create prediction image set img_set = self.prediction_images.create_object(name, image_sets) # Delete the temporary folder shutil.rmtree(temp_dir) return img_set
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def experiments_predictions_list(self, experiment_id, limit=-1, offset=-1): """List of all predictions for given experiment. Parameters experiment_id : string Unique experiment identifier limit : int Limit number of results in returned object listing offset : int Set offset in list (order as defined by object store) Returns ------- ObjectListing Listing of model run handles """
# Get experiment to ensure that it exists if self.experiments_get(experiment_id) is None: return None # Return list of predictions return self.predictions.list_objects( query={'experiment' : experiment_id}, limit=limit, offset=offset )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def experiments_predictions_update_state_active(self, experiment_id, run_id): """Update state of given prediction to active. Parameters experiment_id : string Unique experiment identifier run_id : string Unique model run identifier Returns ------- ModelRunHandle Handle for updated model run or None is prediction is undefined """
# Get prediction to ensure that it exists model_run = self.experiments_predictions_get(experiment_id, run_id) if model_run is None: return None # Update predition state return self.predictions.update_state( run_id, modelrun.ModelRunActive() )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def experiments_predictions_update_state_error(self, experiment_id, run_id, errors): """Update state of given prediction to failed. Set error messages that where generated by the failed run execution. Parameters experiment_id : string Unique experiment identifier run_id : string Unique model run identifier errors : List(string) List of error messages Returns ------- ModelRunHandle Handle for updated model run or None is prediction is undefined """
# Get prediction to ensure that it exists model_run = self.experiments_predictions_get(experiment_id, run_id) if model_run is None: return None # Update predition state return self.predictions.update_state( run_id, modelrun.ModelRunFailed(errors) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def experiments_predictions_update_state_success(self, experiment_id, run_id, result_file): """Update state of given prediction to success. Create a function data resource for the given result file and associate it with the model run. Parameters experiment_id : string Unique experiment identifier run_id : string Unique model run identifier result_file : string Path to model run result file Returns ------- ModelRunHandle Handle for updated model run or None is prediction is undefined """
# Get prediction to ensure that it exists model_run = self.experiments_predictions_get(experiment_id, run_id) if model_run is None: return None # Create new resource for model run result funcdata = self.funcdata.create_object(result_file) # Update predition state return self.predictions.update_state( run_id, modelrun.ModelRunSuccess(funcdata.identifier) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def experiments_predictions_upsert_property(self, experiment_id, run_id, properties): """Upsert property of a prodiction for an experiment. Raises ValueError if given property dictionary results in an illegal operation. Parameters experiment_id : string Unique experiment identifier run_id : string Unique model run identifier properties : Dictionary() Dictionary of property names and their new values. Returns ------- ModelRunHandle Handle for updated object of None if object doesn't exist """
# Get predition to ensure that it exists. Ensures that the combination # of experiment and prediction identifier is valid. if self.experiments_predictions_get(experiment_id, run_id) is None: return None # Return result of upsert for identifier model run return self.predictions.upsert_object_property(run_id, properties)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def images_create(self, filename): """Create and image file or image group object from the given file. The type of the created database object is determined by the suffix of the given file. An ValueError exception is thrown if the file has an unknown suffix. Raises ValueError if invalid file is given. Parameters filename : File-type object File on local disk. Expected to be either an image file or an archive containing image. Returns ------- DataObjectHandle Handle for create dtabase object. Either an ImageHandle or an ImageGroupHandle """
# Check if file is a single image suffix = get_filename_suffix(filename, image.VALID_IMGFILE_SUFFIXES) if not suffix is None: # Create image object from given file return self.images.create_object(filename) # The file has not been recognized as a valid image. Check if the file # is a valid tar archive (based on suffix). suffix = get_filename_suffix(filename, ARCHIVE_SUFFIXES) if not suffix is None: # Unpack the file to a temporary folder . temp_dir = tempfile.mkdtemp() try: tf = tarfile.open(name=filename, mode='r') tf.extractall(path=temp_dir) except (tarfile.ReadError, IOError) as err: # Clean up in case there is an error during extraction shutil.rmtree(temp_dir) raise ValueError(str(err)) # Get names of all files with valid image suffixes and create an # object for each image object group = [] for img_file in image.get_image_files(temp_dir, []): img_obj = self.images.create_object(img_file) folder = img_file[len(temp_dir):-len(img_obj.name)] group.append(image.GroupImage( img_obj.identifier, folder, img_obj.name, img_obj.image_file )) # Create image group name = os.path.basename(os.path.normpath(filename))[:-len(suffix)] img_grp = self.image_groups.create_object(name, group, filename) # Delete the temporary folder shutil.rmtree(temp_dir) return img_grp else: # Not a valid file suffix raise ValueError('invalid file suffix: ' + os.path.basename(os.path.normpath(filename)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def image_files_download(self, image_id): """Get data file for image with given identifier. Parameters image_id : string Unique image identifier Returns ------- FileInfo Information about image file on disk or None if identifier is unknown """
# Retrieve image to ensure that it exist img = self.image_files_get(image_id) if img is None: # Return None if image is unknown return None else: # Reference and information for original uploaded file return FileInfo( img.image_file, img.properties[datastore.PROPERTY_MIMETYPE], img.properties[datastore.PROPERTY_FILENAME] )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def image_files_list(self, limit=-1, offset=-1): """Retrieve list of all images in the data store. Parameters limit : int Limit number of results in returned object listing offset : int Set offset in list (order as defined by object store) Returns ------- ObjectListing Listing of image handles """
return self.images.list_objects(limit=limit, offset=offset)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def image_groups_download(self, image_group_id): """Get data file for image group with given identifier. Parameters image_group_id : string Unique image group identifier Returns ------- FileInfo Information about image group archive file on disk or None if identifier is unknown """
# Retrieve image group to ensure that it exist img_grp = self.image_groups_get(image_group_id) if img_grp is None: # Return None if image group is unknown return None else: # Reference and information for file image group was created from return FileInfo( img_grp.data_file, img_grp.properties[datastore.PROPERTY_MIMETYPE], img_grp.properties[datastore.PROPERTY_FILENAME] )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def image_group_images_list(self, image_group_id, limit=-1, offset=-1): """List images in the given image group. Parameters image_group_id : string Unique image group object identifier limit : int Limit number of results in returned object listing offset : int Set offset in list (order as defined by object store) Returns ------- ObjectListing Listing of group images """
return self.image_groups.list_images( image_group_id, limit=limit, offset=offset )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def image_groups_list(self, limit=-1, offset=-1): """Retrieve list of all image groups in the data store. Parameters limit : int Limit number of results in returned object listing offset : int Set offset in list (order as defined by object store) Returns ------- ObjectListing Listing of image group handles """
return self.image_groups.list_objects(limit=limit, offset=offset)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def subjects_create(self, filename): """Create subject from given data files. Expects the file to be a Freesurfer archive. Raises ValueError if given file is not a valid subject file. Parameters filename : File-type object Freesurfer archive file Returns ------- SubjectHandle Handle for created subject in database """
# Ensure that the file name has a valid archive suffix if get_filename_suffix(filename, ARCHIVE_SUFFIXES) is None: raise ValueError('invalid file suffix: ' + os.path.basename(os.path.normpath(filename))) # Create subject from archive. Raises exception if file is not a valid # subject archive return self.subjects.upload_file(filename)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def subjects_download(self, subject_id): """Get data file for subject with given identifier. Parameters subject_id : string Unique subject identifier Returns ------- FileInfo Information about subject's data file on disk or None if identifier is unknown """
# Retrieve subject to ensure that it exist subject = self.subjects_get(subject_id) if subject is None: # Return None if subject is unknown return None else: # Reference and information for original uploaded file return FileInfo( subject.data_file, subject.properties[datastore.PROPERTY_MIMETYPE], subject.properties[datastore.PROPERTY_FILENAME] )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def subjects_list(self, limit=-1, offset=-1): """Retrieve list of all subjects in the data store. Parameters limit : int Limit number of results in returned object listing offset : int Set offset in list (order as defined by object store) Returns ------- ObjectListing Listing of subject handles """
return self.subjects.list_objects(limit=limit, offset=offset)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def leland94(V, s, r, a, t, C=None, d=None, PosEq=False): """Leland94 Capital Structure model, Corporate Bond valuation model Parameters: V : float Asset Value of the unlevered firm s : float Volatility s of the asset value V of the unlevered firm r : float Risk free rate a : float Bankruptcy cost t : float Corporate tax rate C : float (option, default C=None) The Coupon in $ per $100. - If C>0 then exogenous bancruptcy case, i.e. a failure to pay credit event is triggered when the firm cannot pay the coupon C - If C=None then an endogenous bankcruptcy case, i.e. the management can set endogenously an 'optimal' coupon: min VB, max W=E+D, E>=0 (see pp.1222). The internally computed 'optimal' coupon is retured as output argument. d : float (optional, default d=None) Required dividend by investors, or resp the net cash payout by the firm. - if d=None then 100% retained profits - if d>0 then d is the fixed dividend rate proportional to the firm's asset value. The intermediate result 'X' dependends on 'd'. PosEq : bool (optional, default PosEq=False) If True, then enforce a positive net worth, i.e. obligors demand a "protected bond covenant with positive net worth requirement" (pp.1233) [dt. Positive Eigenkapitalbasis] Returns: -------- D : float Value of debt (p.1219) [dt. Wert des Fremdkapital] E : float Value of equity Wert (p.1221) [dt. Eigenkapitalwert] W : float Value of levered company, or Total value of the firm (p.1221) [dt. Firmenwert] W = V + T - B W = D + E T : float Value of tax benefit (p.1220) [dt. Steuervorteil] B : float Value of bankruptcy costs (p.1220) [dt. Insolvenzkosten] VB : float Level of bankruptcy, i.e. the asset value V at which bankruptcy is declared [dt. Restwert bei Insolvenz] - if PosEq=False then formula in pp.1222 - if PosEq=True then the covenant "VB - D = 0" is applied to protect creditors (pp.1233) PV : float PV of $1 if bankruptcy (p.1219) [dt. Kapitalwert 1 GE bei Insolvenz] Returns (shiny financial metrics): lr : float Leverage Ratio [dt. Kredithebel] i.e. value of debt divided by value of levered firm value D / W yld : float Yield on Debt [dt. Fremdkapitalrendite] i.e. coupon in $ divided by value of debt C / D sprd : float Yield Spread in bp [dt. Kreditspread in bp] i.e. yield on debt minus riskfree rate converted to bps (C/D - r) * 10000 Returns (intermediate results): X : float Net Cash Payout X will differ depending on the dividend policy. - If d=None, then 100% retained profits (p.1218) [dt. Thesaurierend] - If d>0, then fixed dividend per firm value (p.1241) [dt. Prozentuale Dividendenausschüttung] (intermediate result) C : float The Coupon in $ per $100. - If input argument is C>0 then the input argument C is returned as is (exogenous brankruptcy case). - If input argument C=None, then the internally computed 'optimal' coupon the the endogenous brankruptcy case is returned (pp.1222) (intermediate result) A : float Annuity value (Wert der Annuitaet), "A=C/r", The coupon (in $) divded by the risk-free rate. (intermediate result) Examples: --------- PosEq: No (False), Pos Net Worth covenant (True) Coupon: Endo (C=None), Exo (C>0) Source: ------- Leland, Hayne E. 1994. "Corporate Debt Value, Bond Covenants, and Optimal Capital Structure." The Journal of Finance 49 (4): 1213–52. https://doi.org/10.1111/j.1540-6261.1994.tb02452.x. """
# subfunction for def netcashpayout_by_dividend(r, d, s): """net cash payout proportional to the firm's asset value for a given required dividend rate (p.1241) """ import math s2 = s * s tmp = r - d - 0.5 * s2 return (tmp + math.sqrt(tmp * tmp + 2.0 * s2 * r)) / s2 def optimal_coupon(V, r, a, t, X): """Coupon for the endogenous bankcruptcy case (pp.1222)""" m = ((1.0 - t) * X / (r * (1.0 + X)))**X / (1.0 + X) h = (1.0 + X + a * (1 - t) * X / t) * m return V * ((1.0 + X) * h)**(-1.0 / X) def positivenetworth_target(VB, V, a, A, X): """protected bond covenant with positive net worth requirement""" return VB - A - ((1.0 - a) * VB - A) * (VB / V)**X # (1a) Net Cash Payout 'X' if d is None: # Net cash Payout if 100% retained profits (p.1218) X = (2.0 * r) / (s * s) else: # net cash payout proportional to the firm's asset value # for a given required dividend rate (p.1241) X = netcashpayout_by_dividend(r, d, s) # (1b) Optimal coupon of the endogenous bankruptcy # case (p.1222ff.) if C is None: C = optimal_coupon(V, r, a, t, X) # (1c) Wert der Annuitaet A = C / r # (2a) Level of bankruptcy VB (pp.1222) VB = (1.0 - t) * C / (r + 0.5 * s * s) # (2b) protected bond covenant with positive net worth # requirement (pp.1233) if PosEq: from scipy.optimize import fsolve VB = fsolve(func=positivenetworth_target, x0=VB, args=(V, a, A, X)) VB = float(VB) # (3a) PV of $1 if bankruptcy (p.1219) PV = (VB / V)**X # (3b) Value of debt (p.1219) D = A + ((1.0 - a) * VB - A) * PV # (3c) Value of bankruptcy costs (p.1220) B = a * VB * PV # (3d) Value of tax benefit (p.1220) T = t * A * (1.0 - PV) # (3e) Total value of the firm, or Value of levered company (p.1221) W = V + T - B # (3f) Value of equity (p.1221) E = W - D # (4a) Leverage Ratio lr = D / W # (4b) Yield on Debt yld = C / D # (4c) Yield Spread in bp sprd = (yld - r) * 10000.0 # return results return D, E, W, T, B, VB, PV, lr, yld, sprd, X, C, A
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def checkout_dirs(self): """Return directories inside the base directory."""
directories = [os.path.join(self.base_directory, d) for d in os.listdir(self.base_directory)] return [d for d in directories if os.path.isdir(d)]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def missing_tags(self, existing_sdists=None): """Return difference between existing sdists and available tags."""
if existing_sdists is None: existing_sdists = [] logger.debug("Existing sdists: %s", existing_sdists) if self._missing_tags is None: missing = [] existing_sdists = sorted_versions(set(existing_sdists)) available = set(self.wrapper.vcs.available_tags()) available_tags = sorted_versions(available) available_tags.reverse() for tag in available_tags: if tag.is_prerelease: logger.warn("Pre-release marker in tag: %s, ignoring", tag) continue if tag in existing_sdists: logger.debug( "Tag %s is already available, not looking further", tag) break else: missing.append(tag) logger.debug("Tag %s is missing", tag) missing.reverse() # Convert back to proper strings: mapping = {} for tag in available: mapping[parse_version(tag)] = tag self._missing_tags = [mapping[tag] for tag in missing] logger.debug("Missing sdists: %s", self._missing_tags) return self._missing_tags
<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_sdist(self, tag): """Create an sdist and return the full file path of the .tar.gz."""
logger.info("Making tempdir for %s with tag %s...", self.package, tag) self.wrapper.vcs.checkout_from_tag(tag) # checkout_from_tag() chdirs to a temp directory that we need to clean up # later. self.temp_tagdir = os.path.realpath(os.getcwd()) logger.debug("Tag checkout placed in %s", self.temp_tagdir) python = sys.executable logger.debug(command("%s setup.py sdist" % python)) tarball = find_tarball(self.temp_tagdir, self.package, tag) return tarball
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cleanup(self): """Clean up temporary tag checkout dir."""
shutil.rmtree(self.temp_tagdir) # checkout_from_tag might operate on a subdirectory (mostly # 'gitclone'), so cleanup the parent dir as well parentdir = os.path.dirname(self.temp_tagdir) # ensure we don't remove anything important if os.path.basename(parentdir).startswith(self.package): os.rmdir(parentdir) os.chdir(self.start_directory)
<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_client(config_file=None, apikey=None, username=None, userpass=None, service_url=None, verify_ssl_certs=None, select_first=None): """Configure the API service and creates a new instance of client. :param str config_file: absolute path to configuration file :param str apikey: apikey from thetvdb :param str username: username used on thetvdb :param str userpass: password used on thetvdb :param str service_url: the url for thetvdb api service :param str verify_ssl_certs: flag for validating ssl certs for service url (https) :param str select_first: flag for selecting first series from search results :returns: tvdbapi client :rtype: tvdbapi_client.api.TVDBClient """
from oslo_config import cfg from tvdbapi_client import api if config_file is not None: cfg.CONF([], default_config_files=[config_file]) else: if apikey is not None: cfg.CONF.set_override('apikey', apikey, 'tvdb') if username is not None: cfg.CONF.set_override('username', username, 'tvdb') if userpass is not None: cfg.CONF.set_override('userpass', userpass, 'tvdb') if service_url is not None: cfg.CONF.set_override('service_url', service_url, 'tvdb') if verify_ssl_certs is not None: cfg.CONF.set_override('verify_ssl_certs', verify_ssl_certs, 'tvdb') if select_first is not None: cfg.CONF.set_override('select_first', select_first, 'tvdb') return api.TVDBClient()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def close(self) -> None: """Closes connection to the LifeSOS ethernet interface."""
self.cancel_pending_tasks() _LOGGER.debug("Disconnected") if self._transport: self._transport.close() self._is_connected = False
<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_execute(self, command: Command, password: str = '', timeout: int = EXECUTE_TIMEOUT_SECS) -> Response: """ Execute a command and return response. command: the command instance to be executed password: if specified, will be used to execute this command (overriding any global password that may have been assigned to the property) timeout: maximum number of seconds to wait for a response """
if not self._is_connected: raise ConnectionError("Client is not connected to the server") state = { 'command': command, 'event': asyncio.Event(loop=self._loop) } # type: Dict[str, Any] self._executing[command.name] = state try: self._send(command, password) await asyncio.wait_for(state['event'].wait(), timeout) return state['response'] finally: self._executing[command.name] = 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 longest_service_name(self): """Length of the longest service name."""
return max([len(service_handle.service.name) for service_handle in self.service_handles] + [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 list_all_threads_view(request): ''' View of all threads. ''' threads = Thread.objects.all() create_form = ThreadForm( request.POST if "submit_thread_form" in request.POST else None, profile=UserProfile.objects.get(user=request.user), ) if create_form.is_valid(): thread = create_form.save() return HttpResponseRedirect(reverse("threads:view_thread", kwargs={"pk": thread.pk})) elif request.method == "POST": messages.add_message(request, messages.ERROR, MESSAGES['THREAD_ERROR']) return render_to_response('list_threads.html', { 'page_name': "All Threads", "create_form": create_form, 'threads': threads, }, context_instance=RequestContext(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 list_user_threads_view(request, targetUsername): ''' View of threads a user has created. ''' targetUser = get_object_or_404(User, username=targetUsername) targetProfile = get_object_or_404(UserProfile, user=targetUser) threads = Thread.objects.filter(owner=targetProfile) page_name = "{0}'s Threads".format(targetUser.get_full_name()) create_form = ThreadForm( request.POST if "submit_thread_form" in request.POST else None, profile=UserProfile.objects.get(user=request.user), prefix="create", ) if create_form.is_valid(): thread = create_form.save() return HttpResponseRedirect(reverse("threads:view_thread", kwargs={"pk": thread.pk})) elif request.method == "POST": messages.add_message(request, messages.ERROR, MESSAGES['THREAD_ERROR']) return render_to_response('list_threads.html', { 'page_name': page_name, 'threads': threads, "create_form": create_form, 'targetUsername': targetUsername, }, context_instance=RequestContext(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 list_user_messages_view(request, targetUsername): ''' View of threads a user has posted in. ''' targetUser = get_object_or_404(User, username=targetUsername) targetProfile = get_object_or_404(UserProfile, user=targetUser) user_messages = Message.objects.filter(owner=targetProfile) thread_pks = list(set([i.thread.pk for i in user_messages])) threads = Thread.objects.filter(pk__in=thread_pks) page_name = "Threads {0} has posted in".format(targetUser.get_full_name()) return render_to_response('list_threads.html', { 'page_name': page_name, 'threads': threads, 'targetUsername': targetUsername, }, context_instance=RequestContext(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_form(self, request, obj=None, **kwargs): """ Use special form during user creation """
defaults = {} if obj is None: defaults['form'] = self.add_form defaults.update(kwargs) return super(SettingsAdmin, self).get_form(request, obj, **defaults)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _css_select(soup, css_selector): """ Returns the content of the element pointed by the CSS selector, or an empty string if not found """
selection = soup.select(css_selector) if len(selection) > 0: if hasattr(selection[0], 'text'): retour = selection[0].text.strip() else: retour = "" else: retour = "" return retour
<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_authenticity_token(self, url=_SIGNIN_URL): """ Returns an authenticity_token, mandatory for signing in """
res = self.client._get(url=url, expected_status_code=200) soup = BeautifulSoup(res.text, _DEFAULT_BEAUTIFULSOUP_PARSER) selection = soup.select(_AUTHENTICITY_TOKEN_SELECTOR) try: authenticity_token = selection[0].get("content") except: raise ValueError( "authenticity_token not found in {} with {}\n{}".format( _SIGNIN_URL, _AUTHENTICITY_TOKEN_SELECTOR, res.text)) return authenticity_token
<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_surveys(self, url=_SURVEYS_URL): """ Function to get the surveys for the account """
res = self.client._get(url=url, expected_status_code=200) soup = BeautifulSoup(res.text, _DEFAULT_BEAUTIFULSOUP_PARSER) surveys_soup = soup.select(_SURVEYS_SELECTOR) survey_list = [] for survey_soup in surveys_soup: survey_name = _css_select(survey_soup, _SURVEY_NAME_SELECTOR) try: url = survey_soup.select(_SURVEY_URL_SELECTOR)[0]["href"] except: raise ValueError("Cannot get URL for the survey \ with css selector {}".format(_SURVEY_URL_SELECTOR)) try: id = int(url.split("survey_id=")[1].split("&")[0]) except: raise ValueError("Cannot extract id from URL {}".format( url)) survey_location = _css_select(survey_soup, _SURVEY_LOCATION_SELECTOR) try: survey_epoch = int(survey_soup.select( _SURVEY_DATE_SELECTOR)[0]["epoch"]) survey_date_obj = datetime.fromtimestamp(survey_epoch) survey_date = _datetime_object_to_rfc_date_str(survey_date_obj) except: raise ValueError("Cannot get date for the survey \ with css selector {}".format(_SURVEY_DATE_SELECTOR)) survey_img_nb_and_size = survey_soup.select( _SURVEY_IMG_NB_AND_SIZE_SELECTOR) try: survey_img_nb = survey_img_nb_and_size[0].text survey_img_nb = int(survey_img_nb.split(" ")[0]) except: raise ValueError("Cannot get or convert image number, \ survey_img_nb_and_size = {}".format(survey_img_nb_and_size)) try: survey_size = survey_img_nb_and_size[1].text except: raise ValueError("Cannot get survey size, \ survey_img_nb_and_size = {}".format(survey_img_nb_and_size)) sensor = _css_select(survey_soup, _SURVEY_SENSOR_SELECTOR) survey = Survey( id=id, name=survey_name, url=url, date=survey_date, location=survey_location, image_nb=survey_img_nb, size=survey_size, sensor=sensor) survey_list.append(survey) return survey_list
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_client(name, description, base_url=None, middlewares=None, reset=False): """ Build a complete spore client and store it :param name: name of the client :param description: the REST API description as a file or URL :param base_url: the base URL of the REST API :param middlewares: middlewares to enable :type middlewares: ordered list of 2-elements tuples -> (middleware_class, { :param reset: regenerate or not the client Example : import britney_utils from britney.middleware.format import Json from britney.middleware.auth import Basic is_json = lambda environ: environ['spore.format'] == 'json' client = britney_utils.get_client('MyRestApi', 'http://my-rest-api.org/description.json', base_url='http://rest-api.org/v2/', middlewares=( (Json, {'predicate': is_json}), (Basic, {'username': 'toto', 'password': 'lala'}) )) """
if name in __clients and not reset: return __clients[name] middlewares = middlewares if middlewares is not None else [] try: client = britney.spyre(description, base_url=base_url) except (SporeClientBuildError, SporeMethodBuildError) as build_errors: logging.getLogger('britney').error(str(build_errors)) else: for middleware in middlewares: kwargs = {} if len(middleware) == 2: kwargs = middleware[1] predicate = kwargs.pop('predicate', None) if predicate: client.enable_if(predicate, middleware[0], **kwargs) else: client.enable(middleware[0], **kwargs) __clients[name] = client return client
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def isiterable(element, exclude=None): """Check whatever or not if input element is an iterable. :param element: element to check among iterable types. :param type/tuple exclude: not allowed types in the test. :Example: True False False """
# check for allowed type allowed = exclude is None or not isinstance(element, exclude) result = allowed and isinstance(element, Iterable) 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 ensureiterable(value, iterable=list, exclude=None): """Convert a value into an iterable if it is not. :param object value: object to convert :param type iterable: iterable type to apply (default: list) :param type/tuple exclude: types to not convert :Example: [] () ['test'] ['t', 'e', 's', 't'] """
result = value if not isiterable(value, exclude=exclude): result = [value] result = iterable(result) else: result = iterable(value) 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 first(iterable, default=None): """Try to get input iterable first item or default if iterable is empty. :param Iterable iterable: iterable to iterate on. Must provide the method __iter__. :param default: default value to get if input iterable is empty. :raises TypeError: if iterable is not an iterable value. :Example: 't' 'test' None """
result = default # start to get the iterable iterator (raises TypeError if iter) iterator = iter(iterable) # get first element try: result = next(iterator) except StopIteration: # if no element exist, result equals default pass 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 last(iterable, default=None): """Try to get the last iterable item by successive iteration on it. :param Iterable iterable: iterable to iterate on. Must provide the method __iter__. :param default: default value to get if input iterable is empty. :raises TypeError: if iterable is not an iterable value. :Example: 's' 'test' None"""
result = default iterator = iter(iterable) while True: try: result = next(iterator) except StopIteration: break 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 itemat(iterable, index): """Try to get the item at index position in iterable after iterate on iterable items. :param iterable: object which provides the method __getitem__ or __iter__. :param int index: item position to get. """
result = None handleindex = True if isinstance(iterable, dict): handleindex = False else: try: result = iterable[index] except TypeError: handleindex = False if not handleindex: iterator = iter(iterable) if index < 0: # ensure index is positive index += len(iterable) while index >= 0: try: value = next(iterator) except StopIteration: raise IndexError( "{0} index {1} out of range".format( iterable.__class__, index ) ) else: if index == 0: result = value break index -= 1 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 sliceit(iterable, lower=0, upper=None): """Apply a slice on input iterable. :param iterable: object which provides the method __getitem__ or __iter__. :param int lower: lower bound from where start to get items. :param int upper: upper bound from where finish to get items. :return: sliced object of the same type of iterable if not dict, or specific object. otherwise, simple list of sliced items. :rtype: Iterable """
if upper is None: upper = len(iterable) try: result = iterable[lower: upper] except TypeError: # if iterable does not implement the slice method result = [] if lower < 0: # ensure lower is positive lower += len(iterable) if upper < 0: # ensure upper is positive upper += len(iterable) if upper > lower: iterator = iter(iterable) for index in range(upper): try: value = next(iterator) except StopIteration: break else: if index >= lower: result.append(value) iterablecls = iterable.__class__ if not(isinstance(result, iterablecls) or issubclass(iterablecls, dict)): try: result = iterablecls(result) except TypeError: pass 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 hashiter(iterable): """Try to hash input iterable in doing the sum of its content if not hashable. Hash method on not iterable depends on type: - dict: sum of (hash(key) + 1) * (hash(value) + 1). - Otherwise: sum of (pos + 1) * (hash(item) + 1)."""
result = 0 try: result = hash(iterable) except TypeError: result = hash(iterable.__class__) isdict = isinstance(iterable, dict) for index, entry in enumerate(list(iterable)): entryhash = hashiter(entry) + 1 if isdict: entryhash *= hashiter(iterable[entry]) + 1 else: entryhash *= index + 1 result += entryhash return result