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 _disable(self): """ The configuration containing this function has been disabled by host. Endpoint do not work anymore, so cancel AIO operation blocks. """
if self._enabled: self._real_onCannotSend() has_cancelled = 0 for block in self._aio_recv_block_list + self._aio_send_block_list: try: self._aio_context.cancel(block) except OSError as exc: trace( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def onAIOCompletion(self): """ Call when eventfd notified events are available. """
event_count = self.eventfd.read() trace('eventfd reports %i events' % event_count) # Even though eventfd signaled activity, even though it may give us # some number of pending events, some events seem to have been already # processed (maybe during io_cancel call ?). # So...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _iter_errors_custom(instance, checks, options): """Perform additional validation not possible merely with JSON schemas. Args: instance: The STIX object to be...
# Perform validation for v_function in checks: try: result = v_function(instance) except TypeError: result = v_function(instance, options) if isinstance(result, Iterable): for x in result: yield x elif result is not None: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_json_files(directory, recursive=False): """Return a list of file paths for JSON files within `directory`. Args: directory: A path to a directory. recurs...
json_files = [] for top, dirs, files in os.walk(directory): dirs.sort() # Get paths to each file in `files` paths = (os.path.join(top, f) for f in sorted(files)) # Add all the .json files to our return collection json_files.extend(x for x in paths if is_json(x)) ...
<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_json_files(files, recursive=False): """Return a list of files to validate from `files`. If a member of `files` is a directory, its children with a ``.jso...
json_files = [] if not files: return json_files for fn in files: if os.path.isdir(fn): children = list_json_files(fn, recursive) json_files.extend(children) elif is_json(fn): json_files.append(fn) else: continue if not j...
<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_validation(options): """Validate files based on command line options. Args: options: An instance of ``ValidationOptions`` containing options for this val...
if options.files == sys.stdin: results = validate(options.files, options) return [FileValidationResults(is_valid=results.is_valid, filepath='stdin', object_results=results)] files = get_json_files(options.files, option...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_parsed_json(obj_json, options=None): """ Validate objects from parsed JSON. This supports a single object, or a list of objects. If a single object ...
validating_list = isinstance(obj_json, list) if not options: options = ValidationOptions() if not options.no_cache: init_requests_cache(options.refresh_cache) results = None if validating_list: results = [] for obj in obj_json: try: re...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate(in_, options=None): """ Validate objects from JSON data in a textual stream. :param in_: A textual stream of JSON data. :param options: Validation o...
obj_json = json.load(in_) results = validate_parsed_json(obj_json, options) return results
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_file(fn, options=None): """Validate the input document `fn` according to the options passed in. If any exceptions are raised during validation, no f...
file_results = FileValidationResults(filepath=fn) output.info("Performing JSON schema validation on %s" % fn) if not options: options = ValidationOptions(files=fn) try: with open(fn) as instance_file: file_results.object_results = validate(instance_file, options) exce...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_string(string, options=None): """Validate the input `string` according to the options passed in. If any exceptions are raised during validation, no ...
output.info("Performing JSON schema validation on input string: " + string) stream = io.StringIO(string) return validate(stream, options)
<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_validator(schema_path, schema): """Create a JSON schema validator for the given schema. Args: schema_path: The filename of the JSON schema. schema: A Py...
# Get correct prefix based on OS if os.name == 'nt': file_prefix = 'file:///' else: file_prefix = 'file:' resolver = RefResolver(file_prefix + schema_path.replace("\\", "/"), schema) validator = Draft4Validator(schema, resolver=resolver) return validator
<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_schema(schema_dir, obj_type): """Search the `schema_dir` directory for a schema called `obj_type`.json. Return the file path of the first match it finds...
schema_filename = obj_type + '.json' for root, dirnames, filenames in os.walk(schema_dir): if schema_filename in filenames: return os.path.join(root, schema_filename)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_schema(schema_path): """Load the JSON schema at the given path as a Python object. Args: schema_path: A filename for a JSON schema. Returns: A Python ob...
try: with open(schema_path) as schema_file: schema = json.load(schema_file) except ValueError as e: raise SchemaInvalidError('Invalid JSON in schema or included schema: ' '%s\n%s' % (schema_file.name, str(e))) return schema
<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_error_generator(type, obj, schema_dir=None, version=DEFAULT_VER, default='core'): """Get a generator for validating against the schema for the given obj...
# If no schema directory given, use default for the given STIX version, # which comes bundled with this package if schema_dir is None: schema_dir = os.path.abspath(os.path.dirname(__file__) + '/schemas-' + version + '/') try: schema_path = find_sche...
<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_musts(options): """Return the list of 'MUST' validators for the correct version of STIX. Args: options: ValidationOptions instance with validation optio...
if options.version == '2.0': return musts20.list_musts(options) else: return musts21.list_musts(options)
<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_shoulds(options): """Return the list of 'SHOULD' validators for the correct version of STIX. Args: options: ValidationOptions instance with validation o...
if options.version == '2.0': return shoulds20.list_shoulds(options) else: return shoulds21.list_shoulds(options)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _schema_validate(sdo, options): """Set up validation of a single STIX object against its type's schema. This does no actual validation; it just returns gener...
error_gens = [] if 'id' in sdo: try: error_prefix = sdo['id'] + ": " except TypeError: error_prefix = 'unidentifiable object: ' else: error_prefix = '' # Get validator for built-in schema base_sdo_errors = _get_error_generator(sdo['type'], sdo, vers...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_instance(instance, options=None): """Perform STIX JSON Schema validation against STIX input. Find the correct schema by looking at the 'type' proper...
if 'type' not in instance: raise ValidationError("Input must be an object with a 'type' property.") if not options: options = ValidationOptions() error_gens = [] # Schema validation if instance['type'] == 'bundle' and 'objects' in instance: # Validate each object in a bun...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def custom_prefix_strict(instance): """Ensure custom content follows strict naming style conventions. """
for error in chain(custom_object_prefix_strict(instance), custom_property_prefix_strict(instance), custom_observable_object_prefix_strict(instance), custom_object_extension_prefix_strict(instance), custom_observable_propert...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def custom_prefix_lax(instance): """Ensure custom content follows lenient naming style conventions for forward-compatibility. """
for error in chain(custom_object_prefix_lax(instance), custom_property_prefix_lax(instance), custom_observable_object_prefix_lax(instance), custom_object_extension_prefix_lax(instance), custom_observable_properties_prefix_l...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def custom_object_prefix_strict(instance): """Ensure custom objects follow strict naming style conventions. """
if (instance['type'] not in enums.TYPES and instance['type'] not in enums.RESERVED_OBJECTS and not CUSTOM_TYPE_PREFIX_RE.match(instance['type'])): yield JSONError("Custom object type '%s' should start with 'x-' " "followed by a source unique identifier (like ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def custom_object_prefix_lax(instance): """Ensure custom objects follow lenient naming style conventions for forward-compatibility. """
if (instance['type'] not in enums.TYPES and instance['type'] not in enums.RESERVED_OBJECTS and not CUSTOM_TYPE_LAX_PREFIX_RE.match(instance['type'])): yield JSONError("Custom object type '%s' should start with 'x-' in " "order to be compatible with future ver...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def custom_property_prefix_strict(instance): """Ensure custom properties follow strict naming style conventions. Does not check property names in custom objects....
for prop_name in instance.keys(): if (instance['type'] in enums.PROPERTIES and prop_name not in enums.PROPERTIES[instance['type']] and prop_name not in enums.RESERVED_PROPERTIES and not CUSTOM_PROPERTY_PREFIX_RE.match(prop_name)): yield JSONError...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def custom_property_prefix_lax(instance): """Ensure custom properties follow lenient naming style conventions for forward-compatibility. Does not check property ...
for prop_name in instance.keys(): if (instance['type'] in enums.PROPERTIES and prop_name not in enums.PROPERTIES[instance['type']] and prop_name not in enums.RESERVED_PROPERTIES and not CUSTOM_PROPERTY_LAX_PREFIX_RE.match(prop_name)): yield JSONE...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def open_vocab_values(instance): """Ensure that the values of all properties which use open vocabularies are in lowercase and use hyphens instead of spaces or un...
if instance['type'] not in enums.VOCAB_PROPERTIES: return properties = enums.VOCAB_PROPERTIES[instance['type']] for prop in properties: if prop in instance: if type(instance[prop]) is list: values = instance[prop] else: values = [ins...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def kill_chain_phase_names(instance): """Ensure the `kill_chain_name` and `phase_name` properties of `kill_chain_phase` objects follow naming style conventions. ...
if instance['type'] in enums.KILL_CHAIN_PHASE_USES and 'kill_chain_phases' in instance: for phase in instance['kill_chain_phases']: if 'kill_chain_name' not in phase: # Since this field is required, schemas will already catch the error return chain_...
<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_vocab(instance, vocab, code): """Ensure that the open vocabulary specified by `vocab` is used properly. This checks properties of objects specified in ...
vocab_uses = getattr(enums, vocab + "_USES") for k in vocab_uses.keys(): if instance['type'] == k: for prop in vocab_uses[k]: if prop not in instance: continue vocab_ov = getattr(enums, vocab + "_OV") if type(instance[prop...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def vocab_marking_definition(instance): """Ensure that the `definition_type` property of `marking-definition` objects is one of the values in the STIX 2.0 specif...
if (instance['type'] == 'marking-definition' and 'definition_type' in instance and not instance['definition_type'] in enums.MARKING_DEFINITION_TYPES): return JSONError("Marking definition `definition_type` should be one " "of: %s." % ', '.join(enums.MARKING...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def relationships_strict(instance): """Ensure that only the relationship types defined in the specification are used. """
# Don't check objects that aren't relationships or that are custom objects if (instance['type'] != 'relationship' or instance['type'] not in enums.TYPES): return if ('relationship_type' not in instance or 'source_ref' not in instance or 'target_ref' not in instance): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def valid_hash_value(hashname): """Return true if given value is a valid, recommended hash name according to the STIX 2 specification. """
custom_hash_prefix_re = re.compile(r"^x_") if hashname in enums.HASH_ALGO_OV or custom_hash_prefix_re.match(hashname): return True else: 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 vocab_windows_pebinary_type(instance): """Ensure file objects with the windows-pebinary-ext extension have a 'pe-type' property that is from the windows-pebi...
for key, obj in instance['objects'].items(): if 'type' in obj and obj['type'] == 'file': try: pe_type = obj['extensions']['windows-pebinary-ext']['pe_type'] except KeyError: continue if pe_type not in enums.WINDOWS_PEBINARY_TYPE_OV: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def vocab_account_type(instance): """Ensure a user-account objects' 'account-type' property is from the account-type-ov vocabulary. """
for key, obj in instance['objects'].items(): if 'type' in obj and obj['type'] == 'user-account': try: acct_type = obj['account_type'] except KeyError: continue if acct_type not in enums.ACCOUNT_TYPE_OV: yield JSONError("Obj...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def observable_object_keys(instance): """Ensure observable-objects keys are non-negative integers. """
digits_re = re.compile(r"^\d+$") for key in instance['objects']: if not digits_re.match(key): yield JSONError("'%s' is not a good key value. Observable Objects " "should use non-negative integers for their keys." % key, instance['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 custom_observable_object_prefix_strict(instance): """Ensure custom observable objects follow strict naming style conventions. """
for key, obj in instance['objects'].items(): if ('type' in obj and obj['type'] not in enums.OBSERVABLE_TYPES and obj['type'] not in enums.OBSERVABLE_RESERVED_OBJECTS and not CUSTOM_TYPE_PREFIX_RE.match(obj['type'])): yield JSONError("Custom Observable 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 custom_observable_object_prefix_lax(instance): """Ensure custom observable objects follow naming style conventions. """
for key, obj in instance['objects'].items(): if ('type' in obj and obj['type'] not in enums.OBSERVABLE_TYPES and obj['type'] not in enums.OBSERVABLE_RESERVED_OBJECTS and not CUSTOM_TYPE_LAX_PREFIX_RE.match(obj['type'])): yield JSONError("Custom Observable 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 custom_object_extension_prefix_strict(instance): """Ensure custom observable object extensions follow strict naming style conventions. """
for key, obj in instance['objects'].items(): if not ('extensions' in obj and 'type' in obj and obj['type'] in enums.OBSERVABLE_EXTENSIONS): continue for ext_key in obj['extensions']: if (ext_key not in enums.OBSERVABLE_EXTENSIONS[obj['type']] and ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def custom_object_extension_prefix_lax(instance): """Ensure custom observable object extensions follow naming style conventions. """
for key, obj in instance['objects'].items(): if not ('extensions' in obj and 'type' in obj and obj['type'] in enums.OBSERVABLE_EXTENSIONS): continue for ext_key in obj['extensions']: if (ext_key not in enums.OBSERVABLE_EXTENSIONS[obj['type']] and ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def network_traffic_ports(instance): """Ensure network-traffic objects contain both src_port and dst_port. """
for key, obj in instance['objects'].items(): if ('type' in obj and obj['type'] == 'network-traffic' and ('src_port' not in obj or 'dst_port' not in obj)): yield JSONError("The Network Traffic object '%s' should contain " "both the 'src_port' and 'dst_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mime_type(instance): """Ensure the 'mime_type' property of file objects comes from the Template column in the IANA media type registry. """
mime_pattern = re.compile(r'^(application|audio|font|image|message|model' '|multipart|text|video)/[a-zA-Z0-9.+_-]+') for key, obj in instance['objects'].items(): if ('type' in obj and obj['type'] == 'file' and 'mime_type' in obj): if enums.media_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 protocols(instance): """Ensure the 'protocols' property of network-traffic objects contains only values from the IANA Service Name and Transport Protocol Por...
for key, obj in instance['objects'].items(): if ('type' in obj and obj['type'] == 'network-traffic' and 'protocols' in obj): for prot in obj['protocols']: if enums.protocols(): if prot not in enums.protocols(): yield JS...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pdf_doc_info(instance): """Ensure the keys of the 'document_info_dict' property of the pdf-ext extension of file objects are only valid PDF Document Informat...
for key, obj in instance['objects'].items(): if ('type' in obj and obj['type'] == 'file'): try: did = obj['extensions']['pdf-ext']['document_info_dict'] except KeyError: continue for elem in did: if elem not in enums.PDF_D...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def countries(instance): """Ensure that the `country` property of `location` objects is a valid ISO 3166-1 ALPHA-2 Code. """
if (instance['type'] == 'location' and 'country' in instance and not instance['country'].upper() in enums.COUNTRY_CODES): return JSONError("Location `country` should be a valid ISO 3166-1 " "ALPHA-2 Code.", instance['id'], 'marking-definition-t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def windows_process_priority_format(instance): """Ensure the 'priority' property of windows-process-ext ends in '_CLASS'. """
class_suffix_re = re.compile(r'.+_CLASS$') for key, obj in instance['objects'].items(): if 'type' in obj and obj['type'] == 'process': try: priority = obj['extensions']['windows-process-ext']['priority'] except KeyError: continue if no...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def duplicate_ids(instance): """Ensure objects with duplicate IDs have different `modified` timestamps. """
if instance['type'] != 'bundle' or 'objects' not in instance: return unique_ids = {} for obj in instance['objects']: if 'id' not in obj or 'modified' not in obj: continue elif obj['id'] not in unique_ids: unique_ids[obj['id']] = obj['modified'] elif ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def timestamp(instance): """Ensure timestamps contain sane months, days, hours, minutes, seconds. """
ts_re = re.compile(r"^[0-9]{4}-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])T([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9]|60)(\.[0-9]+)?Z$") timestamp_props = ['created', 'modified'] if instance['type'] in enums.TIMESTAMP_PROPERTIES: timestamp_props += enums.TIMESTAMP_PROPERTIES[instance['type']] fo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def modified_created(instance): """`modified` property must be later or equal to `created` property """
if 'modified' in instance and 'created' in instance and \ instance['modified'] < instance['created']: msg = "'modified' (%s) must be later or equal to 'created' (%s)" return JSONError(msg % (instance['modified'], instance['created']), instance['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 marking_selector_syntax(instance): """Ensure selectors in granular markings refer to items which are actually present in the object. """
if 'granular_markings' not in instance: return list_index_re = re.compile(r"\[(\d+)\]") for marking in instance['granular_markings']: if 'selectors' not in marking: continue selectors = marking['selectors'] for selector in selectors: segments = sele...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def observable_object_references(instance): """Ensure certain observable object properties reference the correct type of object. """
for key, obj in instance['objects'].items(): if 'type' not in obj: continue elif obj['type'] not in enums.OBSERVABLE_PROP_REFS: continue obj_type = obj['type'] for obj_prop in enums.OBSERVABLE_PROP_REFS[obj_type]: if obj_prop not in obj: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def artifact_mime_type(instance): """Ensure the 'mime_type' property of artifact objects comes from the Template column in the IANA media type registry. """
for key, obj in instance['objects'].items(): if ('type' in obj and obj['type'] == 'artifact' and 'mime_type' in obj): if enums.media_types(): if obj['mime_type'] not in enums.media_types(): yield JSONError("The 'mime_type' property of object '%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 character_set(instance): """Ensure certain properties of cyber observable objects come from the IANA Character Set list. """
char_re = re.compile(r'^[a-zA-Z0-9_\(\)-]+$') for key, obj in instance['objects'].items(): if ('type' in obj and obj['type'] == 'directory' and 'path_enc' in obj): if enums.char_sets(): if obj['path_enc'] not in enums.char_sets(): yield JSONError("The '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 software_language(instance): """Ensure the 'language' property of software objects is a valid ISO 639-2 language code. """
for key, obj in instance['objects'].items(): if ('type' in obj and obj['type'] == 'software' and 'languages' in obj): for lang in obj['languages']: if lang not in enums.SOFTWARE_LANG_CODES: yield JSONError("The 'languages' property of 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 types_strict(instance): """Ensure that no custom object types are used, but only the official ones from the specification. """
if instance['type'] not in enums.TYPES: yield JSONError("Object type '%s' is not one of those defined in the" " specification." % instance['type'], instance['id']) if has_cyber_observable_data(instance): for key, obj in instance['objects'].items(): if '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 properties_strict(instance): """Ensure that no custom properties are used, but only the official ones from the specification. """
if instance['type'] not in enums.TYPES: return # only check properties for official objects defined_props = enums.PROPERTIES.get(instance['type'], []) for prop in instance.keys(): if prop not in defined_props: yield JSONError("Property '%s' is not one of those defined in the" ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def char_sets(): """Return a list of the IANA Character Sets, or an empty list if the IANA website is unreachable. Store it as a function attribute so that we on...
if not hasattr(char_sets, 'setlist'): clist = [] try: data = requests.get('http://www.iana.org/assignments/character-' 'sets/character-sets-1.csv') except requests.exceptions.RequestException: return [] for line in data.iter_l...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def protocols(): """Return a list of values from the IANA Service Name and Transport Protocol Port Number Registry, or an empty list if the IANA website is unrea...
if not hasattr(protocols, 'protlist'): plist = [] try: data = requests.get('http://www.iana.org/assignments/service-names' '-port-numbers/service-names-port-numbers.csv') except requests.exceptions.RequestException: return [] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def print_level(log_function, fmt, level, *args): """Print a formatted message to stdout prepended by spaces. Useful for printing hierarchical information, like ...
if _SILENT: return msg = fmt % args spaces = ' ' * level log_function("%s%s" % (spaces, msg))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def print_fatal_results(results, level=0): """Print fatal errors that occurred during validation runs. """
print_level(logger.critical, _RED + "[X] Fatal Error: %s", level, results.error)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def print_schema_results(results, level=0): """Print JSON Schema validation errors to stdout. Args: results: An instance of ObjectValidationResults. level: The l...
for error in results.errors: print_level(logger.error, _RED + "[X] %s", level, error)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def print_warning_results(results, level=0): """Print warning messages found during validation. """
marker = _YELLOW + "[!] " for warning in results.warnings: print_level(logger.warning, marker + "Warning: %s", level, warning)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def print_results_header(identifier, is_valid): """Print a header for the results of either a file or an object. """
print_horizontal_rule() print_level(logger.info, "[-] Results for: %s", 0, identifier) if is_valid: marker = _GREEN + "[+]" verdict = "Valid" log_func = logger.info else: marker = _RED + "[X]" verdict = "Invalid" log_func = logger.error print_level(l...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def print_object_results(obj_result): """Print the results of validating an object. Args: obj_result: An ObjectValidationResults instance. """
print_results_header(obj_result.object_id, obj_result.is_valid) if obj_result.warnings: print_warning_results(obj_result, 1) if obj_result.errors: print_schema_results(obj_result, 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 print_file_results(file_result): """Print the results of validating a file. Args: file_result: A FileValidationResults instance. """
print_results_header(file_result.filepath, file_result.is_valid) for object_result in file_result.object_results: if object_result.warnings: print_warning_results(object_result, 1) if object_result.errors: print_schema_results(object_result, 1) if file_result.fatal...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def vocab_encryption_algo(instance): """Ensure file objects' 'encryption_algorithm' property is from the encryption-algo-ov vocabulary. """
for key, obj in instance['objects'].items(): if 'type' in obj and obj['type'] == 'file': try: enc_algo = obj['encryption_algorithm'] except KeyError: continue if enc_algo not in enums.ENCRYPTION_ALGO_OV: yield JSONError("Ob...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def enforce_relationship_refs(instance): """Ensures that all SDOs being referenced by the SRO are contained within the same bundle"""
if instance['type'] != 'bundle' or 'objects' not in instance: return rel_references = set() """Find and store all ids""" for obj in instance['objects']: if obj['type'] != 'relationship': rel_references.add(obj['id']) """Check if id has been encountered""" for obj ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def timestamp_compare(instance): """Ensure timestamp properties with a comparison requirement are valid. E.g. `modified` must be later or equal to `created`. """
compares = [('modified', 'ge', 'created')] additional_compares = enums.TIMESTAMP_COMPARE.get(instance.get('type', ''), []) compares.extend(additional_compares) for first, op, second in compares: comp = getattr(operator, op) comp_str = get_comparison_string(op) if first in inst...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def observable_timestamp_compare(instance): """Ensure cyber observable timestamp properties with a comparison requirement are valid. """
for key, obj in instance['objects'].items(): compares = enums.TIMESTAMP_COMPARE_OBSERVABLE.get(obj.get('type', ''), []) print(compares) for first, op, second in compares: comp = getattr(operator, op) comp_str = get_comparison_string(op) if first in obj 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 language_contents(instance): """Ensure keys in Language Content's 'contents' dictionary are valid language codes, and that the keys in the sub-dictionaries m...
if instance['type'] != 'language-content' or 'contents' not in instance: return for key, value in instance['contents'].items(): if key not in enums.LANG_CODES: yield JSONError("Invalid key '%s' in 'contents' property must be" " an RFC 5646 code" % key, 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 cyber_observable_check(original_function): """Decorator for functions that require cyber observable data. """
def new_function(*args, **kwargs): if not has_cyber_observable_data(args[0]): return func = original_function(*args, **kwargs) if isinstance(func, Iterable): for x in original_function(*args, **kwargs): yield x new_function.__name__ = original_fun...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init_requests_cache(refresh_cache=False): """ Initializes a cache which the ``requests`` library will consult for responses, before making network requests. ...
# Cache data from external sources; used in some checks dirs = AppDirs("stix2-validator", "OASIS") # Create cache dir if doesn't exist try: os.makedirs(dirs.user_cache_dir) except OSError as e: if e.errno != errno.EEXIST: raise requests_cache.install_cache( c...
<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, parser): '''parse content of extension''' # line number of token that started the tag lineno = next(parser.stream).lineno # template context context = nodes.ContextReference() # parse keyword arguments kwargs = [] while parser.stream.loo...
<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_cache_key(content, **kwargs): '''generate cache key''' cache_key = '' for key in sorted(kwargs.keys()): cache_key = '{cache_key}.{key}:{value}'.format( cache_key=cache_key, key=key, value=kwargs[key], ) cache_key = '{content}{cache_key}'.forma...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def check_active(url, element, **kwargs): '''check "active" url, apply css_class''' menu = yesno_to_bool(kwargs['menu'], 'menu') ignore_params = yesno_to_bool(kwargs['ignore_params'], 'ignore_params') # check missing href parameter if not url.attrib.get('href', None) is None: # get href att...
<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_content(content, **kwargs): '''check content for "active" urls''' # valid html root tag try: # render elements tree from content tree = fragment_fromstring(content) # flag for prevent content rerendering, when no "active" urls found processed = False # djang...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def render_content(content, **kwargs): '''check content for "active" urls, store results to django cache''' # try to take pre rendered content from django cache, if caching is enabled if settings.ACTIVE_URL_CACHE: cache_key = get_cache_key(content, **kwargs) # get cached content from django...
<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_configuration(self, **kwargs): '''load configuration, merge with default settings''' # update passed arguments with default values for key in settings.ACTIVE_URL_KWARGS: kwargs.setdefault(key, settings.ACTIVE_URL_KWARGS[key]) # "active" html tag css class 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 _parse_response(response, clazz, is_list=False, resource_name=None): """Parse a Marathon response into an object or list of objects."""
target = response.json()[ resource_name] if resource_name else response.json() if is_list: return [clazz.from_json(resource) for resource in target] else: return clazz.from_json(target)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _do_request(self, method, path, params=None, data=None): """Query Marathon server."""
headers = { 'Content-Type': 'application/json', 'Accept': 'application/json'} if self.auth_token: headers['Authorization'] = "token={}".format(self.auth_token) response = None servers = list(self.servers) while servers and response 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 _do_sse_request(self, path, params=None): """Query Marathon server for events."""
urls = [''.join([server.rstrip('/'), path]) for server in self.servers] while urls: url = urls.pop() try: # Requests does not set the original Authorization header on cross origin # redirects. If set allow_redirects=True we may get a 401 response....
<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_app(self, app_id, app, minimal=True): """Create and start an app. :param str app_id: application ID :param :class:`marathon.models.app.MarathonApp` ap...
app.id = app_id data = app.to_json(minimal=minimal) response = self._do_request('POST', '/v2/apps', data=data) if response.status_code == 201: return self._parse_response(response, MarathonApp) else: 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 list_apps(self, cmd=None, embed_tasks=False, embed_counts=False, embed_deployments=False, embed_readiness=False, embed_last_task_failure=False, embed_failures...
params = {} if cmd: params['cmd'] = cmd if app_id: params['id'] = app_id if label: params['label'] = label embed_params = { 'app.tasks': embed_tasks, 'app.counts': embed_counts, 'app.deployments': embed_dep...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_app(self, app_id, embed_tasks=False, embed_counts=False, embed_deployments=False, embed_readiness=False, embed_last_task_failure=False, embed_failures=Fal...
params = {} embed_params = { 'app.tasks': embed_tasks, 'app.counts': embed_counts, 'app.deployments': embed_deployments, 'app.readiness': embed_readiness, 'app.lastTaskFailure': embed_last_task_failure, 'app.failures': embed_failur...
<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_app(self, app_id, app, force=False, minimal=True): """Update an app. Applies writable settings in `app` to `app_id` Note: this method can not be used ...
# Changes won't take if version is set - blank it for convenience app.version = None params = {'force': force} data = app.to_json(minimal=minimal) response = self._do_request( 'PUT', '/v2/apps/{app_id}'.format(app_id=app_id), params=params, data=data) retur...
<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_apps(self, apps, force=False, minimal=True): """Update multiple apps. Applies writable settings in elements of apps either by upgrading existing ones ...
json_repr_apps = [] for app in apps: # Changes won't take if version is set - blank it for convenience app.version = None json_repr_apps.append(app.json_repr(minimal=minimal)) params = {'force': force} encoder = MarathonMinimalJsonEncoder if minimal ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rollback_app(self, app_id, version, force=False): """Roll an app back to a previous version. :param str app_id: application ID :param str version: applicatio...
params = {'force': force} data = json.dumps({'version': version}) response = self._do_request( 'PUT', '/v2/apps/{app_id}'.format(app_id=app_id), params=params, data=data) return response.json()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete_app(self, app_id, force=False): """Stop and destroy an app. :param str app_id: application ID :param bool force: apply even if a deployment is in prog...
params = {'force': force} response = self._do_request( 'DELETE', '/v2/apps/{app_id}'.format(app_id=app_id), params=params) return response.json()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def scale_app(self, app_id, instances=None, delta=None, force=False): """Scale an app. Scale an app to a target number of instances (with `instances`), or scale ...
if instances is None and delta is None: marathon.log.error('instances or delta must be passed') return try: app = self.get_app(app_id) except NotFoundError: marathon.log.error('App "{app}" not found'.format(app=app_id)) return ...
<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_group(self, group): """Create and start a group. :param :class:`marathon.models.group.MarathonGroup` group: the group to create :returns: success :rty...
data = group.to_json() response = self._do_request('POST', '/v2/groups', data=data) return response.json()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_group(self, group_id): """Get a single group. :param str group_id: group ID :returns: group :rtype: :class:`marathon.models.group.MarathonGroup` """
response = self._do_request( 'GET', '/v2/groups/{group_id}'.format(group_id=group_id)) return self._parse_response(response, MarathonGroup)
<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_group(self, group_id, group, force=False, minimal=True): """Update a group. Applies writable settings in `group` to `group_id` Note: this method can n...
# Changes won't take if version is set - blank it for convenience group.version = None params = {'force': force} data = group.to_json(minimal=minimal) response = self._do_request( 'PUT', '/v2/groups/{group_id}'.format(group_id=group_id), data=data, params=params) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rollback_group(self, group_id, version, force=False): """Roll a group back to a previous version. :param str group_id: group ID :param str version: group ver...
params = {'force': force} response = self._do_request( 'PUT', '/v2/groups/{group_id}/versions/{version}'.format( group_id=group_id, version=version), params=params) return response.json()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete_group(self, group_id, force=False): """Stop and destroy a group. :param str group_id: group ID :param bool force: apply even if a deployment is in pro...
params = {'force': force} response = self._do_request( 'DELETE', '/v2/groups/{group_id}'.format(group_id=group_id), params=params) return response.json()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def scale_group(self, group_id, scale_by): """Scale a group by a factor. :param str group_id: group ID :param int scale_by: factor to scale by :returns: a dict c...
data = {'scaleBy': scale_by} response = self._do_request( 'PUT', '/v2/groups/{group_id}'.format(group_id=group_id), data=json.dumps(data)) return response.json()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_tasks(self, app_id=None, **kwargs): """List running tasks, optionally filtered by app_id. :param str app_id: if passed, only show tasks for this applica...
response = self._do_request( 'GET', '/v2/apps/%s/tasks' % app_id if app_id else '/v2/tasks') tasks = self._parse_response( response, MarathonTask, is_list=True, resource_name='tasks') [setattr(t, 'app_id', app_id) for t in tasks if app_id and t.app_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 kill_given_tasks(self, task_ids, scale=False, force=None): """Kill a list of given tasks. :param list[str] task_ids: tasks to kill :param bool scale: if true...
params = {'scale': scale} if force is not None: params['force'] = force data = json.dumps({"ids": task_ids}) response = self._do_request( 'POST', '/v2/tasks/delete', params=params, data=data) return response == 200
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def kill_tasks(self, app_id, scale=False, wipe=False, host=None, batch_size=0, batch_delay=0): """Kill all tasks belonging to app. :param str app_id: application...
def batch(iterable, size): sourceiter = iter(iterable) while True: batchiter = itertools.islice(sourceiter, size) yield itertools.chain([next(batchiter)], batchiter) if batch_size == 0: # Terminate all at once params = {'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 kill_task(self, app_id, task_id, scale=False, wipe=False): """Kill a task. :param str app_id: application ID :param str task_id: the task to kill :param bool...
params = {'scale': scale, 'wipe': wipe} response = self._do_request('DELETE', '/v2/apps/{app_id}/tasks/{task_id}' .format(app_id=app_id, task_id=task_id), params) # Marathon is inconsistent about what type of object it returns on the multi # task dele...
<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_versions(self, app_id): """List the versions of an app. :param str app_id: application ID :returns: list of versions :rtype: list[str] """
response = self._do_request( 'GET', '/v2/apps/{app_id}/versions'.format(app_id=app_id)) return [version for version in response.json()['versions']]
<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_version(self, app_id, version): """Get the configuration of an app at a specific version. :param str app_id: application ID :param str version: applicati...
response = self._do_request('GET', '/v2/apps/{app_id}/versions/{version}' .format(app_id=app_id, version=version)) return MarathonApp.from_json(response.json())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_event_subscription(self, url): """Register a callback URL as an event subscriber. :param str url: callback URL :returns: the created event subscriptio...
params = {'callbackUrl': url} response = self._do_request('POST', '/v2/eventSubscriptions', params) return response.json()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete_event_subscription(self, url): """Deregister a callback URL as an event subscriber. :param str url: callback URL :returns: the deleted event subscript...
params = {'callbackUrl': url} response = self._do_request('DELETE', '/v2/eventSubscriptions', params) return response.json()