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)...
<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']): ...
<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']: ...
<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=...
<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'):...
<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'.forma...
<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 ...
<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 ...
<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 l...
<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 ...
<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 t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def 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 ...
<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: fl...
<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 ...
<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( ...
<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" ...
<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(), 'en...
<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 value...
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 isinsta...
<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 facilit...
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 ...
<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: lis...
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 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 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 e...
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) ...
<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 CreateU...
# 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.backwa...
<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 func...
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 dime...
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 dime...
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 ...
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 Coord...
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...
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 fi...
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 ...
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 ...
<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. `a...
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. ...
<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 spaw...
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 = subpr...
<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 ``...
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 unic...
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...
<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: ...
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,...
<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 ...
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...
<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 = Beau...
<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 ------...
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 the...
# 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...
<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 experime...
# 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_obj...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def experiments_fmri_delete(self, experiment_id): """Delete fMRI data object associated with given experiment. Raises ValueError if an attempt is made to delete ...
# 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. ...
<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 exp...
# 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_MIMETYP...
<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 exp...
# 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 f...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def experiments_fmri_upsert_property(self, experiment_id, properties): """Upsert property of fMRI data object associated with given experiment. Raises ValueError...
# 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 ...
<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 returne...
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 mode...
# 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 ...
<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 experi...
# 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, 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 experiments_predictions_delete(self, experiment_id, run_id, erase=False): """Delete given prediction for experiment. Raises ValueError if an attempt is made ...
# 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...
<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 : str...
# 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 func...
<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 : str...
# 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 addit...
<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 ...
# 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)) ...
<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 Un...
# 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 Un...
# 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...
# 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(erro...
<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 dat...
# 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 s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def experiments_predictions_upsert_property(self, experiment_id, run_id, properties): """Upsert property of a prodiction for an experiment. Raises ValueError if ...
# 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.p...
<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 t...
# 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. Che...
<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 ------- ...
# 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.i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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 obj...
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 id...
# 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 ...
<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 ...
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 retur...
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...
# 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 ...
<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 ---...
# 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( ...
<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 obje...
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 o...
# 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 ...
<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_ta...
<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.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 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).startswit...
<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 ser...
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_ov...
<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. c...
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: sel...
<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(): thr...
<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 Threa...
<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 = l...
<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( ...
<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...
<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 :...
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...
<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 ty...
# 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 iter...
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. Mus...
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 prov...
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 met...
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 i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sliceit(iterable, lower=0, upper=None): """Apply a slice on input iterable. :param iterable: object which provides the method __getitem__ or __iter__. :param...
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 upp...
<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 o...
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 ...