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 main(): """ Entry point for choosing what subcommand to run. Really should be using asciidocapi """
# Try parsing command line args and flags with docopt args = docopt(__doc__, version="cdk") # Am I going to need validation? No Schema for the moment... if args['FILE']: out = output_file(args['FILE']) # Great! Run asciidoc with appropriate flags theme = pick_theme(args['--theme...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def separate_resources(self): # type: () -> None """Move contents of resources key in internal dictionary into self.resources Returns: None """
self._separate_hdxobjects(self.resources, 'resources', 'name', hdx.data.resource.Resource)
<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_update_resources(self, resources, ignore_datasetid=False): # type: (List[Union[hdx.data.resource.Resource,Dict,str]], bool) -> None """Add new or update ...
if not isinstance(resources, list): raise HDXError('Resources should be a list!') for resource in resources: self.add_update_resource(resource, ignore_datasetid)
<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_resource(self, resource, delete=True): # type: (Union[hdx.data.resource.Resource,Dict,str], bool) -> bool """Delete a resource from the dataset and al...
if isinstance(resource, str): if is_valid_uuid(resource) is False: raise HDXError('%s is not a valid resource id!' % resource) return self._remove_hdxobject(self.resources, resource, delete=delete)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reorder_resources(self, resource_ids, hxl_update=True): # type: (List[str], bool) -> None """Reorder resources in dataset according to provided list. If only...
dataset_id = self.data.get('id') if not dataset_id: raise HDXError('Dataset has no id! It must be read, created or updated first.') data = {'id': dataset_id, 'order': resource_ids} self._write_to_hdx('reorder', data, 'package_id') if hxl_update: ...
<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_from_yaml(self, path=join('config', 'hdx_dataset_static.yml')): # type: (str) -> None """Update dataset metadata with static metadata from YAML file A...
super(Dataset, self).update_from_yaml(path) self.separate_resources()
<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_from_json(self, path=join('config', 'hdx_dataset_static.json')): # type: (str) -> None """Update dataset metadata with static metadata from JSON file ...
super(Dataset, self).update_from_json(path) self.separate_resources()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_from_hdx(identifier, configuration=None): # type: (str, Optional[Configuration]) -> Optional['Dataset'] """Reads the dataset given by identifier from HD...
dataset = Dataset(configuration=configuration) result = dataset._dataset_load_from_hdx(identifier) if result: return dataset 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 _dataset_create_resources(self): # type: () -> None """Creates resource objects in dataset """
if 'resources' in self.data: self.old_data['resources'] = self._copy_hdxobjects(self.resources, hdx.data.resource.Resource, 'file_to_upload') self.init_resources() self.separate_resources()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _dataset_load_from_hdx(self, id_or_name): # type: (str) -> bool """Loads the dataset given by either id or name from HDX Args: id_or_name (str): Either id o...
if not self._load_from_hdx('dataset', id_or_name): return False self._dataset_create_resources() return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_required_fields(self, ignore_fields=list(), allow_no_resources=False): # type: (List[str], bool) -> None """Check that metadata for dataset and its res...
if self.is_requestable(): self._check_required_fields('dataset-requestable', ignore_fields) else: self._check_required_fields('dataset', ignore_fields) if len(self.resources) == 0 and not allow_no_resources: raise HDXError('There are no resources! Ple...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _dataset_merge_filestore_resource(self, resource, updated_resource, filestore_resources, ignore_fields): # type: (hdx.data.Resource, hdx.data.Resource, List[...
if updated_resource.get_file_to_upload(): resource.set_file_to_upload(updated_resource.get_file_to_upload()) filestore_resources.append(resource) merge_two_dictionaries(resource, updated_resource) resource.check_required_fields(ignore_fields=ignore_fields) if 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 _dataset_merge_filestore_newresource(self, new_resource, ignore_fields, filestore_resources): # type: (hdx.data.Resource, List[str], List[hdx.data.Resource])...
new_resource.check_required_fields(ignore_fields=ignore_fields) self.resources.append(new_resource) if new_resource.get_file_to_upload(): filestore_resources.append(new_resource) new_resource['url'] = Dataset.temporary_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 _add_filestore_resources(self, filestore_resources, create_default_views, hxl_update): # type: (List[hdx.data.Resource], bool, bool) -> None """Helper method...
for resource in filestore_resources: for created_resource in self.data['resources']: if resource['name'] == created_resource['name']: merge_two_dictionaries(resource.data, created_resource) del resource['url'] resource.upda...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _dataset_merge_hdx_update(self, update_resources, update_resources_by_name, remove_additional_resources, create_default_views, hxl_update): # type: (bool, bo...
# 'old_data' here is the data we want to use for updating while 'data' is the data read from HDX merge_two_dictionaries(self.data, self.old_data) if 'resources' in self.data: del self.data['resources'] updated_resources = self.old_data.get('resources', None) filestor...
<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_in_hdx(self, update_resources=True, update_resources_by_name=True, remove_additional_resources=False, create_default_views=True, hxl_update=True): # t...
loaded = False if 'id' in self.data: self._check_existing_object('dataset', 'id') if self._dataset_load_from_hdx(self.data['id']): loaded = True else: logger.warning('Failed to load dataset with id %s' % self.data['id']) 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 create_in_hdx(self, allow_no_resources=False, update_resources=True, update_resources_by_name=True, remove_additional_resources=False, create_default_views=Tr...
self.check_required_fields(allow_no_resources=allow_no_resources) loadedid = None if 'id' in self.data: if self._dataset_load_from_hdx(self.data['id']): loadedid = self.data['id'] else: logger.warning('Failed to load dataset with id %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 search_in_hdx(cls, query='*:*', configuration=None, page_size=1000, **kwargs): # type: (Optional[str], Optional[Configuration], int, Any) -> List['Dataset'] ...
dataset = Dataset(configuration=configuration) total_rows = kwargs.get('rows', cls.max_int) start = kwargs.get('start', 0) all_datasets = None attempts = 0 while attempts < cls.max_attempts and all_datasets is None: # if the count values vary for multiple calls, then 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 get_all_dataset_names(configuration=None, **kwargs): # type: (Optional[Configuration], Any) -> List[str] """Get all dataset names in HDX Args: configuration ...
dataset = Dataset(configuration=configuration) dataset['id'] = 'all dataset names' # only for error message if produced return dataset._write_to_hdx('list', kwargs, '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_all_datasets(cls, configuration=None, page_size=1000, check_duplicates=True, **kwargs): # type: (Optional[Configuration], int, bool, Any) -> List['Datase...
dataset = Dataset(configuration=configuration) dataset['id'] = 'all datasets' # only for error message if produced total_rows = kwargs.get('limit', cls.max_int) start = kwargs.get('offset', 0) all_datasets = None attempts = 0 while attempts < cls.max_attempts 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 get_dataset_date_as_datetime(self): # type: () -> Optional[datetime] """Get dataset date as datetime.datetime object. For range returns start date. Returns: ...
dataset_date = self.data.get('dataset_date', None) if dataset_date: if '-' in dataset_date: dataset_date = dataset_date.split('-')[0] return datetime.strptime(dataset_date, '%m/%d/%Y') else: return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_dataset_end_date_as_datetime(self): # type: () -> Optional[datetime] """Get dataset end date as datetime.datetime object. Returns: Optional[datetime.date...
dataset_date = self.data.get('dataset_date', None) if dataset_date: if '-' in dataset_date: dataset_date = dataset_date.split('-')[1] return datetime.strptime(dataset_date, '%m/%d/%Y') return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_formatted_date(dataset_date, date_format=None): # type: (Optional[datetime], Optional[str]) -> Optional[str] """Get supplied dataset date as string in s...
if dataset_date: if date_format: return dataset_date.strftime(date_format) else: return dataset_date.date().isoformat() else: 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 _parse_date(dataset_date, date_format): # type: (str, Optional[str]) -> datetime """Parse dataset date from string using specified format. If no format is su...
if date_format is None: try: return parser.parse(dataset_date) except (ValueError, OverflowError) as e: raisefrom(HDXError, 'Invalid dataset date!', e) else: try: return datetime.strptime(dataset_date, date_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 set_dataset_date(self, dataset_date, dataset_end_date=None, date_format=None): # type: (str, Optional[str], Optional[str]) -> None """Set dataset date from s...
parsed_date = self._parse_date(dataset_date, date_format) if dataset_end_date is None: self.set_dataset_date_from_datetime(parsed_date) else: parsed_end_date = self._parse_date(dataset_end_date, date_format) self.set_dataset_date_from_datetime(parsed_date, pa...
<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_dataset_year_range(self, dataset_year, dataset_end_year=None): # type: (Union[str, int], Optional[Union[str, int]]) -> None """Set dataset date as a rang...
if isinstance(dataset_year, int): dataset_date = '01/01/%d' % dataset_year elif isinstance(dataset_year, str): dataset_date = '01/01/%s' % dataset_year else: raise hdx.data.hdxobject.HDXError('dataset_year has type %s which is not supported!' % type(dataset_y...
<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_expected_update_frequency(self, update_frequency): # type: (str) -> None """Set expected update frequency Args: update_frequency (str): Update frequency...
try: int(update_frequency) except ValueError: update_frequency = Dataset.transform_update_frequency(update_frequency) if not update_frequency: raise HDXError('Invalid update frequency supplied!') self.data['data_update_frequency'] = update_frequency
<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_tag(self, tag): # type: (str) -> bool """Remove a tag Args: tag (str): Tag to remove Returns: bool: True if tag removed or False if not """
return self._remove_hdxobject(self.data.get('tags'), tag, matchon='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_location(self, locations=None): # type: (Optional[List[str]]) -> List[str] """Return the dataset's location Args: locations (Optional[List[str]]): Valid...
countries = self.data.get('groups', None) if not countries: return list() return [Locations.get_location_from_HDX_code(x['name'], locations=locations, configuration=self.configuration) for x in countries]
<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_country_location(self, country, exact=True, locations=None, use_live=True): # type: (str, bool, Optional[List[str]], bool) -> bool """Add a country. If a...
iso3, match = Country.get_iso3_country_code_fuzzy(country, use_live=use_live) if iso3 is None: raise HDXError('Country: %s - cannot find iso3 code!' % country) return self.add_other_location(iso3, exact=exact, alterror='Country: %s with iso3: %...
<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_country_locations(self, countries, locations=None, use_live=True): # type: (List[str], Optional[List[str]], bool) -> bool """Add a list of countries. If ...
allcountriesadded = True for country in countries: if not self.add_country_location(country, locations=locations, use_live=use_live): allcountriesadded = False return allcountriesadded
<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_region_location(self, region, locations=None, use_live=True): # type: (str, Optional[List[str]], bool) -> bool """Add all countries in a region. If a 3 d...
return self.add_country_locations(Country.get_countries_in_region(region, exception=HDXError, use_live=use_live), locations=locations)
<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_other_location(self, location, exact=True, alterror=None, locations=None): # type: (str, bool, Optional[str], Optional[List[str]]) -> bool """Add a locat...
hdx_code, match = Locations.get_HDX_code_from_location_partial(location, locations=locations, configuration=self.configuration) if hdx_code is None or (exact is True and match is False): if alterror 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 remove_location(self, location): # type: (str) -> bool """Remove a location. If the location is already added, it is ignored. Args: location (str): Location...
res = self._remove_hdxobject(self.data.get('groups'), location, matchon='name') if not res: res = self._remove_hdxobject(self.data.get('groups'), location.upper(), matchon='name') if not res: res = self._remove_hdxobject(self.data.get('groups'), location.lower(), matchon...
<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_maintainer(self): # type: () -> hdx.data.user.User """Get the dataset's maintainer. Returns: User: Dataset's maintainer """
return hdx.data.user.User.read_from_hdx(self.data['maintainer'], configuration=self.configuration)
<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_maintainer(self, maintainer): # type: (Union[hdx.data.user.User,Dict,str]) -> None """Set the dataset's maintainer. Args: maintainer (Union[User,Dict,str...
if isinstance(maintainer, hdx.data.user.User) or isinstance(maintainer, dict): if 'id' not in maintainer: maintainer = hdx.data.user.User.read_from_hdx(maintainer['name'], configuration=self.configuration) maintainer = maintainer['id'] elif not isinstance(maintai...
<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_organization(self): # type: () -> hdx.data.organization.Organization """Get the dataset's organization. Returns: Organization: Dataset's organization """
return hdx.data.organization.Organization.read_from_hdx(self.data['owner_org'], configuration=self.configuration)
<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_organization(self, organization): # type: (Union[hdx.data.organization.Organization,Dict,str]) -> None """Set the dataset's organization. Args: organizat...
if isinstance(organization, hdx.data.organization.Organization) or isinstance(organization, dict): if 'id' not in organization: organization = hdx.data.organization.Organization.read_from_hdx(organization['name'], configuration=self.configuration) organization = organiza...
<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_showcases(self): # type: () -> List[hdx.data.showcase.Showcase] """Get any showcases the dataset is in Returns: List[Showcase]: list of showcases """
assoc_result, showcases_dicts = self._read_from_hdx('showcase', self.data['id'], fieldname='package_id', action=hdx.data.showcase.Showcase.actions()['list_showcases']) showcases = list() if assoc_result: for showcase_dict 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 _get_dataset_showcase_dict(self, showcase): # type: (Union[hdx.data.showcase.Showcase, Dict,str]) -> Dict """Get dataset showcase dict Args: showcase (Union[...
if isinstance(showcase, hdx.data.showcase.Showcase) or isinstance(showcase, dict): if 'id' not in showcase: showcase = hdx.data.showcase.Showcase.read_from_hdx(showcase['name']) showcase = showcase['id'] elif not isinstance(showcase, str): raise HDXEr...
<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_showcase(self, showcase, showcases_to_check=None): # type: (Union[hdx.data.showcase.Showcase,Dict,str], List[hdx.data.showcase.Showcase]) -> bool """Add ...
dataset_showcase = self._get_dataset_showcase_dict(showcase) if showcases_to_check is None: showcases_to_check = self.get_showcases() for showcase in showcases_to_check: if dataset_showcase['showcase_id'] == showcase['id']: return False showcase =...
<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_showcases(self, showcases, showcases_to_check=None): # type: (List[Union[hdx.data.showcase.Showcase,Dict,str]], List[hdx.data.showcase.Showcase]) -> bool...
if showcases_to_check is None: showcases_to_check = self.get_showcases() allshowcasesadded = True for showcase in showcases: if not self.add_showcase(showcase, showcases_to_check=showcases_to_check): allshowcasesadded = False return allshowcasesad...
<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_showcase(self, showcase): # type: (Union[hdx.data.showcase.Showcase,Dict,str]) -> None """Remove dataset from showcase Args: showcase (Union[Showcase,...
dataset_showcase = self._get_dataset_showcase_dict(showcase) showcase = hdx.data.showcase.Showcase({'id': dataset_showcase['showcase_id']}, configuration=self.configuration) showcase._write_to_hdx('disassociate', dataset_showcase, 'package_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 set_requestable(self, requestable=True): # type: (bool) -> None """Set the dataset to be of type requestable or not Args: requestable (bool): Set whether da...
self.data['is_requestdata_type'] = requestable if requestable: self.data['private'] = 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_filetypes(self): # type: () -> List[str] """Return list of filetypes in your data Returns: List[str]: List of filetypes """
if not self.is_requestable(): return [resource.get_file_type() for resource in self.get_resources()] return self._get_stringlist_from_commastring('file_types')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clean_dataset_tags(self): # type: () -> Tuple[bool, bool] """Clean dataset tags according to tags cleanup spreadsheet and return if any changes occurred Retu...
tags_dict, wildcard_tags = Tags.tagscleanupdicts() def delete_tag(tag): logger.info('%s - Deleting tag %s!' % (self.data['name'], tag)) return self.remove_tag(tag), False def update_tag(tag, final_tags, wording, remove_existing=True): text = '%s - %s: %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 set_quickchart_resource(self, resource): # type: (Union[hdx.data.resource.Resource,Dict,str,int]) -> bool """Set the resource that will be used for displayin...
if isinstance(resource, int) and not isinstance(resource, bool): resource = self.get_resources()[resource] if isinstance(resource, hdx.data.resource.Resource) or isinstance(resource, dict): res = resource.get('id') if res is None: resource = resource[...
<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_default_views(self, create_datastore_views=False): # type: (bool) -> None """Create default resource views for all resources in dataset Args: create_d...
package = deepcopy(self.data) if self.resources: package['resources'] = self._convert_hdxobjects(self.resources) data = {'package': package, 'create_datastore_views': create_datastore_views} self._write_to_hdx('create_default_views', data, 'package')
<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_credentials(self): # type: () -> Optional[Tuple[str, str]] """ Return HDX site username and password Returns: Optional[Tuple[str, str]]: HDX site userna...
site = self.data[self.hdx_site] username = site.get('username') if username: return b64decode(username).decode('utf-8'), b64decode(site['password']).decode('utf-8') else: 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 call_remoteckan(self, *args, **kwargs): # type: (Any, Any) -> Dict """ Calls the remote CKAN Args: *args: Arguments to pass to remote CKAN call_action method...
requests_kwargs = kwargs.get('requests_kwargs', dict()) credentials = self._get_credentials() if credentials: requests_kwargs['auth'] = credentials kwargs['requests_kwargs'] = requests_kwargs apikey = kwargs.get('apikey', self.get_api_key()) kwargs['apikey'] ...
<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_remoteckan(cls, site_url, user_agent=None, user_agent_config_yaml=None, user_agent_lookup=None, session=None, **kwargs): # type: (str, Optional[str], ...
if not session: session = get_session(user_agent, user_agent_config_yaml, user_agent_lookup, prefix=Configuration.prefix, method_whitelist=frozenset(['HEAD', 'TRACE', 'GET', 'POST', 'PUT', 'OPTIONS', 'DE...
<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_remoteckan(self, remoteckan=None, **kwargs): # type: (Optional[ckanapi.RemoteCKAN], Any) -> None """ Set up remote CKAN from provided CKAN or by creati...
if remoteckan is None: self._remoteckan = self.create_remoteckan(self.get_hdx_site_url(), full_agent=self.get_user_agent(), **kwargs) else: self._remoteckan = remoteckan
<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(cls, configuration=None, **kwargs): # type: (Optional['Configuration'], Any) -> None """ Set up the HDX configuration Args: configuration (Optional[Con...
if configuration is None: cls._configuration = Configuration(**kwargs) else: cls._configuration = configuration
<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(cls, configuration=None, remoteckan=None, **kwargs): # type: (Optional['Configuration'], Optional[ckanapi.RemoteCKAN], Any) -> str """ Create HDX con...
kwargs = cls._environment_variables(**kwargs) cls.setup(configuration, **kwargs) cls._configuration.setup_remoteckan(remoteckan, **kwargs) return cls._configuration.get_hdx_site_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 kwargs_to_variable_assignment(kwargs: dict, value_representation=repr, assignment_operator: str = ' = ', statement_separator: str = '\n', statement_per_line: ...
code = [] join_str = '\n' if statement_per_line else '' for key, value in kwargs.items(): code.append(key + assignment_operator + value_representation(value)+statement_separator) return join_str.join(code)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decode_json(json_input: Union[str, None] = None): """ Simple wrapper of json.load and json.loads. If json_input is None the output is an empty dictionary. If...
if json_input is None: return {} else: if isinstance(json_input, str) is False: raise TypeError() elif json_input[-5:] == ".json": with open(json_input) as f: decoded_json = json.load(f) else: decoded_json = json.loads(json_inp...
<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_jsonable(obj) -> bool: """ Check if an object is jsonable. An object is jsonable if it is json serialisable and by loading its json representation the same...
try: return obj==json.loads(json.dumps(obj)) except TypeError: return False except: raise
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_literal_eval(node_or_string) -> tuple: """ Check if an expresion can be literal_eval. node_or_string : Input Returns ------- tuple (bool,python object) If ...
try: obj=ast.literal_eval(node_or_string) return (True, obj) except: return (False, 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_duplicates(l: list) -> set: """ Return the duplicates in a list. The function relies on https://stackoverflow.com/questions/9835762/find-and-list-duplica...
return set([x for x in l if l.count(x) > 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 sort_dict(d: dict, by: str = 'key', allow_duplicates: bool = True) -> collections.OrderedDict: """ Sort a dictionary by key or value. The function relies on h...
if by == 'key': i = 0 elif by == 'value': values = list(d.values()) if len(values) != len(set(values)) and not allow_duplicates: duplicates = find_duplicates(values) raise ValueError("There are duplicates in the values: {}".format(duplicates)) i = 1 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 group_dict_by_value(d: dict) -> dict: """ Group a dictionary by values. Parameters d : dict Input dictionary Returns ------- dict Output dictionary. The keys ...
d_out = {} for k, v in d.items(): if v in d_out: d_out[v].append(k) else: d_out[v] = [k] return d_out
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def variable_status(code: str, exclude_variable: Union[set, None] = None, jsonable_parameter: bool = True) -> tuple: """ Find the possible parameters and "global"...
if exclude_variable is None: exclude_variable = set() else: exclude_variable = copy.deepcopy(exclude_variable) root = ast.parse(code) store_variable_name = set() assign_only = True dict_parameter={} for node in ast.iter_child_nodes(root): if isinstance(node, ast.Ass...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def increment_name(name: str, start_marker: str = " (", end_marker: str = ")") -> str: """ Increment the name where the incremental part is given by parameters. P...
if start_marker == '': raise ValueError("start_marker can not be the empty string.") a = name start = len(a)-a[::-1].find(start_marker[::-1]) if (a[len(a)-len(end_marker):len(a)] == end_marker and start < (len(a)-len(end_marker)) and a[start-len(start_marker):start] == ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_from_hdx(identifier, configuration=None): # type: (str, Optional[Configuration]) -> Optional['ResourceView'] """Reads the resource view given by identif...
resourceview = ResourceView(configuration=configuration) result = resourceview._load_from_hdx('resource view', identifier) if result: return resourceview return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_all_for_resource(identifier, configuration=None): # type: (str, Optional[Configuration]) -> List['ResourceView'] """Read all resource views for a resourc...
resourceview = ResourceView(configuration=configuration) success, result = resourceview._read_from_hdx('resource view', identifier, 'id', ResourceView.actions()['list']) resourceviews = list() if success: for resourceviewdict in result: resourceview = Resour...
<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_resource_view(self, log=False): # type: () -> bool """Check if resource view exists in HDX and if so, update resource view Returns: bool: True if upd...
update = False if 'id' in self.data and self._load_from_hdx('resource view', self.data['id']): update = True else: if 'resource_id' in self.data: resource_views = self.get_all_for_resource(self.data['resource_id']) for resource_view in 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 create_in_hdx(self): # type: () -> None """Check if resource view exists in HDX and if so, update it, otherwise create resource view Returns: None """
self.check_required_fields() if not self._update_resource_view(log=True): self._save_to_hdx('create', 'title')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def copy(self, resource_view): # type: (Union[ResourceView,Dict,str]) -> None """Copies all fields except id, resource_id and package_id from another resource vi...
if isinstance(resource_view, str): if is_valid_uuid(resource_view) is False: raise HDXError('%s is not a valid resource view id!' % resource_view) resource_view = ResourceView.read_from_hdx(resource_view) if not isinstance(resource_view, dict) and not isinstance(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tagscleanupdicts(configuration=None, url=None, keycolumn=5, failchained=True): # type: (Optional[Configuration], Optional[str], int, bool) -> Tuple[Dict,List...
if not Tags._tags_dict: if configuration is None: configuration = Configuration.read() with Download(full_agent=configuration.get_user_agent()) as downloader: if url is None: url = configuration['tags_cleanup_url'] Tags...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_from_hdx(identifier, configuration=None): # type: (str, Optional[Configuration]) -> Optional['User'] """Reads the user given by identifier from HDX and ...
user = User(configuration=configuration) result = user._load_from_hdx('user', identifier) if result: return user 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 update_in_hdx(self): # type: () -> None """Check if user exists in HDX and if so, update user Returns: None """
capacity = self.data.get('capacity') if capacity is not None: del self.data['capacity'] # remove capacity (which comes from users from Organization) self._update_in_hdx('user', 'id') if capacity is not None: self.data['capacity'] = capacity
<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_in_hdx(self): # type: () -> None """Check if user exists in HDX and if so, update it, otherwise create user Returns: None """
capacity = self.data.get('capacity') if capacity is not None: del self.data['capacity'] self._create_in_hdx('user', 'id', 'name') if capacity is not None: self.data['capacity'] = capacity
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def email(self, subject, text_body, html_body=None, sender=None, **kwargs): # type: (str, str, Optional[str], Optional[str], Any) -> None """Emails a user. Args:...
self.configuration.emailer().send([self.data['email']], subject, text_body, html_body=html_body, sender=sender, **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 get_all_users(configuration=None, **kwargs): # type: (Optional[Configuration], Any) -> List['User'] """Get all users in HDX Args: configuration (Optional[Con...
user = User(configuration=configuration) user['id'] = 'all users' # only for error message if produced result = user._write_to_hdx('list', kwargs, 'id') users = list() if result: for userdict in result: user = User(userdict, configuration=configurati...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def email_users(users, subject, text_body, html_body=None, sender=None, configuration=None, **kwargs): # type: (List['User'], str, str, Optional[str], Optional[s...
if not users: raise ValueError('No users supplied') recipients = list() for user in users: recipients.append(user.data['email']) if configuration is None: configuration = users[0].configuration configuration.emailer().send(recipients, subject,...
<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_organizations(self, permission='read'): # type: (str) -> List['Organization'] """Get organizations in HDX that this user is a member of. Args: permission...
success, result = self._read_from_hdx('user', self.data['name'], 'id', self.actions()['listorgs'], permission=permission) organizations = list() if success: for organizationdict in result: organization = hdx.data.organiza...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def facade(projectmainfn, **kwargs): # (Callable[[None], None], Any) -> None """Facade to simplify project setup that calls project main function Args: projectma...
# # Setting up configuration # site_url = Configuration._create(**kwargs) logger.info('--------------------------------------------------') logger.info('> Using HDX Python API Library %s' % Configuration.apiversion) logger.info('> HDX Site: %s' % site_url) UserAgent.user_agent = Conf...
<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_lint_config(config_path=None): """ Tries loading the config from the given path. If no path is specified, the default config path is tried, and if that i...
# config path specified if config_path: config = LintConfig.load_from_file(config_path) click.echo("Using config from {0}".format(config_path)) # default config path elif os.path.exists(DEFAULT_CONFIG_FILE): config = LintConfig.load_from_file(DEFAULT_CONFIG_FILE) click.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 cli(list_files, config, ignore, path): """ Markdown lint tool, checks your markdown for styling issues """
files = MarkdownFileFinder.find_files(path) if list_files: echo_files(files) lint_config = get_lint_config(config) lint_config.apply_on_csv_string(ignore, lint_config.disable_rule) linter = MarkdownLinter(lint_config) error_count = linter.lint_files(files) exit(error_count)
<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, check_interval=300): """ Run the daemon :type check_interval: int :param check_interval: Delay in seconds between checks """
while True: # Read configuration from the config file if present, else fall # back to command line options if args.config: config = config_file_parser.get_configuration(args.config) access_key_id = config['access-key-id'] secre...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _apply_line_rules(self, markdown_string): """ Iterates over the lines in a given markdown string and applies all the enabled line rules to each line """
all_violations = [] lines = markdown_string.split("\n") line_rules = self.line_rules line_nr = 1 ignoring = False for line in lines: if ignoring: if line.strip() == '<!-- markdownlint:enable -->': ignoring = 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 ReadFrom(self, byte_stream): """Read values from a byte stream. Args: byte_stream (bytes): byte stream. Returns: Raises: IOError: if byte stream cannot be r...
try: return self._struct.unpack_from(byte_stream) except (TypeError, struct.error) as exception: raise IOError('Unable to read byte stream with error: {0!s}'.format( exception))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def WriteTo(self, values): """Writes values to a byte stream. Args: Returns: bytes: byte stream. Raises: IOError: if byte stream cannot be written. OSError: if b...
try: return self._struct.pack(*values) except (TypeError, struct.error) as exception: raise IOError('Unable to write stream with error: {0!s}'.format( exception))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(connection): """ Ensure that we have snapshots for a given volume :type connection: boto.ec2.connection.EC2Connection :param connection: EC2 connection o...
volumes = volume_manager.get_watched_volumes(connection) for volume in volumes: _ensure_snapshot(connection, volume) _remove_old_snapshots(connection, volume)
<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_snapshot(volume): """ Create a new snapshot :type volume: boto.ec2.volume.Volume :param volume: Volume to snapshot :returns: boto.ec2.snapshot.Snapsh...
logger.info('Creating new snapshot for {}'.format(volume.id)) snapshot = volume.create_snapshot( description="Automatic snapshot by Automated EBS Snapshots") logger.info('Created snapshot {} for volume {}'.format( snapshot.id, volume.id)) return snapshot
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _ensure_snapshot(connection, volume): """ Ensure that a given volume has an appropriate snapshot :type connection: boto.ec2.connection.EC2Connection :param c...
if 'AutomatedEBSSnapshots' not in volume.tags: logger.warning( 'Missing tag AutomatedEBSSnapshots for volume {}'.format( volume.id)) return interval = volume.tags['AutomatedEBSSnapshots'] if volume.tags['AutomatedEBSSnapshots'] not in VALID_INTERVALS: lo...
<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_old_snapshots(connection, volume): """ Remove old snapshots :type connection: boto.ec2.connection.EC2Connection :param connection: EC2 connection obj...
if 'AutomatedEBSSnapshotsRetention' not in volume.tags: logger.warning( 'Missing tag AutomatedEBSSnapshotsRetention for volume {}'.format( volume.id)) return retention = int(volume.tags['AutomatedEBSSnapshotsRetention']) snapshots = connection.get_all_snapshots(...
<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(connection): """ List watched EBS volumes :type connection: boto.ec2.connection.EC2Connection :param connection: EC2 connection object :returns: None ""...
volumes = get_watched_volumes(connection) if not volumes: logger.info('No watched volumes found') return logger.info( '+-----------------------' '+----------------------' '+--------------' '+------------+') logger.info( '| {volume:<21} ' ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unwatch(connection, volume_id): """ Remove watching of a volume :type connection: boto.ec2.connection.EC2Connection :param connection: EC2 connection object ...
try: volume = connection.get_all_volumes(volume_ids=[volume_id])[0] volume.remove_tag('AutomatedEBSSnapshots') except EC2ResponseError: pass logger.info('Removed {} from the watchlist'.format(volume_id)) return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_volume_id(connection, volume): """ Get Volume ID from the given volume. Input can be volume id or its Name tag. :type connection: boto.ec2.connection.EC2...
# Regular expression to check whether input is a volume id volume_id_pattern = re.compile('vol-\w{8}') if volume_id_pattern.match(volume): # input is volume id try: # Check whether it exists connection.get_all_volumes(volume_ids=[volume]) volume_id = vol...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_snapshots(connection, volume): """ List all snapshots for the volume :type connection: boto.ec2.connection.EC2Connection :param connection: EC2 connecti...
logger.info( '+----------------' '+----------------------' '+---------------------------+') logger.info( '| {snapshot:<14} ' '| {snapshot_name:<20.20} ' '| {created:<25} |'.format( snapshot='Snapshot ID', snapshot_name='Snapshot 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 stem(self, words, parser, **kwargs): """ Get stems for the words using a given parser Example: from .parsing import ListParser parser = ListParser() stemmer ...
output = self._run_morfologik(words) return parser.parse(output, **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 _run_morfologik(self, words): """ Runs morfologik java jar and assumes that input and output is UTF-8 encoded. """
p = subprocess.Popen( ['java', '-jar', self.jar_path, 'plstem', '-ie', 'UTF-8', '-oe', 'UTF-8'], bufsize=-1, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out, _ = p.communicate(input=bytes(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_from_hdx(identifier, configuration=None): # type: (str, Optional[Configuration]) -> Optional['Showcase'] """Reads the showcase given by identifier from ...
showcase = Showcase(configuration=configuration) result = showcase._load_from_hdx('showcase', identifier) if result: return showcase return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_datasets(self): # type: () -> List[hdx.data.dataset.Dataset] """Get any datasets in the showcase Returns: List[Dataset]: List of datasets """
assoc_result, datasets_dicts = self._read_from_hdx('showcase', self.data['id'], fieldname='showcase_id', action=self.actions()['list_datasets']) datasets = list() if assoc_result: for dataset_dict in datasets_dicts: ...
<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_showcase_dataset_dict(self, dataset): # type: (Union[hdx.data.dataset.Dataset,Dict,str]) -> Dict """Get showcase dataset dict Args: showcase (Union[Show...
if isinstance(dataset, hdx.data.dataset.Dataset) or isinstance(dataset, dict): if 'id' not in dataset: dataset = hdx.data.dataset.Dataset.read_from_hdx(dataset['name']) dataset = dataset['id'] elif not isinstance(dataset, str): raise hdx.data.hdxobjec...
<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_dataset(self, dataset, datasets_to_check=None): # type: (Union[hdx.data.dataset.Dataset,Dict,str], List[hdx.data.dataset.Dataset]) -> bool """Add a datas...
showcase_dataset = self._get_showcase_dataset_dict(dataset) if datasets_to_check is None: datasets_to_check = self.get_datasets() for dataset in datasets_to_check: if showcase_dataset['package_id'] == dataset['id']: return False self._write_to_hdx...
<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_datasets(self, datasets, datasets_to_check=None): # type: (List[Union[hdx.data.dataset.Dataset,Dict,str]], List[hdx.data.dataset.Dataset]) -> bool """Add...
if datasets_to_check is None: datasets_to_check = self.get_datasets() alldatasetsadded = True for dataset in datasets: if not self.add_dataset(dataset, datasets_to_check=datasets_to_check): alldatasetsadded = False return alldatasetsadded
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def join(self, joiner, formatter=lambda s, t: t.format(s), template="{}"): """Join values and convert to string Example: u'0,1,2' u'0#,1#,2#' formatter = lambda ...
return ww.s(joiner).join(self, formatter, 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 append(self, *values): """Append values at the end of the list Allow chaining. Args: values: values to be appened at the end. Example: [1] [1] [1, 2, 3, 4, 5...
for value in values: list.append(self, value) return self