text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def connect_to_ec2(region='us-east-1', access_key=None, secret_key=None): """ Connect to AWS ec2 :type region: str :param region: AWS region to connect to :type ...
if access_key: # Connect using supplied credentials logger.info('Connecting to AWS EC2 in {}'.format(region)) connection = ec2.connect_to_region( region, aws_access_key_id=access_key, aws_secret_access_key=secret_key) else: # Fetch instance 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 parse(self, output): """ Find stems for a given text. """
output = self._get_lines_with_stems(output) words = self._make_unique(output) return self._parse_for_simple_stems(words)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validlocations(configuration=None): # type: () -> List[Dict] """ Read valid locations from HDX Args: configuration (Optional[Configuration]): HDX configurat...
if Locations._validlocations is None: if configuration is None: configuration = Configuration.read() Locations._validlocations = configuration.call_remoteckan('group_list', {'all_fields': True}) return Locations._validlocations
<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_from_HDX_code(code, locations=None, configuration=None): # type: (str, Optional[List[Dict]], Optional[Configuration]) -> Optional[str] """Get lo...
if locations is None: locations = Locations.validlocations(configuration) for locdict in locations: if code.upper() == locdict['name'].upper(): return locdict['title'] 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 CheckDirectory(self, path, extension='yaml'): """Validates definition files in a directory. Args: path (str): path of the definition file. extension (Option...
result = True if extension: glob_spec = os.path.join(path, '*.{0:s}'.format(extension)) else: glob_spec = os.path.join(path, '*') for definition_file in sorted(glob.glob(glob_spec)): if not self.CheckFile(definition_file): result = False return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def CheckFile(self, path): """Validates the definition in a file. Args: path (str): path of the definition file. Returns: bool: True if the file contains valid ...
print('Checking: {0:s}'.format(path)) definitions_registry = registry.DataTypeDefinitionsRegistry() definitions_reader = reader.YAMLDataTypeDefinitionsFileReader() result = False try: definitions_reader.ReadFile(definitions_registry, path) result = True except KeyError as excepti...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def inline_css(html_message, encoding='unicode'): """ Inlines all CSS in an HTML string Given an HTML document with CSS declared in the HEAD, inlines it into the...
document = etree.HTML(html_message) converter = Conversion() converter.perform(document, html_message, '', encoding=encoding) return converter.convertedHTML
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _CheckByteStreamSize(self, byte_stream, byte_offset, data_type_size): """Checks if the byte stream is large enough for the data type. Args: byte_stream (byte...
try: byte_stream_size = len(byte_stream) except Exception as exception: raise errors.MappingError(exception) if byte_stream_size - byte_offset < data_type_size: raise errors.ByteStreamTooSmallError( 'Byte stream too small requested: {0:d} available: {1:d}'.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 _GetByteStreamOperation(self): """Retrieves the byte stream operation. Returns: ByteStreamOperation: byte stream operation or None if unable to determine. ""...
byte_order_string = self.GetStructByteOrderString() format_string = self.GetStructFormatString() # pylint: disable=assignment-from-none if not format_string: return None format_string = ''.join([byte_order_string, format_string]) return byte_operations.StructOperation(format_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 FoldValue(self, value): """Folds the data type into a value. Args: value (object): value. Returns: object: folded value. Raises: ValueError: if the data typ...
if value is False and self._data_type_definition.false_value is not None: return self._data_type_definition.false_value if value is True and self._data_type_definition.true_value is not None: return self._data_type_definition.true_value raise ValueError('No matching True and False 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 _CalculateElementsDataSize(self, context): """Calculates the elements data size. Args: context (Optional[DataTypeMapContext]): data type map context, used t...
elements_data_size = None if self._HasElementsDataSize(): elements_data_size = self._EvaluateElementsDataSize(context) elif self._HasNumberOfElements(): element_byte_size = self._element_data_type_definition.GetByteSize() if element_byte_size is not None: number_of_elements = se...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _EvaluateElementsDataSize(self, context): """Evaluates elements data size. Args: context (DataTypeMapContext): data type map context. Returns: int: elements...
elements_data_size = None if self._data_type_definition.elements_data_size: elements_data_size = self._data_type_definition.elements_data_size elif self._data_type_definition.elements_data_size_expression: expression = self._data_type_definition.elements_data_size_expression namespace = ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _EvaluateNumberOfElements(self, context): """Evaluates number of elements. Args: context (DataTypeMapContext): data type map context. Returns: int: number o...
number_of_elements = None if self._data_type_definition.number_of_elements: number_of_elements = self._data_type_definition.number_of_elements elif self._data_type_definition.number_of_elements_expression: expression = self._data_type_definition.number_of_elements_expression namespace = ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _GetElementDataTypeDefinition(self, data_type_definition): """Retrieves the element data type definition. Args: data_type_definition (DataTypeDefinition): d...
if not data_type_definition: raise errors.FormatError('Missing data type definition') element_data_type_definition = getattr( data_type_definition, 'element_data_type_definition', None) if not element_data_type_definition: raise errors.FormatError( 'Invalid data type definiti...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _CheckCompositeMap(self, data_type_definition): """Determines if the data type definition needs a composite map. Args: data_type_definition (DataTypeDefiniti...
if not data_type_definition: raise errors.FormatError('Missing data type definition') members = getattr(data_type_definition, 'members', None) if not members: raise errors.FormatError('Invalid data type definition missing members') is_composite_map = False last_member_byte_order = 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 _GetMemberDataTypeMaps(self, data_type_definition, data_type_map_cache): """Retrieves the member data type maps. Args: data_type_definition (DataTypeDefiniti...
if not data_type_definition: raise errors.FormatError('Missing data type definition') members = getattr(data_type_definition, 'members', None) if not members: raise errors.FormatError('Invalid data type definition missing members') data_type_maps = [] members_data_size = 0 for me...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def GetName(self, number): """Retrieves the name of an enumeration value by number. Args: number (int): number. Returns: str: name of the enumeration value or N...
value = self._data_type_definition.values_per_number.get(number, None) if not value: return None return value.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 CreateDataTypeMap(self, definition_name): """Creates a specific data type map by name. Args: definition_name (str): name of the data type definition. Return...
data_type_definition = self._definitions_registry.GetDefinitionByName( definition_name) if not data_type_definition: return None return DataTypeMapFactory.CreateDataTypeMapByType(data_type_definition)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def CreateDataTypeMapByType(cls, data_type_definition): """Creates a specific data type map by type indicator. Args: data_type_definition (DataTypeDefinition): ...
data_type_map_class = cls._MAP_PER_DEFINITION.get( data_type_definition.TYPE_INDICATOR, None) if not data_type_map_class: return None return data_type_map_class(data_type_definition)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def IsComposite(self): """Determines if the data type is composite. A composite data type consists of other data types. Returns: bool: True if the data type is c...
return bool(self.condition) or ( self.member_data_type_definition and self.member_data_type_definition.IsComposite())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def AddValue(self, name, number, aliases=None, description=None): """Adds an enumeration value. Args: name (str): name. number (int): number. aliases (Optional...
if name in self.values_per_name: raise KeyError('Value with name: {0:s} already exists.'.format(name)) if number in self.values_per_number: raise KeyError('Value with number: {0!s} already exists.'.format(number)) for alias in aliases or []: if alias in self.values_per_alias: ra...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _ReadBooleanDataTypeDefinition( self, definitions_registry, definition_values, definition_name, is_member=False): """Reads a boolean data type definition. Ar...
return self._ReadFixedSizeDataTypeDefinition( definitions_registry, definition_values, data_types.BooleanDefinition, definition_name, self._SUPPORTED_ATTRIBUTES_BOOLEAN, is_member=is_member, supported_size_values=(1, 2, 4))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _ReadCharacterDataTypeDefinition( self, definitions_registry, definition_values, definition_name, is_member=False): """Reads a character data type definition...
return self._ReadFixedSizeDataTypeDefinition( definitions_registry, definition_values, data_types.CharacterDefinition, definition_name, self._SUPPORTED_ATTRIBUTES_FIXED_SIZE_DATA_TYPE, is_member=is_member, supported_size_values=(1, 2, 4))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _ReadConstantDataTypeDefinition( self, definitions_registry, definition_values, definition_name, is_member=False): """Reads a constant data type definition. ...
if is_member: error_message = 'data type not supported as member' raise errors.DefinitionReaderError(definition_name, error_message) value = definition_values.get('value', None) if value is None: error_message = 'missing value' raise errors.DefinitionReaderError(definition_name, er...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _ReadDataTypeDefinitionWithMembers( self, definitions_registry, definition_values, data_type_definition_class, definition_name, supports_conditions=False): "...
members = definition_values.get('members', None) if not members: error_message = 'missing members' raise errors.DefinitionReaderError(definition_name, error_message) supported_definition_values = ( self._SUPPORTED_DEFINITION_VALUES_STORAGE_DATA_TYPE_WITH_MEMBERS) definition_object ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _ReadEnumerationDataTypeDefinition( self, definitions_registry, definition_values, definition_name, is_member=False): """Reads an enumeration data type defin...
if is_member: error_message = 'data type not supported as member' raise errors.DefinitionReaderError(definition_name, error_message) values = definition_values.get('values') if not values: error_message = 'missing values' raise errors.DefinitionReaderError(definition_name, error_me...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _ReadElementSequenceDataTypeDefinition( self, definitions_registry, definition_values, data_type_definition_class, definition_name, supported_definition_value...
unsupported_definition_values = set(definition_values.keys()).difference( supported_definition_values) if unsupported_definition_values: error_message = 'unsupported definition values: {0:s}'.format( ', '.join(unsupported_definition_values)) raise errors.DefinitionReaderError(defi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _ReadFixedSizeDataTypeDefinition( self, definitions_registry, definition_values, data_type_definition_class, definition_name, supported_attributes, default_si...
definition_object = self._ReadStorageDataTypeDefinition( definitions_registry, definition_values, data_type_definition_class, definition_name, supported_attributes, is_member=is_member) attributes = definition_values.get('attributes', None) if attributes: size = attributes.get('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 _ReadFloatingPointDataTypeDefinition( self, definitions_registry, definition_values, definition_name, is_member=False): """Reads a floating-point data type d...
return self._ReadFixedSizeDataTypeDefinition( definitions_registry, definition_values, data_types.FloatingPointDefinition, definition_name, self._SUPPORTED_ATTRIBUTES_FIXED_SIZE_DATA_TYPE, is_member=is_member, supported_size_values=(4, 8))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _ReadFormatDataTypeDefinition( self, definitions_registry, definition_values, definition_name, is_member=False): """Reads a format data type definition. Args...
if is_member: error_message = 'data type not supported as member' raise errors.DefinitionReaderError(definition_name, error_message) definition_object = self._ReadLayoutDataTypeDefinition( definitions_registry, definition_values, data_types.FormatDefinition, definition_name, self._...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _ReadIntegerDataTypeDefinition( self, definitions_registry, definition_values, definition_name, is_member=False): """Reads an integer data type definition. A...
definition_object = self._ReadFixedSizeDataTypeDefinition( definitions_registry, definition_values, data_types.IntegerDefinition, definition_name, self._SUPPORTED_ATTRIBUTES_INTEGER, is_member=is_member, supported_size_values=(1, 2, 4, 8)) attributes = definition_values.get('at...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _ReadLayoutDataTypeDefinition( self, definitions_registry, definition_values, data_type_definition_class, definition_name, supported_definition_values): """R...
return self._ReadDataTypeDefinition( definitions_registry, definition_values, data_type_definition_class, definition_name, supported_definition_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 _ReadPaddingDataTypeDefinition( self, definitions_registry, definition_values, definition_name, is_member=False): """Reads a padding data type definition. Ar...
if not is_member: error_message = 'data type only supported as member' raise errors.DefinitionReaderError(definition_name, error_message) definition_object = self._ReadDataTypeDefinition( definitions_registry, definition_values, data_types.PaddingDefinition, definition_name, self._...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _ReadSemanticDataTypeDefinition( self, definitions_registry, definition_values, data_type_definition_class, definition_name, supported_definition_values): ""...
return self._ReadDataTypeDefinition( definitions_registry, definition_values, data_type_definition_class, definition_name, supported_definition_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 _ReadSequenceDataTypeDefinition( self, definitions_registry, definition_values, definition_name, is_member=False): """Reads a sequence data type definition. ...
if is_member: supported_definition_values = ( self._SUPPORTED_DEFINITION_VALUES_ELEMENTS_MEMBER_DATA_TYPE) else: supported_definition_values = ( self._SUPPORTED_DEFINITION_VALUES_ELEMENTS_DATA_TYPE) return self._ReadElementSequenceDataTypeDefinition( definitions_reg...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _ReadStorageDataTypeDefinition( self, definitions_registry, definition_values, data_type_definition_class, definition_name, supported_attributes, is_member=Fa...
if is_member: supported_definition_values = ( self._SUPPORTED_DEFINITION_VALUES_MEMBER_DATA_TYPE) else: supported_definition_values = ( self._SUPPORTED_DEFINITION_VALUES_STORAGE_DATA_TYPE) definition_object = self._ReadDataTypeDefinition( definitions_registry, defin...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _ReadStreamDataTypeDefinition( self, definitions_registry, definition_values, definition_name, is_member=False): """Reads a stream data type definition. Args...
if is_member: supported_definition_values = ( self._SUPPORTED_DEFINITION_VALUES_ELEMENTS_MEMBER_DATA_TYPE) else: supported_definition_values = ( self._SUPPORTED_DEFINITION_VALUES_ELEMENTS_DATA_TYPE) return self._ReadElementSequenceDataTypeDefinition( definitions_reg...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _ReadStringDataTypeDefinition( self, definitions_registry, definition_values, definition_name, is_member=False): """Reads a string data type definition. Args...
if is_member: supported_definition_values = ( self._SUPPORTED_DEFINITION_VALUES_STRING_MEMBER) else: supported_definition_values = self._SUPPORTED_DEFINITION_VALUES_STRING definition_object = self._ReadElementSequenceDataTypeDefinition( definitions_registry, definition_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 _ReadStructureDataTypeDefinition( self, definitions_registry, definition_values, definition_name, is_member=False): """Reads a structure data type definition...
if is_member: error_message = 'data type not supported as member' raise errors.DefinitionReaderError(definition_name, error_message) return self._ReadDataTypeDefinitionWithMembers( definitions_registry, definition_values, data_types.StructureDefinition, definition_name, supports_co...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _ReadStructureFamilyDataTypeDefinition( self, definitions_registry, definition_values, definition_name, is_member=False): """Reads a structure family data ty...
if is_member: error_message = 'data type not supported as member' raise errors.DefinitionReaderError(definition_name, error_message) definition_object = self._ReadLayoutDataTypeDefinition( definitions_registry, definition_values, data_types.StructureFamilyDefinition, definition_nam...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _ReadUnionDataTypeDefinition( self, definitions_registry, definition_values, definition_name, is_member=False): """Reads an union data type definition. Args:...
return self._ReadDataTypeDefinitionWithMembers( definitions_registry, definition_values, data_types.UnionDefinition, definition_name, supports_conditions=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 _ReadUUIDDataTypeDefinition( self, definitions_registry, definition_values, definition_name, is_member=False): """Reads an UUID data type definition. Args: d...
return self._ReadFixedSizeDataTypeDefinition( definitions_registry, definition_values, data_types.UUIDDefinition, definition_name, self._SUPPORTED_ATTRIBUTES_FIXED_SIZE_DATA_TYPE, default_size=16, is_member=is_member, supported_size_values=(16, ))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ReadFile(self, definitions_registry, path): """Reads data type definitions from a file into the registry. Args: definitions_registry (DataTypeDefinitionsRegi...
with open(path, 'r') as file_object: self.ReadFileObject(definitions_registry, file_object)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _GetFormatErrorLocation( self, yaml_definition, last_definition_object): """Retrieves a format error location. Args: yaml_definition (dict[str, object]): cu...
name = yaml_definition.get('name', None) if name: error_location = 'in: {0:s}'.format(name or '<NAMELESS>') elif last_definition_object: error_location = 'after: {0:s}'.format(last_definition_object.name) else: error_location = 'at start' return error_location
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ReadFileObject(self, definitions_registry, file_object): """Reads data type definitions from a file-like object into the registry. Args: definitions_registry...
last_definition_object = None error_location = None error_message = None try: yaml_generator = yaml.safe_load_all(file_object) for yaml_definition in yaml_generator: definition_object = self._ReadDefinition( definitions_registry, yaml_definition) if not definit...
<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['Organization'] """Reads the organization given by identifi...
organization = Organization(configuration=configuration) result = organization._load_from_hdx('organization', identifier) if result: return organization 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_users(self, capacity=None): # type: (Optional[str]) -> List[User] """Returns the organization's users. Args: capacity (Optional[str]): Filter by capacit...
users = list() usersdicts = self.data.get('users') if usersdicts is not None: for userdata in usersdicts: if capacity is not None and userdata['capacity'] != capacity: continue id = userdata.get('id') if id 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 get_datasets(self, query='*:*', **kwargs): # type: (str, Any) -> List[hdx.data.dataset.Dataset] """Get list of datasets in organization Args: query (str): R...
return hdx.data.dataset.Dataset.search_in_hdx(query=query, configuration=self.configuration, fq='organization:%s' % self.data['name'], **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_organization_names(configuration=None, **kwargs): # type: (Optional[Configuration], Any) -> List[str] """Get all organization names in HDX Args: conf...
organization = Organization(configuration=configuration) organization['id'] = 'all organizations' # only for error message if produced return organization._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 _read_from_hdx(self, object_type, value, fieldname='id', action=None, **kwargs): # type: (str, str, str, Optional[str], Any) -> Tuple[bool, Union[Dict, str]]...
if not fieldname: raise HDXError('Empty %s field name!' % object_type) if action is None: action = self.actions()['show'] data = {fieldname: value} data.update(kwargs) try: result = self.configuration.call_remoteckan(action, data) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _load_from_hdx(self, object_type, id_field): # type: (str, str) -> bool """Helper method to load the HDX object given by identifier from HDX Args: object_typ...
success, result = self._read_from_hdx(object_type, id_field) if success: self.old_data = self.data self.data = result return True logger.debug(result) 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 _check_load_existing_object(self, object_type, id_field_name, operation='update'): # type: (str, str, str) -> None """Check metadata exists and contains HDX ...
self._check_existing_object(object_type, id_field_name) if not self._load_from_hdx(object_type, self.data[id_field_name]): raise HDXError('No existing %s to %s!' % (object_type, operation))
<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, object_type, ignore_fields): # type: (str, List[str]) -> None """Helper method to check that metadata for HDX object is complete...
for field in self.configuration[object_type]['required_fields']: if field not in self.data and field not in ignore_fields: raise HDXError('Field %s is missing in %s!' % (field, object_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 _merge_hdx_update(self, object_type, id_field_name, file_to_upload=None, **kwargs): # type: (str, str, Optional[str], Any) -> None """Helper method to check ...
merge_two_dictionaries(self.data, self.old_data) if 'batch_mode' in kwargs: # Whether or not CKAN should change groupings of datasets on /datasets page self.data['batch_mode'] = kwargs['batch_mode'] if 'skip_validation' in kwargs: # Whether or not CKAN should perform validation st...
<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, object_type, id_field_name, file_to_upload=None, **kwargs): # type: (str, str, Optional[str], Any) -> None """Helper method to check if ...
self._check_load_existing_object(object_type, id_field_name) # We load an existing object even thought it may well have been loaded already # to prevent an admittedly unlikely race condition where someone has updated # the object in the intervening time self._merge_hdx_update(o...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _write_to_hdx(self, action, data, id_field_name, file_to_upload=None): # type: (str, Dict, str, Optional[str]) -> Dict """Creates or updates an HDX object in...
file = None try: if file_to_upload: file = open(file_to_upload, 'rb') files = [('upload', file)] else: files = None return self.configuration.call_remoteckan(self.actions()[action], data, files=files) except 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 _save_to_hdx(self, action, id_field_name, file_to_upload=None): # type: (str, str, Optional[str]) -> None """Creates or updates an HDX object in HDX, saving ...
result = self._write_to_hdx(action, self.data, id_field_name, file_to_upload) self.old_data = self.data self.data = result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _create_in_hdx(self, object_type, id_field_name, name_field_name, file_to_upload=None): # type: (str, str, str, Optional[str]) -> None """Helper method to ch...
self.check_required_fields() if id_field_name in self.data and self._load_from_hdx(object_type, self.data[id_field_name]): logger.warning('%s exists. Updating %s' % (object_type, self.data[id_field_name])) self._merge_hdx_update(object_type, id_field_name, file_to_upload) ...
<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_from_hdx(self, object_type, id_field_name): # type: (str, str) -> None """Helper method to deletes a resource from HDX Args: object_type (str): Desc...
if id_field_name not in self.data: raise HDXError('No %s field (mandatory) in %s!' % (id_field_name, object_type)) self._save_to_hdx('delete', id_field_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 _addupdate_hdxobject(self, hdxobjects, id_field, new_hdxobject): # type: (List[HDXObjectUpperBound], str, HDXObjectUpperBound) -> HDXObjectUpperBound """Help...
for hdxobject in hdxobjects: if hdxobject[id_field] == new_hdxobject[id_field]: merge_two_dictionaries(hdxobject, new_hdxobject) return hdxobject hdxobjects.append(new_hdxobject) return new_hdxobject
<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_hdxobject(self, objlist, obj, matchon='id', delete=False): # type: (List[Union[HDXObjectUpperBound,Dict]], Union[HDXObjectUpperBound,Dict,str], str, ...
if objlist is None: return False if isinstance(obj, six.string_types): obj_id = obj elif isinstance(obj, dict) or isinstance(obj, HDXObject): obj_id = obj.get(matchon) else: raise HDXError('Type of object not a string, dict or T<=HDXObject...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _convert_hdxobjects(self, hdxobjects): # type: (List[HDXObjectUpperBound]) -> List[HDXObjectUpperBound] """Helper function to convert supplied list of HDX ob...
newhdxobjects = list() for hdxobject in hdxobjects: newhdxobjects.append(hdxobject.data) return newhdxobjects
<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_hdxobjects(self, hdxobjects, hdxobjectclass, attribute_to_copy=None): # type: (List[HDXObjectUpperBound], type, Optional[str]) -> List[HDXObjectUpperBo...
newhdxobjects = list() for hdxobject in hdxobjects: newhdxobjectdata = copy.deepcopy(hdxobject.data) newhdxobject = hdxobjectclass(newhdxobjectdata, configuration=self.configuration) if attribute_to_copy: value = getattr(hdxobject, attribute_to_copy) ...
<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_hdxobjects(self, hdxobjects, hdxobjects_name, id_field, hdxobjectclass): # type: (List[HDXObjectUpperBound], str, str, type) -> None """Helper func...
new_hdxobjects = self.data.get(hdxobjects_name, list()) """:type : List[HDXObjectUpperBound]""" if new_hdxobjects: hdxobject_names = set() for hdxobject in hdxobjects: hdxobject_name = hdxobject[id_field] hdxobject_names.add(hdxobject_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_tags(self): # type: () -> List[str] """Return the dataset's list of tags Returns: List[str]: list of tags or [] if there are none """
tags = self.data.get('tags', None) if not tags: return list() return [x['name'] for x in 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 _add_tag(self, tag): # type: (str) -> bool """Add a tag Args: tag (str): Tag to add Returns: bool: True if tag added or False if tag already present """
tags = self.data.get('tags', None) if tags: if tag in [x['name'] for x in tags]: return False else: tags = list() tags.append({'name': tag}) self.data['tags'] = tags 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 _add_tags(self, tags): # type: (List[str]) -> bool """Add a list of tag Args: tags (List[str]): list of tags to add Returns: bool: True if all tags added or...
alltagsadded = True for tag in tags: if not self._add_tag(tag): alltagsadded = False return alltagsadded
<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_stringlist_from_commastring(self, field): # type: (str) -> List[str] """Return list of strings from comma separated list Args: field (str): Field conta...
strings = self.data.get(field) if strings: return strings.split(',') else: return 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 _add_string_to_commastring(self, field, string): # type: (str, str) -> bool """Add a string to a comma separated list of strings Args: field (str): Field co...
if string in self._get_stringlist_from_commastring(field): return False strings = '%s,%s' % (self.data.get(field, ''), string) if strings[0] == ',': strings = strings[1:] self.data[field] = strings 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 _add_strings_to_commastring(self, field, strings): # type: (str, List[str]) -> bool """Add a list of strings to a comma separated list of strings Args: field...
allstringsadded = True for string in strings: if not self._add_string_to_commastring(field, string): allstringsadded = False return allstringsadded
<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_string_from_commastring(self, field, string): # type: (str, str) -> bool """Remove a string from a comma separated list of strings Args: field (str):...
commastring = self.data.get(field, '') if string in commastring: self.data[field] = commastring.replace(string, '') return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_from_hdx(identifier, configuration=None): # type: (str, Optional[Configuration]) -> Optional['Resource'] """Reads the resource given by identifier from ...
if is_valid_uuid(identifier) is False: raise HDXError('%s is not a valid resource id!' % identifier) resource = Resource(configuration=configuration) result = resource._load_from_hdx('resource', identifier) if result: return resource 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 set_file_to_upload(self, file_to_upload): # type: (str) -> None """Delete any existing url and set the file uploaded to the local path provided Args: file_to...
if 'url' in self.data: del self.data['url'] self.file_to_upload = file_to_upload
<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_url_filetoupload(self): # type: () -> None """Check if url or file to upload provided for resource and add resource_type and url_type if not supplied R...
if self.file_to_upload is None: if 'url' in self.data: if 'resource_type' not in self.data: self.data['resource_type'] = 'api' if 'url_type' not in self.data: self.data['url_type'] = 'api' else: rais...
<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, **kwargs): # type: (Any) -> None """Check if resource exists in HDX and if so, update it Args: **kwargs: See below operation (string): O...
self._check_load_existing_object('resource', 'id') if self.file_to_upload and 'url' in self.data: del self.data['url'] self._merge_hdx_update('resource', 'id', self.file_to_upload, **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 create_in_hdx(self): # type: () -> None """Check if resource exists in HDX and if so, update it, otherwise create it Returns: None """
self.check_required_fields() id = self.data.get('id') if id and self._load_from_hdx('resource', id): logger.warning('%s exists. Updating %s' % ('resource', id)) if self.file_to_upload and 'url' in self.data: del self.data['url'] self._merge_hd...
<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(self): # type: () -> hdx.data.dataset.Dataset """Return dataset containing this resource Returns: hdx.data.dataset.Dataset: Dataset containing th...
package_id = self.data.get('package_id') if package_id is None: raise HDXError('Resource has no package id!') return hdx.data.dataset.Dataset.read_from_hdx(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 download(self, folder=None): # type: (Optional[str]) -> Tuple[str, str] """Download resource store to provided folder or temporary folder if no folder suppli...
# Download the resource url = self.data.get('url', None) if not url: raise HDXError('No URL to download!') logger.debug('Downloading %s' % url) filename = self.data['name'] format = '.%s' % self.data['format'] if format not in filename: fi...
<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_resource_ids_in_datastore(configuration=None): # type: (Optional[Configuration]) -> List[str] """Get list of resources that have a datastore returnin...
resource = Resource(configuration=configuration) success, result = resource._read_from_hdx('datastore', '_table_metadata', 'resource_id', Resource.actions()['datastore_search'], limit=10000) resource_ids = list() if not success: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def has_datastore(self): # type: () -> bool """Check if the resource has a datastore. Returns: bool: Whether the resource has a datastore or not """
success, result = self._read_from_hdx('datastore', self.data['id'], 'resource_id', self.actions()['datastore_search']) if not success: logger.debug(result) else: if result: return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete_datastore(self): # type: () -> None """Delete a resource from the HDX datastore Returns: None """
success, result = self._read_from_hdx('datastore', self.data['id'], 'resource_id', self.actions()['datastore_delete'], force=True) if not success: logger.debug(result)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_datastore(self, schema=None, primary_key=None, delete_first=0, path=None): # type: (Optional[List[Dict]], Optional[str], int, Optional[str]) -> None "...
if delete_first == 0: pass elif delete_first == 1: self.delete_datastore() elif delete_first == 2: if primary_key is None: self.delete_datastore() else: raise HDXError('delete_first must be 0, 1 or 2! (0 = No, 1 = Yes, 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 create_datastore_for_topline(self, delete_first=0, path=None): # type: (int, Optional[str]) -> None """For tabular data, create a resource in the HDX datasto...
data = load_yaml(script_dir_plus_file(join('..', 'hdx_datasource_topline.yml'), Resource)) self.create_datastore_from_dict_schema(data, delete_first, path=path)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_datastore(self, schema=None, primary_key=None, path=None): # type: (Optional[List[Dict]], Optional[str], Optional[str]) -> None """For tabular data, u...
self.create_datastore(schema, primary_key, 2, path=path)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_update_resource_views(self, resource_views): # type: (List[Union[ResourceView,Dict]]) -> None """Add new or update existing resource views in resource wi...
if not isinstance(resource_views, list): raise HDXError('ResourceViews should be a list!') for resource_view in resource_views: self.add_update_resource_view(resource_view)
<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_resource_views(self, resource_views): # type: (List[Union[ResourceView,Dict,str]]) -> None """Order resource views in resource. Args: resource_views ...
if not isinstance(resource_views, list): raise HDXError('ResourceViews should be a list!') ids = list() for resource_view in resource_views: if isinstance(resource_view, str): resource_view_id = resource_view else: resource_vie...
<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_view(self, resource_view): # type: (Union[ResourceView,Dict,str]) -> None """Delete a resource view from the resource and HDX Args: resource_...
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({'id': resource_view}, configuration=self.configuration) else: resource_vie...
<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_for_simple_stems(output, skip_empty=False, skip_same_stems=True): """ Parses the output stem lines to produce a list with possible stems for each word ...
lines_with_stems = _get_lines_with_stems(output) stems = list() last_word = None for line in lines_with_stems: word, stem, _ = line.split("\t") stem = stem if stem != '-' else None if skip_empty and (stem is None): continue if last_word != word: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _CreateClassTemplate(cls, data_type_definition): """Creates the class template. Args: data_type_definition (DataTypeDefinition): data type definition. Retur...
type_name = data_type_definition.name type_description = data_type_definition.description or type_name while type_description.endswith('.'): type_description = type_description[:-1] class_attributes_description = [] init_arguments = [] instance_attributes = [] for member_definition...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _IsIdentifier(cls, string): """Checks if a string contains an identifier. Args: string (str): string to check. Returns: bool: True if the string contains an...
return ( string and not string[0].isdigit() and all(character.isalnum() or character == '_' for character in 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 _ValidateDataTypeDefinition(cls, data_type_definition): """Validates the data type definition. Args: data_type_definition (DataTypeDefinition): data type de...
if not cls._IsIdentifier(data_type_definition.name): raise ValueError( 'Data type definition name: {0!s} not a valid identifier'.format( data_type_definition.name)) if keyword.iskeyword(data_type_definition.name): raise ValueError( 'Data type definition name: {0!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 CreateClass(cls, data_type_definition): """Creates a new structure values class. Args: data_type_definition (DataTypeDefinition): data type definition. Retu...
cls._ValidateDataTypeDefinition(data_type_definition) class_definition = cls._CreateClassTemplate(data_type_definition) namespace = { '__builtins__' : { 'object': builtins.object, 'super': builtins.super}, '__name__': '{0:s}'.format(data_type_definition.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 DeregisterDefinition(self, data_type_definition): """Deregisters a data type definition. The data type definitions are identified based on their lower case n...
name = data_type_definition.name.lower() if name not in self._definitions: raise KeyError('Definition not set for name: {0:s}.'.format( data_type_definition.name)) del self._definitions[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 GetDefinitionByName(self, name): """Retrieves a specific data type definition by name. Args: name (str): name of the data type definition. Returns: DataType...
lookup_name = name.lower() if lookup_name not in self._definitions: lookup_name = self._aliases.get(name, None) return self._definitions.get(lookup_name, None)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def RegisterDefinition(self, data_type_definition): """Registers a data type definition. The data type definitions are identified based on their lower case name....
name_lower = data_type_definition.name.lower() if name_lower in self._definitions: raise KeyError('Definition already set for name: {0:s}.'.format( data_type_definition.name)) if data_type_definition.name in self._aliases: raise KeyError('Alias already set for name: {0:s}.'.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 apply_on_csv_string(rules_str, func): """ Splits a given string by comma, trims whitespace on the resulting strings and applies a given ```func``` to each it...
splitted = rules_str.split(",") for str in splitted: func(str.strip())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def placeFavicon(context): """ Gets Favicon-URL for the Model. Template Syntax: {% placeFavicon %} """
fav = Favicon.objects.filter(isFavicon=True).first() if not fav: return mark_safe('<!-- no favicon -->') html = '' for rel in config: for size in sorted(config[rel], reverse=True): n = fav.get_favicon(size=size, rel=rel) html += '<link rel="%s" sizes="%sx%s" href...
<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_default_theme(theme): """ Set default theme name based in config file. """
pref_init() # make sure config files exist parser = cp.ConfigParser() parser.read(PREFS_FILE) # Do we need to create a section? if not parser.has_section("theme"): parser.add_section("theme") parser.set("theme", "default", theme) # best way to make sure no file truncation? with...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pick_theme(manual): """ Return theme name based on manual input, prefs file, or default to "plain". """
if manual: return manual pref_init() parser = cp.ConfigParser() parser.read(PREFS_FILE) try: theme = parser.get("theme", "default") except (cp.NoSectionError, cp.NoOptionError): theme = "plain" return 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 install_theme(path_to_theme): """ Pass a path to a theme file which will be extracted to the themes directory. """
pref_init() # cp the file filename = basename(path_to_theme) dest = join(THEMES_DIR, filename) copy(path_to_theme, dest) # unzip zf = zipfile.ZipFile(dest) # should make sure zipfile contains only themename folder which doesn't conflict # with existing themename. Or some kind of san...