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 _get(self, rec_id=None, upstream=None): """ Fetches a record by the record's ID or upstream_identifier. Raises: `pulsarpy.models.RecordNotFound`: A record co...
if rec_id: self.record_url = self.__class__.get_record_url(rec_id) self.debug_logger.debug("GET {} record with ID {}: {}".format(self.__class__.__name__, rec_id, self.record_url)) response = requests.get(url=self.record_url, headers=HEADERS, verify=False) if not ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def replace_name_with_id(cls, name): """ Used to replace a foreign key reference using a name with an ID. Works by searching the record in Pulsar and expects to ...
try: int(name) return name #Already a presumed ID. except ValueError: pass #Not an int, so maybe a combination of MODEL_ABBR and Primary Key, i.e. B-8. if name.split("-")[0] in Meta._MODEL_ABBREVS: return int(name.split("-", 1)[1]) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete(self): """Deletes the record. """
res = requests.delete(url=self.record_url, headers=HEADERS, verify=False) #self.write_response_html_to_file(res,"bob_delete.html") if res.status_code == 204: #No content. Can't render json: return {} return res.json()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_by(cls, payload, require=False): """ Searches the model in question by AND joining the query parameters. Implements a Railsy way of looking for a record...
if not isinstance(payload, dict): raise ValueError("The 'payload' parameter must be provided a dictionary object.") url = os.path.join(cls.URL, "find_by") payload = {"find_by": payload} cls.debug_logger.debug("Searching Pulsar {} for {}".format(cls.__name__, json.dumps(paylo...
<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_by_or(cls, payload): """ Searches the model in question by OR joining the query parameters. Implements a Railsy way of looking for a record using a meth...
if not isinstance(payload, dict): raise ValueError("The 'payload' parameter must be provided a dictionary object.") url = os.path.join(cls.URL, "find_by_or") payload = {"find_by_or": payload} cls.debug_logger.debug("Searching Pulsar {} for {}".format(cls.__name__, json.dumps...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def index(cls): """Fetches all records. Returns: `dict`. The JSON formatted response. Raises: `requests.exceptions.HTTPError`: The status code is not ok. """
res = requests.get(cls.URL, headers=HEADERS, verify=False) res.raise_for_status() return res.json()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def patch(self, payload, append_to_arrays=True): """ Patches current record and udpates the current instance's 'attrs' attribute to reflect the new changes. Args...
if not isinstance(payload, dict): raise ValueError("The 'payload' parameter must be provided a dictionary object.") payload = self.__class__.set_id_in_fkeys(payload) if append_to_arrays: for key in payload: val = payload[key] if type(val) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def post(cls, payload): """Posts the data to the specified record. Args: payload: `dict`. This will be JSON-formatted prior to sending the request. Returns: `dic...
if not isinstance(payload, dict): raise ValueError("The 'payload' parameter must be provided a dictionary object.") payload = cls.set_id_in_fkeys(payload) payload = cls.check_boolean_fields(payload) payload = cls.add_model_name_to_payload(payload) # Run any pre-post ...
<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_error(cls, msg): """ Logs the provided error message to both the error logger and the debug logger logging instances. Args: msg: `str`. The error message...
cls.error_logger.error(msg) cls.debug_logger.debug(msg)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def library_sequencing_results(self): """ Generates a dict. where each key is a Library ID on the SequencingRequest and each value is the associated SequencingRe...
sres_ids = self.sequencing_result_ids res = {} for i in sres_ids: sres = SequencingResult(i) res[sres.library_id] = sres return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unarchive_user(self, user_id): """Unarchives the user with the specified user ID. Args: user_id: `int`. The ID of the user to unarchive. Returns: `NoneType`:...
url = self.record_url + "/unarchive" res = requests.patch(url=url, json={"user_id": user_id}, headers=HEADERS, verify=False) self.write_response_html_to_file(res,"bob.html") res.raise_for_status()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_api_key(self): """ Removes the user's existing API key, if present, and sets the current instance's 'api_key' attribute to the empty string. Returns: ...
url = self.record_url + "/remove_api_key" res = requests.patch(url=url, headers=HEADERS, verify=False) res.raise_for_status() self.api_key = ""
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _process(self, resource=None, data={}): """Processes the current transaction Sends an HTTP request to the PAYDUNYA API server """
# use object's data if no data is passed _data = data or self._data rsc_url = self.get_rsc_endpoint(resource) if _data: req = requests.post(rsc_url, data=json.dumps(_data), headers=self.headers) else: req = requests.get(rsc...
<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_header(self, header): """Add a custom HTTP header to the client's request headers"""
if type(header) is dict: self._headers.update(header) else: raise ValueError( "Dictionary expected, got '%s' instead" % type(header) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def changelog_cli(ctx): # type: () -> None """ Generate changelog from commit messages. """
if ctx.invoked_subcommand: return from peltak.core import shell from . import logic shell.cprint(logic.changelog())
<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_default_name(self): ''' Return the default generated name to store value on the parser for this option. eg. An option *['-s', '--use-ssl']* will generate the *use_ssl* name Returns: str: the default name of the option ''' long_names = [name for 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_filename(self, base_dir=None, modality=None): """Construct filename based on the attributes. Parameters base_dir : Path path of the root directory. If sp...
filename = 'sub-' + self.subject if self.session is not None: filename += '_ses-' + self.session if self.task is not None: filename += '_task-' + self.task if self.run is not None and self.direction is None: filename += '_run-' + self.run if 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 get(self, filter_lambda=None, map_lambda=None): """Select elements of the TSV, using python filter and map. Parameters filter_lambda : function function to f...
if filter_lambda is None: filter_lambda = lambda x: True if map_lambda is None: map_lambda = lambda x: x return list(map(map_lambda, filter(filter_lambda, self.tsv)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def connect(self, client_id: str = None, client_secret: str = None) -> dict: """Authenticate application and get token bearer. Isogeo API uses oAuth 2.0 protocol ...
# instanciated or direct call if not client_id and not client_secret: client_id = self.client_id client_secret = self.client_secret else: pass # Basic Authentication header in Base64 (https://en.wikipedia.org/wiki/Base64) # see: http://tools....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search( self, token: dict = None, query: str = "", bbox: list = None, poly: str = None, georel: str = None, order_by: str = "_created", order_dir: str = "desc...
# specific resources specific parsing specific_md = checker._check_filter_specific_md(specific_md) # sub resources specific parsing include = checker._check_filter_includes(include) # handling request parameters payload = { "_id": specific_md, "...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resource( self, token: dict = None, id_resource: str = None, subresource=None, include: list = [], prot: str = "https", ) -> dict: """Get complete or partial ...
# if subresource route if isinstance(subresource, str): subresource = "/{}".format(checker._check_subresource(subresource)) else: subresource = "" # _includes specific parsing include = checker._check_filter_includes(include) # handling r...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shares(self, token: dict = None, prot: str = "https") -> dict: """Get information about shares which feed the application. :param str token: API auth token :p...
# passing auth parameter shares_url = "{}://v1.{}.isogeo.com/shares/".format(prot, self.api_url) shares_req = self.get( shares_url, headers=self.header, proxies=self.proxies, verify=self.ssl ) # checking response checker.check_api_response(shares_req) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def share( self, share_id: str, token: dict = None, augment: bool = False, prot: str = "https", ) -> dict: """Get information about a specific share and its appli...
# passing auth parameter share_url = "{}://v1.{}.isogeo.com/shares/{}".format( prot, self.api_url, share_id ) share_req = self.get( share_url, headers=self.header, proxies=self.proxies, verify=self.ssl ) # checking response checker.check_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def licenses( self, token: dict = None, owner_id: str = None, prot: str = "https" ) -> dict: """Get information about licenses owned by a specific workgroup. :par...
# handling request parameters payload = {"gid": owner_id} # search request licenses_url = "{}://v1.{}.isogeo.com/groups/{}/licenses".format( prot, self.api_url, owner_id ) licenses_req = self.get( licenses_url, headers=self.header, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def license(self, license_id: str, token: dict = None, prot: str = "https") -> dict: """Get details about a specific license. :param str token: API auth token :pa...
# handling request parameters payload = {"lid": license_id} # search request license_url = "{}://v1.{}.isogeo.com/licenses/{}".format( prot, self.api_url, license_id ) license_req = self.get( license_url, headers=self.header, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def thesauri(self, token: dict = None, prot: str = "https") -> dict: """Get list of available thesauri. :param str token: API auth token :param str prot: https [D...
# passing auth parameter thez_url = "{}://v1.{}.isogeo.com/thesauri".format(prot, self.api_url) thez_req = self.get( thez_url, headers=self.header, proxies=self.proxies, verify=self.ssl ) # checking response checker.check_api_response(thez_req) # 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 thesaurus( self, token: dict = None, thez_id: str = "1616597fbc4348c8b11ef9d59cf594c8", prot: str = "https", ) -> dict: """Get a thesaurus. :param str token: ...
# handling request parameters payload = {"tid": thez_id} # passing auth parameter thez_url = "{}://v1.{}.isogeo.com/thesauri/{}".format( prot, self.api_url, thez_id ) thez_req = self.get( thez_url, headers=self.header, par...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def keywords( self, token: dict = None, thez_id: str = "1616597fbc4348c8b11ef9d59cf594c8", query: str = "", offset: int = 0, order_by: str = "text", order_dir: st...
# specific resources specific parsing specific_md = checker._check_filter_specific_md(specific_md) # sub resources specific parsing include = checker._check_filter_includes(include, "keyword") # specific tag specific parsing specific_tag = checker._check_filter_specific_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dl_hosted( self, token: dict = None, resource_link: dict = None, encode_clean: bool = 1, proxy_url: str = None, prot: str = "https", ) -> tuple: """Download h...
# check resource link parameter type if not isinstance(resource_link, dict): raise TypeError("Resource link expects a dictionary.") else: pass # check resource link type if not resource_link.get("type") == "hosted": 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 xml19139( self, token: dict = None, id_resource: str = None, proxy_url=None, prot: str = "https", ): """Get resource exported into XML ISO 19139. :param str ...
# check metadata UUID if not checker.check_is_uuid(id_resource): raise ValueError("Metadata ID is not a correct UUID.") else: pass # handling request parameters payload = {"proxyUrl": proxy_url, "id": id_resource} # resource search md_ur...
<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_tags_shares(self, tags: dict = dict()): """Add shares list to the tags attributes in search results. :param dict tags: tags dictionary from a search requ...
# check if shares_id have already been retrieved or not if not hasattr(self, "shares_id"): shares = self.shares() self.shares_id = { "share:{}".format(i.get("_id")): i.get("name") for i in shares } else: pass # update query...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_app_properties(self, token: dict = None, prot: str = "https"): """Get information about the application declared on Isogeo. :param str token: API auth to...
# check if app properties have already been retrieved or not if not hasattr(self, "app_properties"): first_app = self.shares()[0].get("applications")[0] app = { "admin_url": "{}/applications/{}".format( self.mng_url, first_app.get("_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 get_directives(self, token: dict = None, prot: str = "https") -> dict: """Get environment directives which represent INSPIRE limitations. :param str token: AP...
# search request req_url = "{}://v1.{}.isogeo.com/directives".format(prot, self.api_url) req = self.get( req_url, headers=self.header, proxies=self.proxies, verify=self.ssl ) # checking response checker.check_api_response(req) # end of method ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_coordinate_systems( self, token: dict = None, srs_code: str = None, prot: str = "https" ) -> dict: """Get available coordinate systems in Isogeo API. :par...
# if specific format if isinstance(srs_code, str): specific_srs = "/{}".format(srs_code) else: specific_srs = "" # search request req_url = "{}://v1.{}.isogeo.com/coordinate-systems{}".format( prot, self.api_url, specific_srs ) ...
<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_formats( self, token: dict = None, format_code: str = None, prot: str = "https" ) -> dict: """Get formats. :param str token: API auth token :param str for...
# if specific format if isinstance(format_code, str): specific_format = "/{}".format(format_code) else: specific_format = "" # search request req_url = "{}://v1.{}.isogeo.com/formats{}".format( prot, self.api_url, specific_format ) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search_datasets( self, license=None, format=None, query=None, featured=None, owner=None, organization=None, badge=None, reuses=None, page_size=20, x_fields=No...
# handling request parameters payload = {"badge": badge, "size": page_size, "X-Fields": x_fields} # search request # head = {"X-API-KEY": self.api_key} search_url = "{}/datasets".format( self.base_url, # org_id, # page_size ) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_filters_values(self): """Get different filters values as dicts."""
# DATASETS -- # badges self._DST_BADGES = requests.get(self.base_url + "datasets/badges/").json() # licences self._DST_LICENSES = { l.get("id"): l.get("title") for l in requests.get(self.base_url + "datasets/licenses").json() } # frequenci...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def deploy(app_id, version, promote, quiet): # type: (str, str, bool, bool) -> None """ Deploy the app to AppEngine. Args: app_id (str): AppEngine App ID. Overr...
gae_app = GaeApp.for_branch(git.current_branch().name) if gae_app is None and None in (app_id, version): msg = ( "Can't find an AppEngine app setup for branch <35>{}<32> and" "--project and --version were not given." ) log.err(msg, git.current_branch().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 setup_ci(): # type: () -> None """ Setup AppEngine SDK on CircleCI """
gcloud_path = shell.run('which gcloud', capture=True).stdout.strip() sdk_path = normpath(join(gcloud_path, '../../platform/google_appengine')) gcloud_cmd = gcloud_path + ' --quiet' if not exists(sdk_path): log.info("Installing AppEngine SDK") shell.run('sudo {} components install app-e...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mark_experimental(fn): # type: (FunctionType) -> FunctionType """ Mark function as experimental. Args: fn (FunctionType): The command function to decorate. ...
@wraps(fn) def wrapper(*args, **kw): # pylint: disable=missing-docstring from peltak.core import shell if shell.is_tty: warnings.warn("This command is has experimental status. The " "interface is not yet stable and might change " ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mark_deprecated(replaced_by): # type: (Text) -> FunctionType """ Mark command as deprecated. Args: replaced_by (str): The command that deprecated this comma...
def decorator(fn): # pylint: disable=missing-docstring @wraps(fn) def wrapper(*args, **kw): # pylint: disable=missing-docstring from peltak.core import shell if shell.is_tty: warnings.warn("This command is has been deprecated. Please use " ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def in_batches(iterable, batch_size): # type: (Iterable[Any]) -> Generator[List[Any]] """ Split the given iterable into batches. Args: iterable (Iterable[Any]): ...
items = list(iterable) size = len(items) for i in range(0, size, batch_size): yield items[i:min(i + batch_size, size)]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clear(cls, fn): # type: (FunctionType) -> None """ Clear result cache on the given function. If the function has no cached result, this call will do nothing....
if hasattr(fn, cls.CACHE_VAR): delattr(fn, cls.CACHE_VAR)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def finish(): # type: () -> None """ Merge current feature branch into develop. """
pretend = context.get('pretend', False) if not pretend and (git.staged() or git.unstaged()): log.err( "You have uncommitted changes in your repo!\n" "You need to stash them before you merge the hotfix branch" ) sys.exit(1) branch = git.current_branch(refres...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mutagen_call(action, path, func, *args, **kwargs): """Call a Mutagen function with appropriate error handling. `action` is a string describing what the funct...
try: return func(*args, **kwargs) except mutagen.MutagenError as exc: log.debug(u'%s failed: %s', action, six.text_type(exc)) raise UnreadableFileError(path, six.text_type(exc)) except Exception as exc: # Isolate bugs in Mutagen. log.debug(u'%s', traceback.format_exc...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _safe_cast(out_type, val): """Try to covert val to out_type but never raise an exception. If the value can't be converted, then a sensible default value is r...
if val is None: return None if out_type == int: if isinstance(val, int) or isinstance(val, float): # Just a number. return int(val) else: # Process any other type as a string. if isinstance(val, bytes): val = val.decode('u...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def deserialize(self, mutagen_value): """Given a raw value stored on a Mutagen object, decode and return the represented value. """
if self.suffix and isinstance(mutagen_value, six.text_type) \ and mutagen_value.endswith(self.suffix): return mutagen_value[:-len(self.suffix)] else: return mutagen_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 set(self, mutagen_file, value): """Assign the value for the field using this style. """
self.store(mutagen_file, self.serialize(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 serialize(self, value): """Convert the external Python value to a type that is suitable for storing in a Mutagen file object. """
if isinstance(value, float) and self.as_type is six.text_type: value = u'{0:.{1}f}'.format(value, self.float_places) value = self.as_type(value) elif self.as_type is six.text_type: if isinstance(value, bool): # Store bools as 1/0 instead of True/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 get_list(self, mutagen_file): """Get a list of all values for the field using this style. """
return [self.deserialize(item) for item in self.fetch(mutagen_file)]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_list(self, mutagen_file, values): """Set all values for the field using this style. `values` should be an iterable. """
self.store(mutagen_file, [self.serialize(value) for value in 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 deserialize(self, apic_frame): """Convert APIC frame into Image."""
return Image(data=apic_frame.data, desc=apic_frame.desc, type=apic_frame.type)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def serialize(self, image): """Return an APIC frame populated with data from ``image``. """
assert isinstance(image, Image) frame = mutagen.id3.Frames[self.key]() frame.data = image.data frame.mime = image.mime_type frame.desc = image.desc or u'' # For compatibility with OS X/iTunes prefer latin-1 if possible. # See issue #899 try: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def serialize(self, image): """Turn a Image into a base64 encoded FLAC picture block. """
pic = mutagen.flac.Picture() pic.data = image.data pic.type = image.type_index pic.mime = image.mime_type pic.desc = image.desc or u'' # Encoding with base64 returns bytes on both Python 2 and 3. # Mutagen requires the data to be a Unicode string, so we decode ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def store(self, mutagen_file, pictures): """``pictures`` is a list of mutagen.flac.Picture instances. """
mutagen_file.clear_pictures() for pic in pictures: mutagen_file.add_picture(pic)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def serialize(self, image): """Turn a Image into a mutagen.flac.Picture. """
pic = mutagen.flac.Picture() pic.data = image.data pic.type = image.type_index pic.mime = image.mime_type pic.desc = image.desc or u'' return pic
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete(self, mutagen_file): """Remove all images from the file. """
for cover_tag in self.TAG_NAMES.values(): try: del mutagen_file[cover_tag] except KeyError: 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 styles(self, mutagen_file): """Yields the list of storage styles of this field that can handle the MediaFile's format. """
for style in self._styles: if mutagen_file.__class__.__name__ in style.formats: yield style
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _none_value(self): """Get an appropriate "null" value for this field's type. This is used internally when setting the field to None. """
if self.out_type == int: return 0 elif self.out_type == float: return 0.0 elif self.out_type == bool: return False elif self.out_type == six.text_type: return u''
<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_date_tuple(self, mediafile): """Get a 3-item sequence representing the date consisting of a year, month, and day number. Each number is either an intege...
# Get the underlying data and split on hyphens and slashes. datestring = super(DateField, self).__get__(mediafile, None) if isinstance(datestring, six.string_types): datestring = re.sub(r'[Tt ].*$', '', six.text_type(datestring)) items = re.split('[-/]', six.text_type(da...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _set_date_tuple(self, mediafile, year, month=None, day=None): """Set the value of the field given a year, month, and day number. Each number can be an intege...
if year is None: self.__delete__(mediafile) return date = [u'{0:04d}'.format(int(year))] if month: date.append(u'{0:02d}'.format(int(month))) if month and day: date.append(u'{0:02d}'.format(int(day))) date = map(six.text_type, dat...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save(self): """Write the object's tags back to the file. May throw `UnreadableFileError`. """
# Possibly save the tags to ID3v2.3. kwargs = {} if self.id3v23: id3 = self.mgfile if hasattr(id3, 'tags'): # In case this is an MP3 object, not an ID3 object. id3 = id3.tags id3.update_to_v23() kwargs['v2_version']...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _field_sort_name(cls, name): """Get a sort key for a field name that determines the order fields should be written in. Fields names are kept unchanged, unles...
if isinstance(cls.__dict__[name], DateItemField): name = re.sub('year', 'date0', name) name = re.sub('month', 'date1', name) name = re.sub('day', 'date2', name) return 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 sorted_fields(cls): """Get the names of all writable metadata fields, sorted in the order that they should be written. This is a lexicographic order, except ...
for property in sorted(cls.fields(), key=cls._field_sort_name): yield property
<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_field(cls, name, descriptor): """Add a field to store custom tags. :param name: the name of the property the field is accessed through. It must not alrea...
if not isinstance(descriptor, MediaField): raise ValueError( u'{0} must be an instance of MediaField'.format(descriptor)) if name in cls.__dict__: raise ValueError( u'property "{0}" already exists on MediaField'.format(name)) setattr(cls, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(self, dict): """Set all field values from a dictionary. For any key in `dict` that is also a field to store tags the method retrieves the correspondin...
for field in self.sorted_fields(): if field in dict: if dict[field] is None: delattr(self, field) else: setattr(self, field, dict[field])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rebin2x2(a): """ Wrapper around rebin that actually rebins 2 by 2 """
inshape = np.array(a.shape) if not (inshape % 2 == np.zeros(2)).all(): # Modulo check to see if size is even raise RuntimeError, "I want even image shapes !" return rebin(a, inshape/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 labelmask(self, verbose = None): """ Finds and labels the cosmic "islands" and returns a list of dicts containing their positions. This is made on purpose fo...
if verbose == None: verbose = self.verbose if verbose: print "Labeling mask pixels ..." # We morphologicaly dilate the mask to generously connect "sparse" cosmics : #dilstruct = np.ones((5,5)) dilmask = ndimage.morphology.binary_dilation(self.mask, struct...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getdilatedmask(self, size=3): """ Returns a morphologically dilated copy of the current mask. size = 3 or 5 decides how to dilate. """
if size == 3: dilmask = ndimage.morphology.binary_dilation(self.mask, structure=growkernel, iterations=1, mask=None, output=None, border_value=0, origin=0, brute_force=False) elif size == 5: dilmask = ndimage.morphology.binary_dilation(self.mask, structure=dilstruct, iterations=...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getsatstars(self, verbose = None): """ Returns the mask of saturated stars after finding them if not yet done. Intended mainly for external use. """
if verbose == None: verbose = self.verbose if not self.satlevel > 0: raise RuntimeError, "Cannot determine satstars : you gave satlevel <= 0 !" if self.satstars == None: self.findsatstars(verbose = verbose) return self.satstars
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def guessbackgroundlevel(self): """ Estimates the background level. This could be used to fill pixels in large cosmics. """
if self.backgroundlevel == None: self.backgroundlevel = np.median(self.rawarray.ravel()) return self.backgroundlevel
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search_project_root(): """ Search your Django project root. returns: - path:string Django project root path """
while True: current = os.getcwd() if pathlib.Path("Miragefile.py").is_file() or pathlib.Path("Miragefile").is_file(): return current elif os.getcwd() == "/": raise FileNotFoundError else: os.chdir("../")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search_app_root(): """ Search your Django application root returns: - (String) Django application root path """
while True: current = os.getcwd() if pathlib.Path("apps.py").is_file(): return current elif pathlib.Path.cwd() == "/": raise FileNotFoundError else: os.chdir("../")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def in_app() -> bool: """ Judge where current working directory is in Django application or not. returns: - (Bool) cwd is in app dir returns True """
try: MirageEnvironment.set_import_root() import apps if os.path.isfile("apps.py"): return True else: return False except ImportError: return False except: 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 start(name): # type: (str) -> None """ Start working on a new hotfix. This will create a new branch off master called hotfix/<name>. Args: name (str): The n...
hotfix_branch = 'hotfix/' + common.to_branch_name(name) master = conf.get('git.master_branch', 'master') common.assert_on_branch(master) common.git_checkout(hotfix_branch, create=True)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def finish(): # type: () -> None """ Merge current feature into develop. """
pretend = context.get('pretend', False) if not pretend and (git.staged() or git.unstaged()): log.err( "You have uncommitted changes in your repo!\n" "You need to stash them before you merge the hotfix branch" ) sys.exit(1) develop = conf.get('git.devel_bran...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self): """ Run the shell command Returns: ShellCommand: return this ShellCommand instance for chaining """
if not self.block: self.output = [] self.error = [] self.thread = threading.Thread(target=self.run_non_blocking) self.thread.start() else: self.__create_process() self.process.wait() if self._stdout is not 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 send(self, value): """ Send text to stdin. Can only be used on non blocking commands Args: value (str): the text to write on stdin Raises: TypeError: If com...
if not self.block and self._stdin is not None: self.writer.write("{}\n".format(value)) return self else: raise TypeError(NON_BLOCKING_ERROR_MESSAGE)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def poll_output(self): """ Append lines from stdout to self.output. Returns: list: The lines added since last call """
if self.block: return self.output new_list = self.output[self.old_output_size:] self.old_output_size += len(new_list) return new_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 poll_error(self): """ Append lines from stderr to self.errors. Returns: list: The lines added since last call """
if self.block: return self.error new_list = self.error[self.old_error_size:] self.old_error_size += len(new_list) return new_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 kill(self): """ Kill the current non blocking command Raises: TypeError: If command is blocking """
if self.block: raise TypeError(NON_BLOCKING_ERROR_MESSAGE) try: self.process.kill() except ProcessLookupError as exc: self.logger.debug(exc)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wait_for(self, pattern, timeout=None): """ Block until a pattern have been found in stdout and stderr Args: pattern(:class:`~re.Pattern`): The pattern to se...
should_continue = True if self.block: raise TypeError(NON_BLOCKING_ERROR_MESSAGE) def stop(signum, frame): # pylint: disable=W0613 nonlocal should_continue if should_continue: raise TimeoutError() if timeout: signal.sig...
<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_running(self): """ Check if the command is currently running Returns: bool: True if running, else False """
if self.block: return False return self.thread.is_alive() or self.process.poll() is 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 print_live_output(self): ''' Block and print the output of the command Raises: TypeError: If command is blocking ''' if self.block: raise TypeError(NON_BLOCKING_ERROR_MESSAGE) else: while self.thread.is_alive() or self.old_output_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 scatter(slope, zero, x1, x2, x1err=[], x2err=[]): """ Used mainly to measure scatter for the BCES best-fit """
n = len(x1) x2pred = zero + slope * x1 s = sum((x2 - x2pred) ** 2) / (n - 1) if len(x2err) == n: s_obs = sum((x2err / x2) ** 2) / n s0 = s - s_obs print numpy.sqrt(s), numpy.sqrt(s_obs), numpy.sqrt(s0) return numpy.sqrt(s0)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mcmc(x1, x2, x1err=[], x2err=[], po=(1,1,0.5), logify=True, nsteps=5000, nwalkers=100, nburn=500, output='full'): """ Use emcee to find the best-fit linear r...
import emcee if len(x1err) == 0: x1err = numpy.ones(len(x1)) if len(x2err) == 0: x2err = numpy.ones(len(x1)) def lnlike(theta, x, y, xerr, yerr): a, b, s = theta model = a + b*x sigma = numpy.sqrt((b*xerr)**2 + yerr*2 + s**2) lglk = 2 * sum(numpy.log(sigm...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mle(x1, x2, x1err=[], x2err=[], cerr=[], s_int=True, po=(1,0,0.1), verbose=False, logify=True, full_output=False): """ Maximum Likelihood Estimation of best-...
from scipy import optimize n = len(x1) if len(x2) != n: raise ValueError('x1 and x2 must have same length') if len(x1err) == 0: x1err = numpy.ones(n) if len(x2err) == 0: x2err = numpy.ones(n) if logify: x1, x2, x1err, x2err = to_log(x1, x2, x1err, x2err) 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 to_log(x1, x2, x1err, x2err): """ Take linear measurements and uncertainties and transform to log values. """
logx1 = numpy.log10(numpy.array(x1)) logx2 = numpy.log10(numpy.array(x2)) x1err = numpy.log10(numpy.array(x1)+numpy.array(x1err)) - logx1 x2err = numpy.log10(numpy.array(x2)+numpy.array(x2err)) - logx2 return logx1, logx2, x1err, x2err
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wrap_paths(paths): # type: (list[str]) -> str """ Put quotes around all paths and join them with space in-between. """
if isinstance(paths, string_types): raise ValueError( "paths cannot be a string. " "Use array with one element instead." ) return ' '.join('"' + path + '"' for path in 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 lint_cli(ctx, exclude, skip_untracked, commit_only): # type: (click.Context, List[str], bool, bool) -> None """ Run pep8 and pylint on all project files. You...
if ctx.invoked_subcommand: return from peltak.logic import lint lint.lint(exclude, skip_untracked, commit_only)
<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_ip_addresses(): """Gets the ip addresses from ifconfig :return: (dict) of devices and aliases with the IPv4 address """
log = logging.getLogger(mod_logger + '.get_ip_addresses') command = ['/sbin/ifconfig'] try: result = run_command(command) except CommandError: raise ifconfig = result['output'].strip() # Scan the ifconfig output for IPv4 addresses devices = {} parts = ifconfig.split() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_mac_address(device_index=0): """Returns the Mac Address given a device index :param device_index: (int) Device index :return: (str) Mac address or None "...
log = logging.getLogger(mod_logger + '.get_mac_address') command = ['ip', 'addr', 'show', 'eth{d}'.format(d=device_index)] log.info('Attempting to find a mac address at device index: {d}'.format(d=device_index)) try: result = run_command(command) except CommandError: _, ex, trace = ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def chmod(path, mode, recursive=False): """Emulates bash chmod command This method sets the file permissions to the specified mode. :param path: (str) Full path ...
log = logging.getLogger(mod_logger + '.chmod') # Validate args if not isinstance(path, basestring): msg = 'path argument is not a string' log.error(msg) raise CommandError(msg) if not isinstance(mode, basestring): msg = 'mode argument is not a string' log.error(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mkdir_p(path): """Emulates 'mkdir -p' in bash :param path: (str) Path to create :return: None :raises CommandError """
log = logging.getLogger(mod_logger + '.mkdir_p') if not isinstance(path, basestring): msg = 'path argument is not a string' log.error(msg) raise CommandError(msg) log.info('Attempting to create directory: %s', path) try: os.makedirs(path) except OSError as e: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def source(script): """Emulates 'source' command in bash :param script: (str) Full path to the script to source :return: Updated environment :raises CommandError...
log = logging.getLogger(mod_logger + '.source') if not isinstance(script, basestring): msg = 'script argument must be a string' log.error(msg) raise CommandError(msg) log.info('Attempting to source script: %s', script) try: pipe = subprocess.Popen(". %s; env" % script, 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 yum_update(downloadonly=False, dest_dir='/tmp'): """Run a yum update on this system This public method runs the yum -y update command to update packages from...
log = logging.getLogger(mod_logger + '.yum_update') # Type checks on the args if not isinstance(dest_dir, basestring): msg = 'dest_dir argument must be a string' log.error(msg) raise CommandError(msg) if not isinstance(downloadonly, bool): msg = 'downloadonly argument m...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rpm_install(install_dir): """This method installs all RPM files in a specific dir :param install_dir: (str) Full path to the directory :return int exit code ...
log = logging.getLogger(mod_logger + '.rpm_install') # Type checks on the args if not isinstance(install_dir, basestring): msg = 'install_dir argument must be a string' log.error(msg) raise CommandError(msg) # Ensure the install_dir directory exists if not os.path.isdir(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 sed(file_path, pattern, replace_str, g=0): """Python impl of the bash sed command This method emulates the functionality of a bash sed command. :param file_p...
log = logging.getLogger(mod_logger + '.sed') # Type checks on the args if not isinstance(file_path, basestring): msg = 'file_path argument must be a string' log.error(msg) raise CommandError(msg) if not isinstance(pattern, basestring): msg = 'pattern argument must be 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 zip_dir(dir_path, zip_file): """Creates a zip file of a directory tree This method creates a zip archive using the directory tree dir_path and adds to zip_fi...
log = logging.getLogger(mod_logger + '.zip_dir') # Validate args if not isinstance(dir_path, basestring): msg = 'dir_path argument must be a string' log.error(msg) raise CommandError(msg) if not isinstance(zip_file, basestring): msg = 'zip_file argument must be a string...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_ip(interface=0): """This method return the IP address :param interface: (int) Interface number (e.g. 0 for eth0) :return: (str) IP address or None """
log = logging.getLogger(mod_logger + '.get_ip') log.info('Getting the IP address for this system...') ip_address = None try: log.info('Attempting to get IP address by hostname...') ip_address = socket.gethostbyname(socket.gethostname()) except socket.error: log.info('Unable...