sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def get_page(self, form): '''Get the requested page''' page_size = form.cleaned_data['iDisplayLength'] start_index = form.cleaned_data['iDisplayStart'] paginator = Paginator(self.object_list, page_size) num_page = (start_index / page_size) + 1 return paginator.page(num_pa...
Get the requested page
entailment
def get_row(self, row): '''Format a single row (if necessary)''' if isinstance(self.fields, dict): return dict([ (key, text_type(value).format(**row) if RE_FORMATTED.match(value) else row[value]) for key, value in self.fields.items() ]) el...
Format a single row (if necessary)
entailment
def render_to_response(self, form, **kwargs): '''Render Datatables expected JSON format''' page = self.get_page(form) data = { 'iTotalRecords': page.paginator.count, 'iTotalDisplayRecords': page.paginator.count, 'sEcho': form.cleaned_data['sEcho'], ...
Render Datatables expected JSON format
entailment
def set_grant_type(self, grant_type = 'client_credentials', api_key=None, api_secret=None, scope=None, info=None): """ Grant types: - token: An authorization is requested to the end-user by redirecting it to an authorization page hosted on Dailymotion. Once authorized, ...
Grant types: - token: An authorization is requested to the end-user by redirecting it to an authorization page hosted on Dailymotion. Once authorized, a refresh token is requested by the API client to the token server and stored in the end-user's cookie (or other storage tec...
entailment
def authenticated(func): """ Decorator to check if Smappee's access token has expired. If it has, use the refresh token to request a new access token """ @wraps(func) def wrapper(*args, **kwargs): self = args[0] if self.refresh_token is not None and \ self.token_expira...
Decorator to check if Smappee's access token has expired. If it has, use the refresh token to request a new access token
entailment
def urljoin(*parts): """ Join terms together with forward slashes Parameters ---------- parts Returns ------- str """ # first strip extra forward slashes (except http:// and the likes) and # create list part_list = [] for part in parts: p = str(part) ...
Join terms together with forward slashes Parameters ---------- parts Returns ------- str
entailment
def authenticate(self, username, password): """ Uses a Smappee username and password to request an access token, refresh token and expiry date. Parameters ---------- username : str password : str Returns ------- requests.Response ...
Uses a Smappee username and password to request an access token, refresh token and expiry date. Parameters ---------- username : str password : str Returns ------- requests.Response access token is saved in self.access_token refre...
entailment
def _set_token_expiration_time(self, expires_in): """ Saves the token expiration time by adding the 'expires in' parameter to the current datetime (in utc). Parameters ---------- expires_in : int number of seconds from the time of the request until expiration...
Saves the token expiration time by adding the 'expires in' parameter to the current datetime (in utc). Parameters ---------- expires_in : int number of seconds from the time of the request until expiration Returns ------- nothing saves ex...
entailment
def get_service_locations(self): """ Request service locations Returns ------- dict """ url = URLS['servicelocation'] headers = {"Authorization": "Bearer {}".format(self.access_token)} r = requests.get(url, headers=headers) r.raise_for_sta...
Request service locations Returns ------- dict
entailment
def get_service_location_info(self, service_location_id): """ Request service location info Parameters ---------- service_location_id : int Returns ------- dict """ url = urljoin(URLS['servicelocation'], service_location_id, "info") ...
Request service location info Parameters ---------- service_location_id : int Returns ------- dict
entailment
def get_consumption(self, service_location_id, start, end, aggregation, raw=False): """ Request Elektricity consumption and Solar production for a given service location. Parameters ---------- service_location_id : int start : int | dt.datetime | pd.Timestamp ...
Request Elektricity consumption and Solar production for a given service location. Parameters ---------- service_location_id : int start : int | dt.datetime | pd.Timestamp end : int | dt.datetime | pd.Timestamp start and end support epoch (in milliseconds), ...
entailment
def get_sensor_consumption(self, service_location_id, sensor_id, start, end, aggregation): """ Request consumption for a given sensor in a given service location Parameters ---------- service_location_id : int sensor_id : int start ...
Request consumption for a given sensor in a given service location Parameters ---------- service_location_id : int sensor_id : int start : int | dt.datetime | pd.Timestamp end : int | dt.datetime | pd.Timestamp start and end support epoch (in milliseconds), ...
entailment
def _get_consumption(self, url, start, end, aggregation): """ Request for both the get_consumption and get_sensor_consumption methods. Parameters ---------- url : str start : dt.datetime end : dt.datetime aggregation : int Returns ...
Request for both the get_consumption and get_sensor_consumption methods. Parameters ---------- url : str start : dt.datetime end : dt.datetime aggregation : int Returns ------- dict
entailment
def get_events(self, service_location_id, appliance_id, start, end, max_number=None): """ Request events for a given appliance Parameters ---------- service_location_id : int appliance_id : int start : int | dt.datetime | pd.Timestamp e...
Request events for a given appliance Parameters ---------- service_location_id : int appliance_id : int start : int | dt.datetime | pd.Timestamp end : int | dt.datetime | pd.Timestamp start and end support epoch (in milliseconds), datetime and Pan...
entailment
def actuator_on(self, service_location_id, actuator_id, duration=None): """ Turn actuator on Parameters ---------- service_location_id : int actuator_id : int duration : int, optional 300,900,1800 or 3600 , specifying the time in seconds the actuator ...
Turn actuator on Parameters ---------- service_location_id : int actuator_id : int duration : int, optional 300,900,1800 or 3600 , specifying the time in seconds the actuator should be turned on. Any other value results in turning on for an un...
entailment
def actuator_off(self, service_location_id, actuator_id, duration=None): """ Turn actuator off Parameters ---------- service_location_id : int actuator_id : int duration : int, optional 300,900,1800 or 3600 , specifying the time in seconds the actuato...
Turn actuator off Parameters ---------- service_location_id : int actuator_id : int duration : int, optional 300,900,1800 or 3600 , specifying the time in seconds the actuator should be turned on. Any other value results in turning on for an u...
entailment
def _actuator_on_off(self, on_off, service_location_id, actuator_id, duration=None): """ Turn actuator on or off Parameters ---------- on_off : str 'on' or 'off' service_location_id : int actuator_id : int duration : i...
Turn actuator on or off Parameters ---------- on_off : str 'on' or 'off' service_location_id : int actuator_id : int duration : int, optional 300,900,1800 or 3600 , specifying the time in seconds the actuator should be turned on. Any o...
entailment
def get_consumption_dataframe(self, service_location_id, start, end, aggregation, sensor_id=None, localize=False, raw=False): """ Extends get_consumption() AND get_sensor_consumption(), parses the results in a Pandas DataFrame ...
Extends get_consumption() AND get_sensor_consumption(), parses the results in a Pandas DataFrame Parameters ---------- service_location_id : int start : dt.datetime | int end : dt.datetime | int timezone-naive datetimes are assumed to be in UTC ep...
entailment
def _to_milliseconds(self, time): """ Converts a datetime-like object to epoch, in milliseconds Timezone-naive datetime objects are assumed to be in UTC Parameters ---------- time : dt.datetime | pd.Timestamp | int Returns ------- int ...
Converts a datetime-like object to epoch, in milliseconds Timezone-naive datetime objects are assumed to be in UTC Parameters ---------- time : dt.datetime | pd.Timestamp | int Returns ------- int epoch milliseconds
entailment
def _basic_post(self, url, data=None): """ Because basically every post request is the same Parameters ---------- url : str data : str, optional Returns ------- requests.Response """ _url = urljoin(self.base_url, url) r = ...
Because basically every post request is the same Parameters ---------- url : str data : str, optional Returns ------- requests.Response
entailment
def logon(self, password='admin'): """ Parameters ---------- password : str default 'admin' Returns ------- dict """ r = self._basic_post(url='logon', data=password) return r.json()
Parameters ---------- password : str default 'admin' Returns ------- dict
entailment
def active_power(self): """ Takes the sum of all instantaneous active power values Returns them in kWh Returns ------- float """ inst = self.load_instantaneous() values = [float(i['value']) for i in inst if i['key'].endswith('ActivePower')] ...
Takes the sum of all instantaneous active power values Returns them in kWh Returns ------- float
entailment
def active_cosfi(self): """ Takes the average of all instantaneous cosfi values Returns ------- float """ inst = self.load_instantaneous() values = [float(i['value']) for i in inst if i['key'].endswith('Cosfi')] return sum(values) / len(values)
Takes the average of all instantaneous cosfi values Returns ------- float
entailment
def on_command_control(self, val_id): """ Parameters ---------- val_id : str Returns ------- requests.Response """ data = "control,controlId=1|" + val_id return self._basic_post(url='commandControlPublic', data=data)
Parameters ---------- val_id : str Returns ------- requests.Response
entailment
def off_command_control(self, val_id): """ Parameters ---------- val_id : str Returns ------- requests.Response """ data = "control,controlId=0|" + val_id return self._basic_post(url='commandControlPublic', data=data)
Parameters ---------- val_id : str Returns ------- requests.Response
entailment
def delete_command_control(self, val_id): """ Parameters ---------- val_id : str Returns ------- requests.Response """ data = "delete,controlId=" + val_id return self._basic_post(url='commandControlPublic', data=data)
Parameters ---------- val_id : str Returns ------- requests.Response
entailment
def delete_command_control_timers(self, val_id): """ Parameters ---------- val_id : str Returns ------- requests.Response """ data = "deleteTimers,controlId=" + val_id return self._basic_post(url='commandControlPublic', data=data)
Parameters ---------- val_id : str Returns ------- requests.Response
entailment
def select_logfile(self, logfile): """ Parameters ---------- logfile : str Returns ------- dict """ data = 'logFileSelect,' + logfile r = self._basic_post(url='logBrowser', data=data) return r.json()
Parameters ---------- logfile : str Returns ------- dict
entailment
def getInterfaceInAllSpeeds(interface, endpoint_list, class_descriptor_list=()): """ Produce similar fs, hs and ss interface and endpoints descriptors. Should be useful for devices desiring to work in all 3 speeds with maximum endpoint wMaxPacketSize. Reduces data duplication from descriptor declara...
Produce similar fs, hs and ss interface and endpoints descriptors. Should be useful for devices desiring to work in all 3 speeds with maximum endpoint wMaxPacketSize. Reduces data duplication from descriptor declarations. Not intended to cover fancy combinations. interface (dict): Keyword arg...
entailment
def getDescriptor(klass, **kw): """ Automatically fills bLength and bDescriptorType. """ # XXX: ctypes Structure.__init__ ignores arguments which do not exist # as structure fields. So check it. # This is annoying, but not doing it is a huge waste of time for the # developer. empty = kla...
Automatically fills bLength and bDescriptorType.
entailment
def getOSDesc(interface, ext_list): """ Return an OS description header. interface (int) Related interface number. ext_list (list of OSExtCompatDesc or OSExtPropDesc) List of instances of extended descriptors. """ try: ext_type, = {type(x) for x in ext_list} except Va...
Return an OS description header. interface (int) Related interface number. ext_list (list of OSExtCompatDesc or OSExtPropDesc) List of instances of extended descriptors.
entailment
def getOSExtPropDesc(data_type, name, value): """ Returns an OS extension property descriptor. data_type (int) See wPropertyDataType documentation. name (string) See PropertyName documentation. value (string) See PropertyData documentation. NULL chars must be explicit...
Returns an OS extension property descriptor. data_type (int) See wPropertyDataType documentation. name (string) See PropertyName documentation. value (string) See PropertyData documentation. NULL chars must be explicitely included in the value when needed, this functi...
entailment
def getDescsV2(flags, fs_list=(), hs_list=(), ss_list=(), os_list=()): """ Return a FunctionFS descriptor suitable for serialisation. flags (int) Any combination of VIRTUAL_ADDR, EVENTFD, ALL_CTRL_RECIP, CONFIG0_SETUP. {fs,hs,ss,os}_list (list of descriptors) Instances of the fo...
Return a FunctionFS descriptor suitable for serialisation. flags (int) Any combination of VIRTUAL_ADDR, EVENTFD, ALL_CTRL_RECIP, CONFIG0_SETUP. {fs,hs,ss,os}_list (list of descriptors) Instances of the following classes: {fs,hs,ss}_list: USBInterfaceDescriptor ...
entailment
def getStrings(lang_dict): """ Return a FunctionFS descriptor suitable for serialisation. lang_dict (dict) Key: language ID (ex: 0x0409 for en-us) Value: list of unicode objects All values must have the same number of items. """ field_list = [] kw = {} try: s...
Return a FunctionFS descriptor suitable for serialisation. lang_dict (dict) Key: language ID (ex: 0x0409 for en-us) Value: list of unicode objects All values must have the same number of items.
entailment
def serialise(structure): """ structure (ctypes.Structure) The structure to serialise. Returns a ctypes.c_char array. Does not copy memory. """ return ctypes.cast( ctypes.pointer(structure), ctypes.POINTER(ctypes.c_char * ctypes.sizeof(structure)), ).contents
structure (ctypes.Structure) The structure to serialise. Returns a ctypes.c_char array. Does not copy memory.
entailment
def halt(self, request_type): """ Halt current endpoint. """ try: if request_type & ch9.USB_DIR_IN: self.read(0) else: self.write(b'') except IOError as exc: if exc.errno != errno.EL2HLT: raise ...
Halt current endpoint.
entailment
def getRealInterfaceNumber(self, interface): """ Returns the host-visible interface number, or None if there is no such interface. """ try: return self._ioctl(INTERFACE_REVMAP, interface) except IOError as exc: if exc.errno == errno.EDOM: ...
Returns the host-visible interface number, or None if there is no such interface.
entailment
def getDescriptor(self): """ Returns the currently active endpoint descriptor (depending on current USB speed). """ result = USBEndpointDescriptor() self._ioctl(ENDPOINT_DESC, result, True) return result
Returns the currently active endpoint descriptor (depending on current USB speed).
entailment
def halt(self): """ Halt current endpoint. """ try: self._halt() except IOError as exc: if exc.errno != errno.EBADMSG: raise else: raise ValueError('halt did not return EBADMSG ?') self._halted = True
Halt current endpoint.
entailment
def close(self): """ Close all endpoint file descriptors. """ ep_list = self._ep_list while ep_list: ep_list.pop().close() self._closed = True
Close all endpoint file descriptors.
entailment
def onSetup(self, request_type, request, value, index, length): """ Called when a setup USB transaction was received. Default implementation: - handles USB_REQ_GET_STATUS on interface and endpoints - handles USB_REQ_CLEAR_FEATURE(USB_ENDPOINT_HALT) on endpoints - handles...
Called when a setup USB transaction was received. Default implementation: - handles USB_REQ_GET_STATUS on interface and endpoints - handles USB_REQ_CLEAR_FEATURE(USB_ENDPOINT_HALT) on endpoints - handles USB_REQ_SET_FEATURE(USB_ENDPOINT_HALT) on endpoints - halts on everything e...
entailment
def main(): """ Slowly writes to stdout, without emitting a newline so any output buffering (or input for next pipeline command) can be detected. """ now = datetime.datetime.now try: while True: sys.stdout.write(str(now()) + ' ') time.sleep(1) except KeyboardI...
Slowly writes to stdout, without emitting a newline so any output buffering (or input for next pipeline command) can be detected.
entailment
def onEnable(self): """ The configuration containing this function has been enabled by host. Endpoints become working files, so submit some read operations. """ trace('onEnable') self._disable() self._aio_context.submit(self._aio_recv_block_list) self._rea...
The configuration containing this function has been enabled by host. Endpoints become working files, so submit some read operations.
entailment
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...
The configuration containing this function has been disabled by host. Endpoint do not work anymore, so cancel AIO operation blocks.
entailment
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 even...
Call when eventfd notified events are available.
entailment
def write(self, value): """ Queue write in kernel. value (bytes) Value to send. """ aio_block = libaio.AIOBlock( mode=libaio.AIOBLOCK_MODE_WRITE, target_file=self.getEndpoint(1), buffer_list=[bytearray(value)], offset=0,...
Queue write in kernel. value (bytes) Value to send.
entailment
def pretty_error(error, verbose=False): """Return an error message that is easier to read and more useful. May require updating if the schemas change significantly. """ error_loc = '' if error.path: while len(error.path) > 0: path_elem = error.path.popleft() if type(...
Return an error message that is easier to read and more useful. May require updating if the schemas change significantly.
entailment
def _iter_errors_custom(instance, checks, options): """Perform additional validation not possible merely with JSON schemas. Args: instance: The STIX object to be validated. checks: A sequence of callables which do the checks. Each callable may be written to accept 1 arg, which is t...
Perform additional validation not possible merely with JSON schemas. Args: instance: The STIX object to be validated. checks: A sequence of callables which do the checks. Each callable may be written to accept 1 arg, which is the object to check, or 2 args, which are the ob...
entailment
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. recursive: If ``True``, this function will descend into all subdirectories. Returns: A list of JSON file paths dire...
Return a list of file paths for JSON files within `directory`. Args: directory: A path to a directory. recursive: If ``True``, this function will descend into all subdirectories. Returns: A list of JSON file paths directly under `directory`.
entailment
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 ``.json`` extension will be added to the return value. Args: files: A list of file paths and/or directory paths. recursive: If ``tru...
Return a list of files to validate from `files`. If a member of `files` is a directory, its children with a ``.json`` extension will be added to the return value. Args: files: A list of file paths and/or directory paths. recursive: If ``true``, this will descend into any subdirectories ...
entailment
def run_validation(options): """Validate files based on command line options. Args: options: An instance of ``ValidationOptions`` containing options for this validation run. """ if options.files == sys.stdin: results = validate(options.files, options) return [FileVa...
Validate files based on command line options. Args: options: An instance of ``ValidationOptions`` containing options for this validation run.
entailment
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 is given, a single result is returned. Otherwise, a list of results is returned. If an error occurs, a ValidationErrorResults instance ...
Validate objects from parsed JSON. This supports a single object, or a list of objects. If a single object is given, a single result is returned. Otherwise, a list of results is returned. If an error occurs, a ValidationErrorResults instance or list which includes one of these instances, is returned...
entailment
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 options :return: An ObjectValidationResults instance, or a list of such. """ obj_json = json.load(in_) results = validate_pars...
Validate objects from JSON data in a textual stream. :param in_: A textual stream of JSON data. :param options: Validation options :return: An ObjectValidationResults instance, or a list of such.
entailment
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 further validation will take place. Args: fn: The filename of the JSON file to be validated. options: An instance of ``Validat...
Validate the input document `fn` according to the options passed in. If any exceptions are raised during validation, no further validation will take place. Args: fn: The filename of the JSON file to be validated. options: An instance of ``ValidationOptions``. Returns: An insta...
entailment
def validate_string(string, options=None): """Validate the input `string` according to the options passed in. If any exceptions are raised during validation, no further validation will take place. Args: string: The string containing the JSON to be validated. options: An instance of ``V...
Validate the input `string` according to the options passed in. If any exceptions are raised during validation, no further validation will take place. Args: string: The string containing the JSON to be validated. options: An instance of ``ValidationOptions``. Returns: An Objec...
entailment
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 Python object representation of the same schema. Returns: An instance of Draft4Validator. """ # Get correct prefix...
Create a JSON schema validator for the given schema. Args: schema_path: The filename of the JSON schema. schema: A Python object representation of the same schema. Returns: An instance of Draft4Validator.
entailment
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: ...
Search the `schema_dir` directory for a schema called `obj_type`.json. Return the file path of the first match it finds.
entailment
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 object representation of the schema. """ try: with open(schema_path) as schema_file: schema = json.loa...
Load the JSON schema at the given path as a Python object. Args: schema_path: A filename for a JSON schema. Returns: A Python object representation of the schema.
entailment
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 object type. Args: type (str): The object type to find the schema for. obj: The object to be validated. schema_dir (str): The pat...
Get a generator for validating against the schema for the given object type. Args: type (str): The object type to find the schema for. obj: The object to be validated. schema_dir (str): The path in which to search for schemas. version (str): The version of the STIX specification to ...
entailment
def _get_musts(options): """Return the list of 'MUST' validators for the correct version of STIX. Args: options: ValidationOptions instance with validation options for this validation run, including the STIX spec version. """ if options.version == '2.0': return musts20.list_...
Return the list of 'MUST' validators for the correct version of STIX. Args: options: ValidationOptions instance with validation options for this validation run, including the STIX spec version.
entailment
def _get_shoulds(options): """Return the list of 'SHOULD' validators for the correct version of STIX. Args: options: ValidationOptions instance with validation options for this validation run, including the STIX spec version. """ if options.version == '2.0': return shoulds20...
Return the list of 'SHOULD' validators for the correct version of STIX. Args: options: ValidationOptions instance with validation options for this validation run, including the STIX spec version.
entailment
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 generators which must be iterated to trigger the actual generation. This function first creates generators for the built-in schemas, then adds ...
Set up validation of a single STIX object against its type's schema. This does no actual validation; it just returns generators which must be iterated to trigger the actual generation. This function first creates generators for the built-in schemas, then adds generators for additional schemas from the ...
entailment
def validate_instance(instance, options=None): """Perform STIX JSON Schema validation against STIX input. Find the correct schema by looking at the 'type' property of the `instance` JSON object. Args: instance: A Python dictionary representing a STIX object with a 'type' property. ...
Perform STIX JSON Schema validation against STIX input. Find the correct schema by looking at the 'type' property of the `instance` JSON object. Args: instance: A Python dictionary representing a STIX object with a 'type' property. options: ValidationOptions instance with valid...
entailment
def object_result(self): """ Get the object result object, assuming there is only one. Raises an error if there is more than one. :return: The result object :raises ValueError: If there is more than one result """ num_obj_results = len(self._object_results) ...
Get the object result object, assuming there is only one. Raises an error if there is more than one. :return: The result object :raises ValueError: If there is more than one result
entailment
def object_results(self, object_results): """ Set the results to an iterable of values. The values will be collected into a list. A single value is allowed; it will be converted to a length 1 list. :param object_results: The results to set """ if _is_iterable_no...
Set the results to an iterable of values. The values will be collected into a list. A single value is allowed; it will be converted to a length 1 list. :param object_results: The results to set
entailment
def as_dict(self): """A dictionary representation of the :class:`.ObjectValidationResults` instance. Keys: * ``'result'``: The validation results (``True`` or ``False``) * ``'errors'``: A list of validation errors. Returns: A dictionary representatio...
A dictionary representation of the :class:`.ObjectValidationResults` instance. Keys: * ``'result'``: The validation results (``True`` or ``False``) * ``'errors'``: A list of validation errors. Returns: A dictionary representation of an instance of this class...
entailment
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), ...
Ensure custom content follows strict naming style conventions.
entailment
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...
Ensure custom content follows lenient naming style conventions for forward-compatibility.
entailment
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("...
Ensure custom objects follow strict naming style conventions.
entailment
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['typ...
Ensure custom objects follow lenient naming style conventions for forward-compatibility.
entailment
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[...
Ensure custom properties follow strict naming style conventions. Does not check property names in custom objects.
entailment
def custom_property_prefix_lax(instance): """Ensure custom properties follow lenient naming style conventions for forward-compatibility. Does not check property names in custom objects. """ for prop_name in instance.keys(): if (instance['type'] in enums.PROPERTIES and prop_n...
Ensure custom properties follow lenient naming style conventions for forward-compatibility. Does not check property names in custom objects.
entailment
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 underscores as word separators. """ if instance['type'] not in enums.VOCAB_PROPERTIES: return properties = enums.VOCAB_PROPERTIE...
Ensure that the values of all properties which use open vocabularies are in lowercase and use hyphens instead of spaces or underscores as word separators.
entailment
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']:...
Ensure the `kill_chain_name` and `phase_name` properties of `kill_chain_phase` objects follow naming style conventions.
entailment
def check_vocab(instance, vocab, code): """Ensure that the open vocabulary specified by `vocab` is used properly. This checks properties of objects specified in the appropriate `_USES` dictionary to determine which properties SHOULD use the given vocabulary, then checks that the values in those propert...
Ensure that the open vocabulary specified by `vocab` is used properly. This checks properties of objects specified in the appropriate `_USES` dictionary to determine which properties SHOULD use the given vocabulary, then checks that the values in those properties are from the vocabulary.
entailment
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 specification. """ if (instance['type'] == 'marking-definition' and 'definition_type' in instance and not instance['definitio...
Ensure that the `definition_type` property of `marking-definition` objects is one of the values in the STIX 2.0 specification.
entailment
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): ret...
Ensure that only the relationship types defined in the specification are used.
entailment
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: retu...
Return true if given value is a valid, recommended hash name according to the STIX 2 specification.
entailment
def vocab_hash_algo(instance): """Ensure objects with 'hashes' properties only use values from the hash-algo-ov vocabulary. """ for key, obj in instance['objects'].items(): if 'type' not in obj: continue if obj['type'] == 'file': try: hashes = obj...
Ensure objects with 'hashes' properties only use values from the hash-algo-ov vocabulary.
entailment
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-pebinary-type-ov vocabulary. """ for key, obj in instance['objects'].items(): if 'type' in obj and obj['type'] == 'file': try: ...
Ensure file objects with the windows-pebinary-ext extension have a 'pe-type' property that is from the windows-pebinary-type-ov vocabulary.
entailment
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'...
Ensure a user-account objects' 'account-type' property is from the account-type-ov vocabulary.
entailment
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 " ...
Ensure observable-objects keys are non-negative integers.
entailment
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_R...
Ensure custom observable objects follow strict naming style conventions.
entailment
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_OB...
Ensure custom observable objects follow naming style conventions.
entailment
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...
Ensure custom observable object extensions follow strict naming style conventions.
entailment
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): ...
Ensure custom observable object extensions follow naming style conventions.
entailment
def custom_observable_properties_prefix_strict(instance): """Ensure observable object custom properties follow strict naming style conventions. """ for key, obj in instance['objects'].items(): if 'type' not in obj: continue type_ = obj['type'] for prop in obj: ...
Ensure observable object custom properties follow strict naming style conventions.
entailment
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 ...
Ensure network-traffic objects contain both src_port and dst_port.
entailment
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, ...
Ensure the 'mime_type' property of file objects comes from the Template column in the IANA media type registry.
entailment
def protocols(instance): """Ensure the 'protocols' property of network-traffic objects contains only values from the IANA Service Name and Transport Protocol Port Number Registry. """ for key, obj in instance['objects'].items(): if ('type' in obj and obj['type'] == 'network-traffic' and ...
Ensure the 'protocols' property of network-traffic objects contains only values from the IANA Service Name and Transport Protocol Port Number Registry.
entailment
def ipfix(instance): """Ensure the 'ipfix' property of network-traffic objects contains only values from the IANA IP Flow Information Export (IPFIX) Entities Registry. """ ipf_pattern = re.compile(r'^[a-z][a-zA-Z0-9]+') for key, obj in instance['objects'].items(): if ('type' in obj and obj['...
Ensure the 'ipfix' property of network-traffic objects contains only values from the IANA IP Flow Information Export (IPFIX) Entities Registry.
entailment
def http_request_headers(instance): """Ensure the keys of the 'request_headers' property of the http-request- ext extension of network-traffic objects conform to the format for HTTP request headers. Use a regex because there isn't a definitive source. https://www.iana.org/assignments/message-headers/mes...
Ensure the keys of the 'request_headers' property of the http-request- ext extension of network-traffic objects conform to the format for HTTP request headers. Use a regex because there isn't a definitive source. https://www.iana.org/assignments/message-headers/message-headers.xhtml does not differentia...
entailment
def socket_options(instance): """Ensure the keys of the 'options' property of the socket-ext extension of network-traffic objects are only valid socket options (SO_*). """ for key, obj in instance['objects'].items(): if ('type' in obj and obj['type'] == 'network-traffic'): try: ...
Ensure the keys of the 'options' property of the socket-ext extension of network-traffic objects are only valid socket options (SO_*).
entailment
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 Information Dictionary Keys. """ for key, obj in instance['objects'].items(): if ('type' in obj and obj['type'] == 'file'): try...
Ensure the keys of the 'document_info_dict' property of the pdf-ext extension of file objects are only valid PDF Document Information Dictionary Keys.
entailment
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`...
Ensure that the `country` property of `location` objects is a valid ISO 3166-1 ALPHA-2 Code.
entailment
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: pr...
Ensure the 'priority' property of windows-process-ext ends in '_CLASS'.
entailment
def hash_length(instance): """Ensure keys in 'hashes'-type properties are no more than 30 characters long. """ for key, obj in instance['objects'].items(): if 'type' not in obj: continue if obj['type'] == 'file': try: hashes = obj['hashes'] ...
Ensure keys in 'hashes'-type properties are no more than 30 characters long.
entailment
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: c...
Ensure objects with duplicate IDs have different `modified` timestamps.
entailment
def list_shoulds(options): """Construct the list of 'SHOULD' validators to be run by the validator. """ validator_list = [] # Default: enable all if not options.disabled and not options.enabled: validator_list.extend(CHECKS['all']) return validator_list # --disable # Add SH...
Construct the list of 'SHOULD' validators to be run by the validator.
entailment
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'] i...
Ensure timestamps contain sane months, days, hours, minutes, seconds.
entailment