repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
noirbizarre/django-eztables | eztables/views.py | DatatablesView.get_page | 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... | python | 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... | [
"def",
"get_page",
"(",
"self",
",",
"form",
")",
":",
"page_size",
"=",
"form",
".",
"cleaned_data",
"[",
"'iDisplayLength'",
"]",
"start_index",
"=",
"form",
".",
"cleaned_data",
"[",
"'iDisplayStart'",
"]",
"paginator",
"=",
"Paginator",
"(",
"self",
".",... | Get the requested page | [
"Get",
"the",
"requested",
"page"
] | train | https://github.com/noirbizarre/django-eztables/blob/347e74dcc08121d20f4cf942181d873dbe33b995/eztables/views.py#L179-L185 |
noirbizarre/django-eztables | eztables/views.py | DatatablesView.get_row | 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... | python | 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... | [
"def",
"get_row",
"(",
"self",
",",
"row",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"fields",
",",
"dict",
")",
":",
"return",
"dict",
"(",
"[",
"(",
"key",
",",
"text_type",
"(",
"value",
")",
".",
"format",
"(",
"*",
"*",
"row",
")",
"... | Format a single row (if necessary) | [
"Format",
"a",
"single",
"row",
"(",
"if",
"necessary",
")"
] | train | https://github.com/noirbizarre/django-eztables/blob/347e74dcc08121d20f4cf942181d873dbe33b995/eztables/views.py#L191-L202 |
noirbizarre/django-eztables | eztables/views.py | DatatablesView.render_to_response | 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'],
... | python | 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'],
... | [
"def",
"render_to_response",
"(",
"self",
",",
"form",
",",
"*",
"*",
"kwargs",
")",
":",
"page",
"=",
"self",
".",
"get_page",
"(",
"form",
")",
"data",
"=",
"{",
"'iTotalRecords'",
":",
"page",
".",
"paginator",
".",
"count",
",",
"'iTotalDisplayRecord... | Render Datatables expected JSON format | [
"Render",
"Datatables",
"expected",
"JSON",
"format"
] | train | https://github.com/noirbizarre/django-eztables/blob/347e74dcc08121d20f4cf942181d873dbe33b995/eztables/views.py#L204-L213 |
dailymotion/dailymotion-sdk-python | dailymotion.py | Dailymotion.set_grant_type | 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, ... | python | 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, ... | [
"def",
"set_grant_type",
"(",
"self",
",",
"grant_type",
"=",
"'client_credentials'",
",",
"api_key",
"=",
"None",
",",
"api_secret",
"=",
"None",
",",
"scope",
"=",
"None",
",",
"info",
"=",
"None",
")",
":",
"self",
".",
"access_token",
"=",
"None",
"i... | 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... | [
"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",
"... | train | https://github.com/dailymotion/dailymotion-sdk-python/blob/944a8a474119c87d351504b0865e21216e286559/dailymotion.py#L164-L215 |
EnergieID/smappy | smappy/smappy.py | authenticated | 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... | python | 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... | [
"def",
"authenticated",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
"=",
"args",
"[",
"0",
"]",
"if",
"self",
".",
"refresh_token",
"is",
"not",
"None",
"an... | Decorator to check if Smappee's access token has expired.
If it has, use the refresh token to request a new access token | [
"Decorator",
"to",
"check",
"if",
"Smappee",
"s",
"access",
"token",
"has",
"expired",
".",
"If",
"it",
"has",
"use",
"the",
"refresh",
"token",
"to",
"request",
"a",
"new",
"access",
"token"
] | train | https://github.com/EnergieID/smappy/blob/1ada3abc9a51c76205c072369258f6f4f4e8fd0f/smappy/smappy.py#L18-L30 |
EnergieID/smappy | smappy/smappy.py | urljoin | 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)
... | python | 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)
... | [
"def",
"urljoin",
"(",
"*",
"parts",
")",
":",
"# first strip extra forward slashes (except http:// and the likes) and",
"# create list",
"part_list",
"=",
"[",
"]",
"for",
"part",
"in",
"parts",
":",
"p",
"=",
"str",
"(",
"part",
")",
"if",
"p",
".",
"endswith"... | Join terms together with forward slashes
Parameters
----------
parts
Returns
-------
str | [
"Join",
"terms",
"together",
"with",
"forward",
"slashes"
] | train | https://github.com/EnergieID/smappy/blob/1ada3abc9a51c76205c072369258f6f4f4e8fd0f/smappy/smappy.py#L806-L830 |
EnergieID/smappy | smappy/smappy.py | Smappee.authenticate | 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
... | python | 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
... | [
"def",
"authenticate",
"(",
"self",
",",
"username",
",",
"password",
")",
":",
"url",
"=",
"URLS",
"[",
"'token'",
"]",
"data",
"=",
"{",
"\"grant_type\"",
":",
"\"password\"",
",",
"\"client_id\"",
":",
"self",
".",
"client_id",
",",
"\"client_secret\"",
... | 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... | [
"Uses",
"a",
"Smappee",
"username",
"and",
"password",
"to",
"request",
"an",
"access",
"token",
"refresh",
"token",
"and",
"expiry",
"date",
"."
] | train | https://github.com/EnergieID/smappy/blob/1ada3abc9a51c76205c072369258f6f4f4e8fd0f/smappy/smappy.py#L57-L89 |
EnergieID/smappy | smappy/smappy.py | Smappee._set_token_expiration_time | 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... | python | 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... | [
"def",
"_set_token_expiration_time",
"(",
"self",
",",
"expires_in",
")",
":",
"self",
".",
"token_expiration_time",
"=",
"dt",
".",
"datetime",
".",
"utcnow",
"(",
")",
"+",
"dt",
".",
"timedelta",
"(",
"0",
",",
"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
Returns
-------
nothing
saves ex... | [
"Saves",
"the",
"token",
"expiration",
"time",
"by",
"adding",
"the",
"expires",
"in",
"parameter",
"to",
"the",
"current",
"datetime",
"(",
"in",
"utc",
")",
"."
] | train | https://github.com/EnergieID/smappy/blob/1ada3abc9a51c76205c072369258f6f4f4e8fd0f/smappy/smappy.py#L91-L108 |
EnergieID/smappy | smappy/smappy.py | Smappee.get_service_locations | 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... | python | 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... | [
"def",
"get_service_locations",
"(",
"self",
")",
":",
"url",
"=",
"URLS",
"[",
"'servicelocation'",
"]",
"headers",
"=",
"{",
"\"Authorization\"",
":",
"\"Bearer {}\"",
".",
"format",
"(",
"self",
".",
"access_token",
")",
"}",
"r",
"=",
"requests",
".",
... | Request service locations
Returns
-------
dict | [
"Request",
"service",
"locations"
] | train | https://github.com/EnergieID/smappy/blob/1ada3abc9a51c76205c072369258f6f4f4e8fd0f/smappy/smappy.py#L139-L151 |
EnergieID/smappy | smappy/smappy.py | Smappee.get_service_location_info | 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")
... | python | 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")
... | [
"def",
"get_service_location_info",
"(",
"self",
",",
"service_location_id",
")",
":",
"url",
"=",
"urljoin",
"(",
"URLS",
"[",
"'servicelocation'",
"]",
",",
"service_location_id",
",",
"\"info\"",
")",
"headers",
"=",
"{",
"\"Authorization\"",
":",
"\"Bearer {}\... | Request service location info
Parameters
----------
service_location_id : int
Returns
-------
dict | [
"Request",
"service",
"location",
"info"
] | train | https://github.com/EnergieID/smappy/blob/1ada3abc9a51c76205c072369258f6f4f4e8fd0f/smappy/smappy.py#L154-L170 |
EnergieID/smappy | smappy/smappy.py | Smappee.get_consumption | 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
... | python | 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
... | [
"def",
"get_consumption",
"(",
"self",
",",
"service_location_id",
",",
"start",
",",
"end",
",",
"aggregation",
",",
"raw",
"=",
"False",
")",
":",
"url",
"=",
"urljoin",
"(",
"URLS",
"[",
"'servicelocation'",
"]",
",",
"service_location_id",
",",
"\"consum... | 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),
... | [
"Request",
"Elektricity",
"consumption",
"and",
"Solar",
"production",
"for",
"a",
"given",
"service",
"location",
"."
] | train | https://github.com/EnergieID/smappy/blob/1ada3abc9a51c76205c072369258f6f4f4e8fd0f/smappy/smappy.py#L173-L213 |
EnergieID/smappy | smappy/smappy.py | Smappee.get_sensor_consumption | 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 ... | python | 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 ... | [
"def",
"get_sensor_consumption",
"(",
"self",
",",
"service_location_id",
",",
"sensor_id",
",",
"start",
",",
"end",
",",
"aggregation",
")",
":",
"url",
"=",
"urljoin",
"(",
"URLS",
"[",
"'servicelocation'",
"]",
",",
"service_location_id",
",",
"\"sensor\"",
... | 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),
... | [
"Request",
"consumption",
"for",
"a",
"given",
"sensor",
"in",
"a",
"given",
"service",
"location"
] | train | https://github.com/EnergieID/smappy/blob/1ada3abc9a51c76205c072369258f6f4f4e8fd0f/smappy/smappy.py#L216-L244 |
EnergieID/smappy | smappy/smappy.py | Smappee._get_consumption | 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
... | python | 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
... | [
"def",
"_get_consumption",
"(",
"self",
",",
"url",
",",
"start",
",",
"end",
",",
"aggregation",
")",
":",
"start",
"=",
"self",
".",
"_to_milliseconds",
"(",
"start",
")",
"end",
"=",
"self",
".",
"_to_milliseconds",
"(",
"end",
")",
"headers",
"=",
... | Request for both the get_consumption and
get_sensor_consumption methods.
Parameters
----------
url : str
start : dt.datetime
end : dt.datetime
aggregation : int
Returns
-------
dict | [
"Request",
"for",
"both",
"the",
"get_consumption",
"and",
"get_sensor_consumption",
"methods",
"."
] | train | https://github.com/EnergieID/smappy/blob/1ada3abc9a51c76205c072369258f6f4f4e8fd0f/smappy/smappy.py#L246-L273 |
EnergieID/smappy | smappy/smappy.py | Smappee.get_events | 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... | python | 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... | [
"def",
"get_events",
"(",
"self",
",",
"service_location_id",
",",
"appliance_id",
",",
"start",
",",
"end",
",",
"max_number",
"=",
"None",
")",
":",
"start",
"=",
"self",
".",
"_to_milliseconds",
"(",
"start",
")",
"end",
"=",
"self",
".",
"_to_milliseco... | 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... | [
"Request",
"events",
"for",
"a",
"given",
"appliance"
] | train | https://github.com/EnergieID/smappy/blob/1ada3abc9a51c76205c072369258f6f4f4e8fd0f/smappy/smappy.py#L276-L311 |
EnergieID/smappy | smappy/smappy.py | Smappee.actuator_on | 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
... | python | 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
... | [
"def",
"actuator_on",
"(",
"self",
",",
"service_location_id",
",",
"actuator_id",
",",
"duration",
"=",
"None",
")",
":",
"return",
"self",
".",
"_actuator_on_off",
"(",
"on_off",
"=",
"'on'",
",",
"service_location_id",
"=",
"service_location_id",
",",
"actuat... | 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... | [
"Turn",
"actuator",
"on"
] | train | https://github.com/EnergieID/smappy/blob/1ada3abc9a51c76205c072369258f6f4f4e8fd0f/smappy/smappy.py#L314-L333 |
EnergieID/smappy | smappy/smappy.py | Smappee.actuator_off | 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... | python | 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... | [
"def",
"actuator_off",
"(",
"self",
",",
"service_location_id",
",",
"actuator_id",
",",
"duration",
"=",
"None",
")",
":",
"return",
"self",
".",
"_actuator_on_off",
"(",
"on_off",
"=",
"'off'",
",",
"service_location_id",
"=",
"service_location_id",
",",
"actu... | 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... | [
"Turn",
"actuator",
"off"
] | train | https://github.com/EnergieID/smappy/blob/1ada3abc9a51c76205c072369258f6f4f4e8fd0f/smappy/smappy.py#L336-L355 |
EnergieID/smappy | smappy/smappy.py | Smappee._actuator_on_off | 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... | python | 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... | [
"def",
"_actuator_on_off",
"(",
"self",
",",
"on_off",
",",
"service_location_id",
",",
"actuator_id",
",",
"duration",
"=",
"None",
")",
":",
"url",
"=",
"urljoin",
"(",
"URLS",
"[",
"'servicelocation'",
"]",
",",
"service_location_id",
",",
"\"actuator\"",
"... | 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... | [
"Turn",
"actuator",
"on",
"or",
"off"
] | train | https://github.com/EnergieID/smappy/blob/1ada3abc9a51c76205c072369258f6f4f4e8fd0f/smappy/smappy.py#L357-L386 |
EnergieID/smappy | smappy/smappy.py | Smappee.get_consumption_dataframe | 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
... | python | 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
... | [
"def",
"get_consumption_dataframe",
"(",
"self",
",",
"service_location_id",
",",
"start",
",",
"end",
",",
"aggregation",
",",
"sensor_id",
"=",
"None",
",",
"localize",
"=",
"False",
",",
"raw",
"=",
"False",
")",
":",
"import",
"pandas",
"as",
"pd",
"if... | 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... | [
"Extends",
"get_consumption",
"()",
"AND",
"get_sensor_consumption",
"()",
"parses",
"the",
"results",
"in",
"a",
"Pandas",
"DataFrame"
] | train | https://github.com/EnergieID/smappy/blob/1ada3abc9a51c76205c072369258f6f4f4e8fd0f/smappy/smappy.py#L388-L450 |
EnergieID/smappy | smappy/smappy.py | Smappee._to_milliseconds | 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
... | python | 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
... | [
"def",
"_to_milliseconds",
"(",
"self",
",",
"time",
")",
":",
"if",
"isinstance",
"(",
"time",
",",
"dt",
".",
"datetime",
")",
":",
"if",
"time",
".",
"tzinfo",
"is",
"None",
":",
"time",
"=",
"time",
".",
"replace",
"(",
"tzinfo",
"=",
"pytz",
"... | 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 | [
"Converts",
"a",
"datetime",
"-",
"like",
"object",
"to",
"epoch",
"in",
"milliseconds",
"Timezone",
"-",
"naive",
"datetime",
"objects",
"are",
"assumed",
"to",
"be",
"in",
"UTC"
] | train | https://github.com/EnergieID/smappy/blob/1ada3abc9a51c76205c072369258f6f4f4e8fd0f/smappy/smappy.py#L452-L474 |
EnergieID/smappy | smappy/smappy.py | LocalSmappee._basic_post | 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 = ... | python | 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 = ... | [
"def",
"_basic_post",
"(",
"self",
",",
"url",
",",
"data",
"=",
"None",
")",
":",
"_url",
"=",
"urljoin",
"(",
"self",
".",
"base_url",
",",
"url",
")",
"r",
"=",
"self",
".",
"session",
".",
"post",
"(",
"_url",
",",
"data",
"=",
"data",
",",
... | Because basically every post request is the same
Parameters
----------
url : str
data : str, optional
Returns
-------
requests.Response | [
"Because",
"basically",
"every",
"post",
"request",
"is",
"the",
"same"
] | train | https://github.com/EnergieID/smappy/blob/1ada3abc9a51c76205c072369258f6f4f4e8fd0f/smappy/smappy.py#L516-L532 |
EnergieID/smappy | smappy/smappy.py | LocalSmappee.logon | def logon(self, password='admin'):
"""
Parameters
----------
password : str
default 'admin'
Returns
-------
dict
"""
r = self._basic_post(url='logon', data=password)
return r.json() | python | def logon(self, password='admin'):
"""
Parameters
----------
password : str
default 'admin'
Returns
-------
dict
"""
r = self._basic_post(url='logon', data=password)
return r.json() | [
"def",
"logon",
"(",
"self",
",",
"password",
"=",
"'admin'",
")",
":",
"r",
"=",
"self",
".",
"_basic_post",
"(",
"url",
"=",
"'logon'",
",",
"data",
"=",
"password",
")",
"return",
"r",
".",
"json",
"(",
")"
] | Parameters
----------
password : str
default 'admin'
Returns
-------
dict | [
"Parameters",
"----------",
"password",
":",
"str",
"default",
"admin"
] | train | https://github.com/EnergieID/smappy/blob/1ada3abc9a51c76205c072369258f6f4f4e8fd0f/smappy/smappy.py#L541-L553 |
EnergieID/smappy | smappy/smappy.py | LocalSmappee.active_power | 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')]
... | python | 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')]
... | [
"def",
"active_power",
"(",
"self",
")",
":",
"inst",
"=",
"self",
".",
"load_instantaneous",
"(",
")",
"values",
"=",
"[",
"float",
"(",
"i",
"[",
"'value'",
"]",
")",
"for",
"i",
"in",
"inst",
"if",
"i",
"[",
"'key'",
"]",
".",
"endswith",
"(",
... | Takes the sum of all instantaneous active power values
Returns them in kWh
Returns
-------
float | [
"Takes",
"the",
"sum",
"of",
"all",
"instantaneous",
"active",
"power",
"values",
"Returns",
"them",
"in",
"kWh"
] | train | https://github.com/EnergieID/smappy/blob/1ada3abc9a51c76205c072369258f6f4f4e8fd0f/smappy/smappy.py#L573-L584 |
EnergieID/smappy | smappy/smappy.py | LocalSmappee.active_cosfi | 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) | python | 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) | [
"def",
"active_cosfi",
"(",
"self",
")",
":",
"inst",
"=",
"self",
".",
"load_instantaneous",
"(",
")",
"values",
"=",
"[",
"float",
"(",
"i",
"[",
"'value'",
"]",
")",
"for",
"i",
"in",
"inst",
"if",
"i",
"[",
"'key'",
"]",
".",
"endswith",
"(",
... | Takes the average of all instantaneous cosfi values
Returns
-------
float | [
"Takes",
"the",
"average",
"of",
"all",
"instantaneous",
"cosfi",
"values"
] | train | https://github.com/EnergieID/smappy/blob/1ada3abc9a51c76205c072369258f6f4f4e8fd0f/smappy/smappy.py#L586-L596 |
EnergieID/smappy | smappy/smappy.py | LocalSmappee.on_command_control | 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) | python | 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) | [
"def",
"on_command_control",
"(",
"self",
",",
"val_id",
")",
":",
"data",
"=",
"\"control,controlId=1|\"",
"+",
"val_id",
"return",
"self",
".",
"_basic_post",
"(",
"url",
"=",
"'commandControlPublic'",
",",
"data",
"=",
"data",
")"
] | Parameters
----------
val_id : str
Returns
-------
requests.Response | [
"Parameters",
"----------",
"val_id",
":",
"str"
] | train | https://github.com/EnergieID/smappy/blob/1ada3abc9a51c76205c072369258f6f4f4e8fd0f/smappy/smappy.py#L697-L708 |
EnergieID/smappy | smappy/smappy.py | LocalSmappee.off_command_control | 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) | python | 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) | [
"def",
"off_command_control",
"(",
"self",
",",
"val_id",
")",
":",
"data",
"=",
"\"control,controlId=0|\"",
"+",
"val_id",
"return",
"self",
".",
"_basic_post",
"(",
"url",
"=",
"'commandControlPublic'",
",",
"data",
"=",
"data",
")"
] | Parameters
----------
val_id : str
Returns
-------
requests.Response | [
"Parameters",
"----------",
"val_id",
":",
"str"
] | train | https://github.com/EnergieID/smappy/blob/1ada3abc9a51c76205c072369258f6f4f4e8fd0f/smappy/smappy.py#L710-L721 |
EnergieID/smappy | smappy/smappy.py | LocalSmappee.delete_command_control | 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) | python | 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) | [
"def",
"delete_command_control",
"(",
"self",
",",
"val_id",
")",
":",
"data",
"=",
"\"delete,controlId=\"",
"+",
"val_id",
"return",
"self",
".",
"_basic_post",
"(",
"url",
"=",
"'commandControlPublic'",
",",
"data",
"=",
"data",
")"
] | Parameters
----------
val_id : str
Returns
-------
requests.Response | [
"Parameters",
"----------",
"val_id",
":",
"str"
] | train | https://github.com/EnergieID/smappy/blob/1ada3abc9a51c76205c072369258f6f4f4e8fd0f/smappy/smappy.py#L739-L751 |
EnergieID/smappy | smappy/smappy.py | LocalSmappee.delete_command_control_timers | 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) | python | 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) | [
"def",
"delete_command_control_timers",
"(",
"self",
",",
"val_id",
")",
":",
"data",
"=",
"\"deleteTimers,controlId=\"",
"+",
"val_id",
"return",
"self",
".",
"_basic_post",
"(",
"url",
"=",
"'commandControlPublic'",
",",
"data",
"=",
"data",
")"
] | Parameters
----------
val_id : str
Returns
-------
requests.Response | [
"Parameters",
"----------",
"val_id",
":",
"str"
] | train | https://github.com/EnergieID/smappy/blob/1ada3abc9a51c76205c072369258f6f4f4e8fd0f/smappy/smappy.py#L753-L764 |
EnergieID/smappy | smappy/smappy.py | LocalSmappee.select_logfile | def select_logfile(self, logfile):
"""
Parameters
----------
logfile : str
Returns
-------
dict
"""
data = 'logFileSelect,' + logfile
r = self._basic_post(url='logBrowser', data=data)
return r.json() | python | def select_logfile(self, logfile):
"""
Parameters
----------
logfile : str
Returns
-------
dict
"""
data = 'logFileSelect,' + logfile
r = self._basic_post(url='logBrowser', data=data)
return r.json() | [
"def",
"select_logfile",
"(",
"self",
",",
"logfile",
")",
":",
"data",
"=",
"'logFileSelect,'",
"+",
"logfile",
"r",
"=",
"self",
".",
"_basic_post",
"(",
"url",
"=",
"'logBrowser'",
",",
"data",
"=",
"data",
")",
"return",
"r",
".",
"json",
"(",
")"
... | Parameters
----------
logfile : str
Returns
-------
dict | [
"Parameters",
"----------",
"logfile",
":",
"str"
] | train | https://github.com/EnergieID/smappy/blob/1ada3abc9a51c76205c072369258f6f4f4e8fd0f/smappy/smappy.py#L791-L803 |
vpelletier/python-functionfs | functionfs/__init__.py | getInterfaceInAllSpeeds | 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... | python | 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... | [
"def",
"getInterfaceInAllSpeeds",
"(",
"interface",
",",
"endpoint_list",
",",
"class_descriptor_list",
"=",
"(",
")",
")",
":",
"interface",
"=",
"getDescriptor",
"(",
"USBInterfaceDescriptor",
",",
"bNumEndpoints",
"=",
"len",
"(",
"endpoint_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
declarations.
Not intended to cover fancy combinations.
interface (dict):
Keyword arg... | [
"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... | train | https://github.com/vpelletier/python-functionfs/blob/e19f729bb47a7d1edd2488531af24551bb86726f/functionfs/__init__.py#L120-L260 |
vpelletier/python-functionfs | functionfs/__init__.py | getDescriptor | 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... | python | 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... | [
"def",
"getDescriptor",
"(",
"klass",
",",
"*",
"*",
"kw",
")",
":",
"# 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",
"=",
"... | Automatically fills bLength and bDescriptorType. | [
"Automatically",
"fills",
"bLength",
"and",
"bDescriptorType",
"."
] | train | https://github.com/vpelletier/python-functionfs/blob/e19f729bb47a7d1edd2488531af24551bb86726f/functionfs/__init__.py#L262-L283 |
vpelletier/python-functionfs | functionfs/__init__.py | getOSDesc | 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... | python | 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... | [
"def",
"getOSDesc",
"(",
"interface",
",",
"ext_list",
")",
":",
"try",
":",
"ext_type",
",",
"=",
"{",
"type",
"(",
"x",
")",
"for",
"x",
"in",
"ext_list",
"}",
"except",
"ValueError",
":",
"raise",
"TypeError",
"(",
"'Extensions of a single type are requir... | Return an OS description header.
interface (int)
Related interface number.
ext_list (list of OSExtCompatDesc or OSExtPropDesc)
List of instances of extended descriptors. | [
"Return",
"an",
"OS",
"description",
"header",
".",
"interface",
"(",
"int",
")",
"Related",
"interface",
"number",
".",
"ext_list",
"(",
"list",
"of",
"OSExtCompatDesc",
"or",
"OSExtPropDesc",
")",
"List",
"of",
"instances",
"of",
"extended",
"descriptors",
"... | train | https://github.com/vpelletier/python-functionfs/blob/e19f729bb47a7d1edd2488531af24551bb86726f/functionfs/__init__.py#L285-L329 |
vpelletier/python-functionfs | functionfs/__init__.py | getOSExtPropDesc | 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... | python | 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... | [
"def",
"getOSExtPropDesc",
"(",
"data_type",
",",
"name",
",",
"value",
")",
":",
"klass",
"=",
"type",
"(",
"'OSExtPropDesc'",
",",
"(",
"OSExtPropDescHead",
",",
")",
",",
"{",
"'_fields_'",
":",
"[",
"(",
"'bPropertyName'",
",",
"ctypes",
".",
"c_char",... | 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... | [
"Returns",
"an",
"OS",
"extension",
"property",
"descriptor",
".",
"data_type",
"(",
"int",
")",
"See",
"wPropertyDataType",
"documentation",
".",
"name",
"(",
"string",
")",
"See",
"PropertyName",
"documentation",
".",
"value",
"(",
"string",
")",
"See",
"Pro... | train | https://github.com/vpelletier/python-functionfs/blob/e19f729bb47a7d1edd2488531af24551bb86726f/functionfs/__init__.py#L331-L361 |
vpelletier/python-functionfs | functionfs/__init__.py | getDescsV2 | 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... | python | 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... | [
"def",
"getDescsV2",
"(",
"flags",
",",
"fs_list",
"=",
"(",
")",
",",
"hs_list",
"=",
"(",
")",
",",
"ss_list",
"=",
"(",
")",
",",
"os_list",
"=",
"(",
")",
")",
":",
"count_field_list",
"=",
"[",
"]",
"descr_field_list",
"=",
"[",
"]",
"kw",
"... | 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
... | [
"Return",
"a",
"FunctionFS",
"descriptor",
"suitable",
"for",
"serialisation",
"."
] | train | https://github.com/vpelletier/python-functionfs/blob/e19f729bb47a7d1edd2488531af24551bb86726f/functionfs/__init__.py#L389-L480 |
vpelletier/python-functionfs | functionfs/__init__.py | getStrings | 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... | python | 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... | [
"def",
"getStrings",
"(",
"lang_dict",
")",
":",
"field_list",
"=",
"[",
"]",
"kw",
"=",
"{",
"}",
"try",
":",
"str_count",
"=",
"len",
"(",
"next",
"(",
"iter",
"(",
"lang_dict",
".",
"values",
"(",
")",
")",
")",
")",
"except",
"StopIteration",
"... | 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. | [
"Return",
"a",
"FunctionFS",
"descriptor",
"suitable",
"for",
"serialisation",
"."
] | train | https://github.com/vpelletier/python-functionfs/blob/e19f729bb47a7d1edd2488531af24551bb86726f/functionfs/__init__.py#L482-L530 |
vpelletier/python-functionfs | functionfs/__init__.py | serialise | 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 | python | 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 | [
"def",
"serialise",
"(",
"structure",
")",
":",
"return",
"ctypes",
".",
"cast",
"(",
"ctypes",
".",
"pointer",
"(",
"structure",
")",
",",
"ctypes",
".",
"POINTER",
"(",
"ctypes",
".",
"c_char",
"*",
"ctypes",
".",
"sizeof",
"(",
"structure",
")",
")"... | structure (ctypes.Structure)
The structure to serialise.
Returns a ctypes.c_char array.
Does not copy memory. | [
"structure",
"(",
"ctypes",
".",
"Structure",
")",
"The",
"structure",
"to",
"serialise",
"."
] | train | https://github.com/vpelletier/python-functionfs/blob/e19f729bb47a7d1edd2488531af24551bb86726f/functionfs/__init__.py#L532-L543 |
vpelletier/python-functionfs | functionfs/__init__.py | Endpoint0File.halt | 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
... | python | 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
... | [
"def",
"halt",
"(",
"self",
",",
"request_type",
")",
":",
"try",
":",
"if",
"request_type",
"&",
"ch9",
".",
"USB_DIR_IN",
":",
"self",
".",
"read",
"(",
"0",
")",
"else",
":",
"self",
".",
"write",
"(",
"b''",
")",
"except",
"IOError",
"as",
"exc... | Halt current endpoint. | [
"Halt",
"current",
"endpoint",
"."
] | train | https://github.com/vpelletier/python-functionfs/blob/e19f729bb47a7d1edd2488531af24551bb86726f/functionfs/__init__.py#L559-L572 |
vpelletier/python-functionfs | functionfs/__init__.py | Endpoint0File.getRealInterfaceNumber | 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:
... | python | 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:
... | [
"def",
"getRealInterfaceNumber",
"(",
"self",
",",
"interface",
")",
":",
"try",
":",
"return",
"self",
".",
"_ioctl",
"(",
"INTERFACE_REVMAP",
",",
"interface",
")",
"except",
"IOError",
"as",
"exc",
":",
"if",
"exc",
".",
"errno",
"==",
"errno",
".",
"... | Returns the host-visible interface number, or None if there is no such
interface. | [
"Returns",
"the",
"host",
"-",
"visible",
"interface",
"number",
"or",
"None",
"if",
"there",
"is",
"no",
"such",
"interface",
"."
] | train | https://github.com/vpelletier/python-functionfs/blob/e19f729bb47a7d1edd2488531af24551bb86726f/functionfs/__init__.py#L574-L584 |
vpelletier/python-functionfs | functionfs/__init__.py | EndpointFile.getDescriptor | def getDescriptor(self):
"""
Returns the currently active endpoint descriptor
(depending on current USB speed).
"""
result = USBEndpointDescriptor()
self._ioctl(ENDPOINT_DESC, result, True)
return result | python | def getDescriptor(self):
"""
Returns the currently active endpoint descriptor
(depending on current USB speed).
"""
result = USBEndpointDescriptor()
self._ioctl(ENDPOINT_DESC, result, True)
return result | [
"def",
"getDescriptor",
"(",
"self",
")",
":",
"result",
"=",
"USBEndpointDescriptor",
"(",
")",
"self",
".",
"_ioctl",
"(",
"ENDPOINT_DESC",
",",
"result",
",",
"True",
")",
"return",
"result"
] | Returns the currently active endpoint descriptor
(depending on current USB speed). | [
"Returns",
"the",
"currently",
"active",
"endpoint",
"descriptor",
"(",
"depending",
"on",
"current",
"USB",
"speed",
")",
"."
] | train | https://github.com/vpelletier/python-functionfs/blob/e19f729bb47a7d1edd2488531af24551bb86726f/functionfs/__init__.py#L621-L628 |
vpelletier/python-functionfs | functionfs/__init__.py | EndpointFile.halt | 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 | python | 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 | [
"def",
"halt",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"_halt",
"(",
")",
"except",
"IOError",
"as",
"exc",
":",
"if",
"exc",
".",
"errno",
"!=",
"errno",
".",
"EBADMSG",
":",
"raise",
"else",
":",
"raise",
"ValueError",
"(",
"'halt did not r... | Halt current endpoint. | [
"Halt",
"current",
"endpoint",
"."
] | train | https://github.com/vpelletier/python-functionfs/blob/e19f729bb47a7d1edd2488531af24551bb86726f/functionfs/__init__.py#L633-L644 |
vpelletier/python-functionfs | functionfs/__init__.py | Function.close | def close(self):
"""
Close all endpoint file descriptors.
"""
ep_list = self._ep_list
while ep_list:
ep_list.pop().close()
self._closed = True | python | def close(self):
"""
Close all endpoint file descriptors.
"""
ep_list = self._ep_list
while ep_list:
ep_list.pop().close()
self._closed = True | [
"def",
"close",
"(",
"self",
")",
":",
"ep_list",
"=",
"self",
".",
"_ep_list",
"while",
"ep_list",
":",
"ep_list",
".",
"pop",
"(",
")",
".",
"close",
"(",
")",
"self",
".",
"_closed",
"=",
"True"
] | Close all endpoint file descriptors. | [
"Close",
"all",
"endpoint",
"file",
"descriptors",
"."
] | train | https://github.com/vpelletier/python-functionfs/blob/e19f729bb47a7d1edd2488531af24551bb86726f/functionfs/__init__.py#L800-L807 |
vpelletier/python-functionfs | functionfs/__init__.py | Function.onSetup | 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... | python | 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... | [
"def",
"onSetup",
"(",
"self",
",",
"request_type",
",",
"request",
",",
"value",
",",
"index",
",",
"length",
")",
":",
"if",
"(",
"request_type",
"&",
"ch9",
".",
"USB_TYPE_MASK",
")",
"==",
"ch9",
".",
"USB_TYPE_STANDARD",
":",
"recipient",
"=",
"requ... | 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... | [
"Called",
"when",
"a",
"setup",
"USB",
"transaction",
"was",
"received",
"."
] | train | https://github.com/vpelletier/python-functionfs/blob/e19f729bb47a7d1edd2488531af24551bb86726f/functionfs/__init__.py#L956-L1036 |
vpelletier/python-functionfs | examples/usbcat/slowprinter.py | main | 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... | python | 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... | [
"def",
"main",
"(",
")",
":",
"now",
"=",
"datetime",
".",
"datetime",
".",
"now",
"try",
":",
"while",
"True",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"str",
"(",
"now",
"(",
")",
")",
"+",
"' '",
")",
"time",
".",
"sleep",
"(",
"1",
"... | Slowly writes to stdout, without emitting a newline so any output
buffering (or input for next pipeline command) can be detected. | [
"Slowly",
"writes",
"to",
"stdout",
"without",
"emitting",
"a",
"newline",
"so",
"any",
"output",
"buffering",
"(",
"or",
"input",
"for",
"next",
"pipeline",
"command",
")",
"can",
"be",
"detected",
"."
] | train | https://github.com/vpelletier/python-functionfs/blob/e19f729bb47a7d1edd2488531af24551bb86726f/examples/usbcat/slowprinter.py#L22-L36 |
vpelletier/python-functionfs | examples/usbcat/device.py | USBCat.onEnable | 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... | python | 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... | [
"def",
"onEnable",
"(",
"self",
")",
":",
"trace",
"(",
"'onEnable'",
")",
"self",
".",
"_disable",
"(",
")",
"self",
".",
"_aio_context",
".",
"submit",
"(",
"self",
".",
"_aio_recv_block_list",
")",
"self",
".",
"_real_onCanSend",
"(",
")",
"self",
"."... | The configuration containing this function has been enabled by host.
Endpoints become working files, so submit some read operations. | [
"The",
"configuration",
"containing",
"this",
"function",
"has",
"been",
"enabled",
"by",
"host",
".",
"Endpoints",
"become",
"working",
"files",
"so",
"submit",
"some",
"read",
"operations",
"."
] | train | https://github.com/vpelletier/python-functionfs/blob/e19f729bb47a7d1edd2488531af24551bb86726f/examples/usbcat/device.py#L121-L130 |
vpelletier/python-functionfs | examples/usbcat/device.py | USBCat._disable | 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... | python | 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... | [
"def",
"_disable",
"(",
"self",
")",
":",
"if",
"self",
".",
"_enabled",
":",
"self",
".",
"_real_onCannotSend",
"(",
")",
"has_cancelled",
"=",
"0",
"for",
"block",
"in",
"self",
".",
"_aio_recv_block_list",
"+",
"self",
".",
"_aio_send_block_list",
":",
... | The configuration containing this function has been disabled by host.
Endpoint do not work anymore, so cancel AIO operation blocks. | [
"The",
"configuration",
"containing",
"this",
"function",
"has",
"been",
"disabled",
"by",
"host",
".",
"Endpoint",
"do",
"not",
"work",
"anymore",
"so",
"cancel",
"AIO",
"operation",
"blocks",
"."
] | train | https://github.com/vpelletier/python-functionfs/blob/e19f729bb47a7d1edd2488531af24551bb86726f/examples/usbcat/device.py#L136-L155 |
vpelletier/python-functionfs | examples/usbcat/device.py | USBCat.onAIOCompletion | 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... | python | 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... | [
"def",
"onAIOCompletion",
"(",
"self",
")",
":",
"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 ... | Call when eventfd notified events are available. | [
"Call",
"when",
"eventfd",
"notified",
"events",
"are",
"available",
"."
] | train | https://github.com/vpelletier/python-functionfs/blob/e19f729bb47a7d1edd2488531af24551bb86726f/examples/usbcat/device.py#L157-L168 |
vpelletier/python-functionfs | examples/usbcat/device.py | USBCat.write | 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,... | python | 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,... | [
"def",
"write",
"(",
"self",
",",
"value",
")",
":",
"aio_block",
"=",
"libaio",
".",
"AIOBlock",
"(",
"mode",
"=",
"libaio",
".",
"AIOBLOCK_MODE_WRITE",
",",
"target_file",
"=",
"self",
".",
"getEndpoint",
"(",
"1",
")",
",",
"buffer_list",
"=",
"[",
... | Queue write in kernel.
value (bytes)
Value to send. | [
"Queue",
"write",
"in",
"kernel",
".",
"value",
"(",
"bytes",
")",
"Value",
"to",
"send",
"."
] | train | https://github.com/vpelletier/python-functionfs/blob/e19f729bb47a7d1edd2488531af24551bb86726f/examples/usbcat/device.py#L196-L213 |
oasis-open/cti-stix-validator | stix2validator/errors.py | pretty_error | 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(... | python | 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(... | [
"def",
"pretty_error",
"(",
"error",
",",
"verbose",
"=",
"False",
")",
":",
"error_loc",
"=",
"''",
"if",
"error",
".",
"path",
":",
"while",
"len",
"(",
"error",
".",
"path",
")",
">",
"0",
":",
"path_elem",
"=",
"error",
".",
"path",
".",
"pople... | Return an error message that is easier to read and more useful.
May require updating if the schemas change significantly. | [
"Return",
"an",
"error",
"message",
"that",
"is",
"easier",
"to",
"read",
"and",
"more",
"useful",
".",
"May",
"require",
"updating",
"if",
"the",
"schemas",
"change",
"significantly",
"."
] | train | https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/errors.py#L71-L252 |
oasis-open/cti-stix-validator | stix2validator/validator.py | _iter_errors_custom | 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... | python | 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... | [
"def",
"_iter_errors_custom",
"(",
"instance",
",",
"checks",
",",
"options",
")",
":",
"# Perform validation",
"for",
"v_function",
"in",
"checks",
":",
"try",
":",
"result",
"=",
"v_function",
"(",
"instance",
")",
"except",
"TypeError",
":",
"result",
"=",
... | 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... | [
"Perform",
"additional",
"validation",
"not",
"possible",
"merely",
"with",
"JSON",
"schemas",
"."
] | train | https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/validator.py#L34-L63 |
oasis-open/cti-stix-validator | stix2validator/validator.py | list_json_files | 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... | python | 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... | [
"def",
"list_json_files",
"(",
"directory",
",",
"recursive",
"=",
"False",
")",
":",
"json_files",
"=",
"[",
"]",
"for",
"top",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"directory",
")",
":",
"dirs",
".",
"sort",
"(",
")",
"# Get pat... | 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`. | [
"Return",
"a",
"list",
"of",
"file",
"paths",
"for",
"JSON",
"files",
"within",
"directory",
"."
] | train | https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/validator.py#L281-L306 |
oasis-open/cti-stix-validator | stix2validator/validator.py | get_json_files | 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... | python | 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... | [
"def",
"get_json_files",
"(",
"files",
",",
"recursive",
"=",
"False",
")",
":",
"json_files",
"=",
"[",
"]",
"if",
"not",
"files",
":",
"return",
"json_files",
"for",
"fn",
"in",
"files",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"fn",
")",
... | 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
... | [
"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",
"... | train | https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/validator.py#L309-L339 |
oasis-open/cti-stix-validator | stix2validator/validator.py | run_validation | 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... | python | 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... | [
"def",
"run_validation",
"(",
"options",
")",
":",
"if",
"options",
".",
"files",
"==",
"sys",
".",
"stdin",
":",
"results",
"=",
"validate",
"(",
"options",
".",
"files",
",",
"options",
")",
"return",
"[",
"FileValidationResults",
"(",
"is_valid",
"=",
... | Validate files based on command line options.
Args:
options: An instance of ``ValidationOptions`` containing options for
this validation run. | [
"Validate",
"files",
"based",
"on",
"command",
"line",
"options",
"."
] | train | https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/validator.py#L342-L360 |
oasis-open/cti-stix-validator | stix2validator/validator.py | validate_parsed_json | 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 ... | python | 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 ... | [
"def",
"validate_parsed_json",
"(",
"obj_json",
",",
"options",
"=",
"None",
")",
":",
"validating_list",
"=",
"isinstance",
"(",
"obj_json",
",",
"list",
")",
"if",
"not",
"options",
":",
"options",
"=",
"ValidationOptions",
"(",
")",
"if",
"not",
"options"... | 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... | [
"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",
"l... | train | https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/validator.py#L363-L408 |
oasis-open/cti-stix-validator | stix2validator/validator.py | validate | 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... | python | 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... | [
"def",
"validate",
"(",
"in_",
",",
"options",
"=",
"None",
")",
":",
"obj_json",
"=",
"json",
".",
"load",
"(",
"in_",
")",
"results",
"=",
"validate_parsed_json",
"(",
"obj_json",
",",
"options",
")",
"return",
"results"
] | 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. | [
"Validate",
"objects",
"from",
"JSON",
"data",
"in",
"a",
"textual",
"stream",
"."
] | train | https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/validator.py#L411-L423 |
oasis-open/cti-stix-validator | stix2validator/validator.py | validate_file | 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... | python | 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... | [
"def",
"validate_file",
"(",
"fn",
",",
"options",
"=",
"None",
")",
":",
"file_results",
"=",
"FileValidationResults",
"(",
"filepath",
"=",
"fn",
")",
"output",
".",
"info",
"(",
"\"Performing JSON schema validation on %s\"",
"%",
"fn",
")",
"if",
"not",
"op... | 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... | [
"Validate",
"the",
"input",
"document",
"fn",
"according",
"to",
"the",
"options",
"passed",
"in",
"."
] | train | https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/validator.py#L426-L467 |
oasis-open/cti-stix-validator | stix2validator/validator.py | validate_string | 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... | python | 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... | [
"def",
"validate_string",
"(",
"string",
",",
"options",
"=",
"None",
")",
":",
"output",
".",
"info",
"(",
"\"Performing JSON schema validation on input string: \"",
"+",
"string",
")",
"stream",
"=",
"io",
".",
"StringIO",
"(",
"string",
")",
"return",
"valida... | 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... | [
"Validate",
"the",
"input",
"string",
"according",
"to",
"the",
"options",
"passed",
"in",
"."
] | train | https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/validator.py#L470-L486 |
oasis-open/cti-stix-validator | stix2validator/validator.py | load_validator | 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... | python | 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... | [
"def",
"load_validator",
"(",
"schema_path",
",",
"schema",
")",
":",
"# Get correct prefix based on OS",
"if",
"os",
".",
"name",
"==",
"'nt'",
":",
"file_prefix",
"=",
"'file:///'",
"else",
":",
"file_prefix",
"=",
"'file:'",
"resolver",
"=",
"RefResolver",
"(... | 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. | [
"Create",
"a",
"JSON",
"schema",
"validator",
"for",
"the",
"given",
"schema",
"."
] | train | https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/validator.py#L489-L509 |
oasis-open/cti-stix-validator | stix2validator/validator.py | find_schema | 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:
... | python | 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:
... | [
"def",
"find_schema",
"(",
"schema_dir",
",",
"obj_type",
")",
":",
"schema_filename",
"=",
"obj_type",
"+",
"'.json'",
"for",
"root",
",",
"dirnames",
",",
"filenames",
"in",
"os",
".",
"walk",
"(",
"schema_dir",
")",
":",
"if",
"schema_filename",
"in",
"... | Search the `schema_dir` directory for a schema called `obj_type`.json.
Return the file path of the first match it finds. | [
"Search",
"the",
"schema_dir",
"directory",
"for",
"a",
"schema",
"called",
"obj_type",
".",
"json",
".",
"Return",
"the",
"file",
"path",
"of",
"the",
"first",
"match",
"it",
"finds",
"."
] | train | https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/validator.py#L512-L520 |
oasis-open/cti-stix-validator | stix2validator/validator.py | load_schema | 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... | python | 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... | [
"def",
"load_schema",
"(",
"schema_path",
")",
":",
"try",
":",
"with",
"open",
"(",
"schema_path",
")",
"as",
"schema_file",
":",
"schema",
"=",
"json",
".",
"load",
"(",
"schema_file",
")",
"except",
"ValueError",
"as",
"e",
":",
"raise",
"SchemaInvalidE... | 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. | [
"Load",
"the",
"JSON",
"schema",
"at",
"the",
"given",
"path",
"as",
"a",
"Python",
"object",
"."
] | train | https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/validator.py#L523-L540 |
oasis-open/cti-stix-validator | stix2validator/validator.py | _get_error_generator | 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... | python | 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... | [
"def",
"_get_error_generator",
"(",
"type",
",",
"obj",
",",
"schema_dir",
"=",
"None",
",",
"version",
"=",
"DEFAULT_VER",
",",
"default",
"=",
"'core'",
")",
":",
"# If no schema directory given, use default for the given STIX version,",
"# which comes bundled with this p... | 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 ... | [
"Get",
"a",
"generator",
"for",
"validating",
"against",
"the",
"schema",
"for",
"the",
"given",
"object",
"type",
"."
] | train | https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/validator.py#L543-L598 |
oasis-open/cti-stix-validator | stix2validator/validator.py | _get_musts | 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_... | python | 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_... | [
"def",
"_get_musts",
"(",
"options",
")",
":",
"if",
"options",
".",
"version",
"==",
"'2.0'",
":",
"return",
"musts20",
".",
"list_musts",
"(",
"options",
")",
"else",
":",
"return",
"musts21",
".",
"list_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. | [
"Return",
"the",
"list",
"of",
"MUST",
"validators",
"for",
"the",
"correct",
"version",
"of",
"STIX",
"."
] | train | https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/validator.py#L601-L611 |
oasis-open/cti-stix-validator | stix2validator/validator.py | _get_shoulds | 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... | python | 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... | [
"def",
"_get_shoulds",
"(",
"options",
")",
":",
"if",
"options",
".",
"version",
"==",
"'2.0'",
":",
"return",
"shoulds20",
".",
"list_shoulds",
"(",
"options",
")",
"else",
":",
"return",
"shoulds21",
".",
"list_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. | [
"Return",
"the",
"list",
"of",
"SHOULD",
"validators",
"for",
"the",
"correct",
"version",
"of",
"STIX",
"."
] | train | https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/validator.py#L614-L624 |
oasis-open/cti-stix-validator | stix2validator/validator.py | _schema_validate | 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
... | python | 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
... | [
"def",
"_schema_validate",
"(",
"sdo",
",",
"options",
")",
":",
"error_gens",
"=",
"[",
"]",
"if",
"'id'",
"in",
"sdo",
":",
"try",
":",
"error_prefix",
"=",
"sdo",
"[",
"'id'",
"]",
"+",
"\": \"",
"except",
"TypeError",
":",
"error_prefix",
"=",
"'un... | 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 ... | [
"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",
"t... | train | https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/validator.py#L627-L692 |
oasis-open/cti-stix-validator | stix2validator/validator.py | validate_instance | 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.
... | python | 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.
... | [
"def",
"validate_instance",
"(",
"instance",
",",
"options",
"=",
"None",
")",
":",
"if",
"'type'",
"not",
"in",
"instance",
":",
"raise",
"ValidationError",
"(",
"\"Input must be an object with a 'type' property.\"",
")",
"if",
"not",
"options",
":",
"options",
"... | 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... | [
"Perform",
"STIX",
"JSON",
"Schema",
"validation",
"against",
"STIX",
"input",
"."
] | train | https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/validator.py#L695-L766 |
oasis-open/cti-stix-validator | stix2validator/validator.py | FileValidationResults.object_result | 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)
... | python | 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)
... | [
"def",
"object_result",
"(",
"self",
")",
":",
"num_obj_results",
"=",
"len",
"(",
"self",
".",
"_object_results",
")",
"if",
"num_obj_results",
"<",
"1",
":",
"return",
"None",
"elif",
"num_obj_results",
"<",
"2",
":",
"return",
"self",
".",
"_object_result... | 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 | [
"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",
... | train | https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/validator.py#L129-L143 |
oasis-open/cti-stix-validator | stix2validator/validator.py | FileValidationResults.object_results | 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... | python | 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... | [
"def",
"object_results",
"(",
"self",
",",
"object_results",
")",
":",
"if",
"_is_iterable_non_string",
"(",
"object_results",
")",
":",
"self",
".",
"_object_results",
"=",
"list",
"(",
"object_results",
")",
"elif",
"object_results",
"is",
"None",
":",
"self",... | 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 | [
"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",... | train | https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/validator.py#L167-L179 |
oasis-open/cti-stix-validator | stix2validator/validator.py | ObjectValidationResults.as_dict | 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... | python | 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... | [
"def",
"as_dict",
"(",
"self",
")",
":",
"d",
"=",
"super",
"(",
"ObjectValidationResults",
",",
"self",
")",
".",
"as_dict",
"(",
")",
"if",
"self",
".",
"errors",
":",
"d",
"[",
"'errors'",
"]",
"=",
"[",
"x",
".",
"as_dict",
"(",
")",
"for",
"... | 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... | [
"A",
"dictionary",
"representation",
"of",
"the",
":",
"class",
":",
".",
"ObjectValidationResults",
"instance",
"."
] | train | https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/validator.py#L226-L243 |
oasis-open/cti-stix-validator | stix2validator/v21/shoulds.py | custom_prefix_strict | 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),
... | python | 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),
... | [
"def",
"custom_prefix_strict",
"(",
"instance",
")",
":",
"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. | [
"Ensure",
"custom",
"content",
"follows",
"strict",
"naming",
"style",
"conventions",
"."
] | train | https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L32-L40 |
oasis-open/cti-stix-validator | stix2validator/v21/shoulds.py | custom_prefix_lax | 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... | python | 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... | [
"def",
"custom_prefix_lax",
"(",
"instance",
")",
":",
"for",
"error",
"in",
"chain",
"(",
"custom_object_prefix_lax",
"(",
"instance",
")",
",",
"custom_property_prefix_lax",
"(",
"instance",
")",
",",
"custom_observable_object_prefix_lax",
"(",
"instance",
")",
",... | Ensure custom content follows lenient naming style conventions
for forward-compatibility. | [
"Ensure",
"custom",
"content",
"follows",
"lenient",
"naming",
"style",
"conventions",
"for",
"forward",
"-",
"compatibility",
"."
] | train | https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L43-L52 |
oasis-open/cti-stix-validator | stix2validator/v21/shoulds.py | custom_object_prefix_strict | 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("... | python | 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("... | [
"def",
"custom_object_prefix_strict",
"(",
"instance",
")",
":",
"if",
"(",
"instance",
"[",
"'type'",
"]",
"not",
"in",
"enums",
".",
"TYPES",
"and",
"instance",
"[",
"'type'",
"]",
"not",
"in",
"enums",
".",
"RESERVED_OBJECTS",
"and",
"not",
"CUSTOM_TYPE_P... | Ensure custom objects follow strict naming style conventions. | [
"Ensure",
"custom",
"objects",
"follow",
"strict",
"naming",
"style",
"conventions",
"."
] | train | https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L55-L65 |
oasis-open/cti-stix-validator | stix2validator/v21/shoulds.py | custom_object_prefix_lax | 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... | python | 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... | [
"def",
"custom_object_prefix_lax",
"(",
"instance",
")",
":",
"if",
"(",
"instance",
"[",
"'type'",
"]",
"not",
"in",
"enums",
".",
"TYPES",
"and",
"instance",
"[",
"'type'",
"]",
"not",
"in",
"enums",
".",
"RESERVED_OBJECTS",
"and",
"not",
"CUSTOM_TYPE_LAX_... | Ensure custom objects follow lenient naming style conventions
for forward-compatibility. | [
"Ensure",
"custom",
"objects",
"follow",
"lenient",
"naming",
"style",
"conventions",
"for",
"forward",
"-",
"compatibility",
"."
] | train | https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L68-L78 |
oasis-open/cti-stix-validator | stix2validator/v21/shoulds.py | custom_property_prefix_strict | 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[... | python | 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[... | [
"def",
"custom_property_prefix_strict",
"(",
"instance",
")",
":",
"for",
"prop_name",
"in",
"instance",
".",
"keys",
"(",
")",
":",
"if",
"(",
"instance",
"[",
"'type'",
"]",
"in",
"enums",
".",
"PROPERTIES",
"and",
"prop_name",
"not",
"in",
"enums",
".",... | Ensure custom properties follow strict naming style conventions.
Does not check property names in custom objects. | [
"Ensure",
"custom",
"properties",
"follow",
"strict",
"naming",
"style",
"conventions",
"."
] | train | https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L81-L97 |
oasis-open/cti-stix-validator | stix2validator/v21/shoulds.py | custom_property_prefix_lax | 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... | python | 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... | [
"def",
"custom_property_prefix_lax",
"(",
"instance",
")",
":",
"for",
"prop_name",
"in",
"instance",
".",
"keys",
"(",
")",
":",
"if",
"(",
"instance",
"[",
"'type'",
"]",
"in",
"enums",
".",
"PROPERTIES",
"and",
"prop_name",
"not",
"in",
"enums",
".",
... | Ensure custom properties follow lenient naming style conventions
for forward-compatibility.
Does not check property names in custom objects. | [
"Ensure",
"custom",
"properties",
"follow",
"lenient",
"naming",
"style",
"conventions",
"for",
"forward",
"-",
"compatibility",
"."
] | train | https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L100-L116 |
oasis-open/cti-stix-validator | stix2validator/v21/shoulds.py | open_vocab_values | 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... | python | 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... | [
"def",
"open_vocab_values",
"(",
"instance",
")",
":",
"if",
"instance",
"[",
"'type'",
"]",
"not",
"in",
"enums",
".",
"VOCAB_PROPERTIES",
":",
"return",
"properties",
"=",
"enums",
".",
"VOCAB_PROPERTIES",
"[",
"instance",
"[",
"'type'",
"]",
"]",
"for",
... | 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. | [
"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",
"."
] | train | https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L119-L142 |
oasis-open/cti-stix-validator | stix2validator/v21/shoulds.py | kill_chain_phase_names | 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']:... | python | 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']:... | [
"def",
"kill_chain_phase_names",
"(",
"instance",
")",
":",
"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. | [
"Ensure",
"the",
"kill_chain_name",
"and",
"phase_name",
"properties",
"of",
"kill_chain_phase",
"objects",
"follow",
"naming",
"style",
"conventions",
"."
] | train | https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L145-L168 |
oasis-open/cti-stix-validator | stix2validator/v21/shoulds.py | check_vocab | 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... | python | 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... | [
"def",
"check_vocab",
"(",
"instance",
",",
"vocab",
",",
"code",
")",
":",
"vocab_uses",
"=",
"getattr",
"(",
"enums",
",",
"vocab",
"+",
"\"_USES\"",
")",
"for",
"k",
"in",
"vocab_uses",
".",
"keys",
"(",
")",
":",
"if",
"instance",
"[",
"'type'",
... | 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. | [
"Ensure",
"that",
"the",
"open",
"vocabulary",
"specified",
"by",
"vocab",
"is",
"used",
"properly",
"."
] | train | https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L171-L195 |
oasis-open/cti-stix-validator | stix2validator/v21/shoulds.py | vocab_marking_definition | 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... | python | 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... | [
"def",
"vocab_marking_definition",
"(",
"instance",
")",
":",
"if",
"(",
"instance",
"[",
"'type'",
"]",
"==",
"'marking-definition'",
"and",
"'definition_type'",
"in",
"instance",
"and",
"not",
"instance",
"[",
"'definition_type'",
"]",
"in",
"enums",
".",
"MAR... | Ensure that the `definition_type` property of `marking-definition`
objects is one of the values in the STIX 2.0 specification. | [
"Ensure",
"that",
"the",
"definition_type",
"property",
"of",
"marking",
"-",
"definition",
"objects",
"is",
"one",
"of",
"the",
"values",
"in",
"the",
"STIX",
"2",
".",
"0",
"specification",
"."
] | train | https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L258-L268 |
oasis-open/cti-stix-validator | stix2validator/v21/shoulds.py | relationships_strict | 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... | python | 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... | [
"def",
"relationships_strict",
"(",
"instance",
")",
":",
"# Don't check objects that aren't relationships or that are custom objects",
"if",
"(",
"instance",
"[",
"'type'",
"]",
"!=",
"'relationship'",
"or",
"instance",
"[",
"'type'",
"]",
"not",
"in",
"enums",
".",
... | Ensure that only the relationship types defined in the specification are
used. | [
"Ensure",
"that",
"only",
"the",
"relationship",
"types",
"defined",
"in",
"the",
"specification",
"are",
"used",
"."
] | train | https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L271-L315 |
oasis-open/cti-stix-validator | stix2validator/v21/shoulds.py | valid_hash_value | 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... | python | 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... | [
"def",
"valid_hash_value",
"(",
"hashname",
")",
":",
"custom_hash_prefix_re",
"=",
"re",
".",
"compile",
"(",
"r\"^x_\"",
")",
"if",
"hashname",
"in",
"enums",
".",
"HASH_ALGO_OV",
"or",
"custom_hash_prefix_re",
".",
"match",
"(",
"hashname",
")",
":",
"retur... | Return true if given value is a valid, recommended hash name according
to the STIX 2 specification. | [
"Return",
"true",
"if",
"given",
"value",
"is",
"a",
"valid",
"recommended",
"hash",
"name",
"according",
"to",
"the",
"STIX",
"2",
"specification",
"."
] | train | https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L318-L326 |
oasis-open/cti-stix-validator | stix2validator/v21/shoulds.py | vocab_hash_algo | 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... | python | 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... | [
"def",
"vocab_hash_algo",
"(",
"instance",
")",
":",
"for",
"key",
",",
"obj",
"in",
"instance",
"[",
"'objects'",
"]",
".",
"items",
"(",
")",
":",
"if",
"'type'",
"not",
"in",
"obj",
":",
"continue",
"if",
"obj",
"[",
"'type'",
"]",
"==",
"'file'",... | Ensure objects with 'hashes' properties only use values from the
hash-algo-ov vocabulary. | [
"Ensure",
"objects",
"with",
"hashes",
"properties",
"only",
"use",
"values",
"from",
"the",
"hash",
"-",
"algo",
"-",
"ov",
"vocabulary",
"."
] | train | https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L330-L427 |
oasis-open/cti-stix-validator | stix2validator/v21/shoulds.py | vocab_windows_pebinary_type | 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:
... | python | 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:
... | [
"def",
"vocab_windows_pebinary_type",
"(",
"instance",
")",
":",
"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. | [
"Ensure",
"file",
"objects",
"with",
"the",
"windows",
"-",
"pebinary",
"-",
"ext",
"extension",
"have",
"a",
"pe",
"-",
"type",
"property",
"that",
"is",
"from",
"the",
"windows",
"-",
"pebinary",
"-",
"type",
"-",
"ov",
"vocabulary",
"."
] | train | https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L431-L446 |
oasis-open/cti-stix-validator | stix2validator/v21/shoulds.py | vocab_account_type | 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'... | python | 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'... | [
"def",
"vocab_account_type",
"(",
"instance",
")",
":",
"for",
"key",
",",
"obj",
"in",
"instance",
"[",
"'objects'",
"]",
".",
"items",
"(",
")",
":",
"if",
"'type'",
"in",
"obj",
"and",
"obj",
"[",
"'type'",
"]",
"==",
"'user-account'",
":",
"try",
... | Ensure a user-account objects' 'account-type' property is from the
account-type-ov vocabulary. | [
"Ensure",
"a",
"user",
"-",
"account",
"objects",
"account",
"-",
"type",
"property",
"is",
"from",
"the",
"account",
"-",
"type",
"-",
"ov",
"vocabulary",
"."
] | train | https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L450-L464 |
oasis-open/cti-stix-validator | stix2validator/v21/shoulds.py | observable_object_keys | 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 "
... | python | 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 "
... | [
"def",
"observable_object_keys",
"(",
"instance",
")",
":",
"digits_re",
"=",
"re",
".",
"compile",
"(",
"r\"^\\d+$\"",
")",
"for",
"key",
"in",
"instance",
"[",
"'objects'",
"]",
":",
"if",
"not",
"digits_re",
".",
"match",
"(",
"key",
")",
":",
"yield"... | Ensure observable-objects keys are non-negative integers. | [
"Ensure",
"observable",
"-",
"objects",
"keys",
"are",
"non",
"-",
"negative",
"integers",
"."
] | train | https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L468-L476 |
oasis-open/cti-stix-validator | stix2validator/v21/shoulds.py | custom_observable_object_prefix_strict | 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... | python | 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... | [
"def",
"custom_observable_object_prefix_strict",
"(",
"instance",
")",
":",
"for",
"key",
",",
"obj",
"in",
"instance",
"[",
"'objects'",
"]",
".",
"items",
"(",
")",
":",
"if",
"(",
"'type'",
"in",
"obj",
"and",
"obj",
"[",
"'type'",
"]",
"not",
"in",
... | Ensure custom observable objects follow strict naming style conventions. | [
"Ensure",
"custom",
"observable",
"objects",
"follow",
"strict",
"naming",
"style",
"conventions",
"."
] | train | https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L504-L516 |
oasis-open/cti-stix-validator | stix2validator/v21/shoulds.py | custom_observable_object_prefix_lax | 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... | python | 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... | [
"def",
"custom_observable_object_prefix_lax",
"(",
"instance",
")",
":",
"for",
"key",
",",
"obj",
"in",
"instance",
"[",
"'objects'",
"]",
".",
"items",
"(",
")",
":",
"if",
"(",
"'type'",
"in",
"obj",
"and",
"obj",
"[",
"'type'",
"]",
"not",
"in",
"e... | Ensure custom observable objects follow naming style conventions. | [
"Ensure",
"custom",
"observable",
"objects",
"follow",
"naming",
"style",
"conventions",
"."
] | train | https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L520-L530 |
oasis-open/cti-stix-validator | stix2validator/v21/shoulds.py | custom_object_extension_prefix_strict | 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... | python | 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... | [
"def",
"custom_object_extension_prefix_strict",
"(",
"instance",
")",
":",
"for",
"key",
",",
"obj",
"in",
"instance",
"[",
"'objects'",
"]",
".",
"items",
"(",
")",
":",
"if",
"not",
"(",
"'extensions'",
"in",
"obj",
"and",
"'type'",
"in",
"obj",
"and",
... | Ensure custom observable object extensions follow strict naming style
conventions. | [
"Ensure",
"custom",
"observable",
"object",
"extensions",
"follow",
"strict",
"naming",
"style",
"conventions",
"."
] | train | https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L534-L550 |
oasis-open/cti-stix-validator | stix2validator/v21/shoulds.py | custom_object_extension_prefix_lax | 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):
... | python | 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):
... | [
"def",
"custom_object_extension_prefix_lax",
"(",
"instance",
")",
":",
"for",
"key",
",",
"obj",
"in",
"instance",
"[",
"'objects'",
"]",
".",
"items",
"(",
")",
":",
"if",
"not",
"(",
"'extensions'",
"in",
"obj",
"and",
"'type'",
"in",
"obj",
"and",
"o... | Ensure custom observable object extensions follow naming style
conventions. | [
"Ensure",
"custom",
"observable",
"object",
"extensions",
"follow",
"naming",
"style",
"conventions",
"."
] | train | https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L554-L568 |
oasis-open/cti-stix-validator | stix2validator/v21/shoulds.py | custom_observable_properties_prefix_strict | 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:
... | python | 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:
... | [
"def",
"custom_observable_properties_prefix_strict",
"(",
"instance",
")",
":",
"for",
"key",
",",
"obj",
"in",
"instance",
"[",
"'objects'",
"]",
".",
"items",
"(",
")",
":",
"if",
"'type'",
"not",
"in",
"obj",
":",
"continue",
"type_",
"=",
"obj",
"[",
... | Ensure observable object custom properties follow strict naming style
conventions. | [
"Ensure",
"observable",
"object",
"custom",
"properties",
"follow",
"strict",
"naming",
"style",
"conventions",
"."
] | train | https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L572-L657 |
oasis-open/cti-stix-validator | stix2validator/v21/shoulds.py | network_traffic_ports | 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 ... | python | 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 ... | [
"def",
"network_traffic_ports",
"(",
"instance",
")",
":",
"for",
"key",
",",
"obj",
"in",
"instance",
"[",
"'objects'",
"]",
".",
"items",
"(",
")",
":",
"if",
"(",
"'type'",
"in",
"obj",
"and",
"obj",
"[",
"'type'",
"]",
"==",
"'network-traffic'",
"a... | Ensure network-traffic objects contain both src_port and dst_port. | [
"Ensure",
"network",
"-",
"traffic",
"objects",
"contain",
"both",
"src_port",
"and",
"dst_port",
"."
] | train | https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L733-L741 |
oasis-open/cti-stix-validator | stix2validator/v21/shoulds.py | mime_type | 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, ... | python | 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, ... | [
"def",
"mime_type",
"(",
"instance",
")",
":",
"mime_pattern",
"=",
"re",
".",
"compile",
"(",
"r'^(application|audio|font|image|message|model'",
"'|multipart|text|video)/[a-zA-Z0-9.+_-]+'",
")",
"for",
"key",
",",
"obj",
"in",
"instance",
"[",
"'objects'",
"]",
".",
... | Ensure the 'mime_type' property of file objects comes from the Template
column in the IANA media type registry. | [
"Ensure",
"the",
"mime_type",
"property",
"of",
"file",
"objects",
"comes",
"from",
"the",
"Template",
"column",
"in",
"the",
"IANA",
"media",
"type",
"registry",
"."
] | train | https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L745-L767 |
oasis-open/cti-stix-validator | stix2validator/v21/shoulds.py | protocols | 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
... | python | 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
... | [
"def",
"protocols",
"(",
"instance",
")",
":",
"for",
"key",
",",
"obj",
"in",
"instance",
"[",
"'objects'",
"]",
".",
"items",
"(",
")",
":",
"if",
"(",
"'type'",
"in",
"obj",
"and",
"obj",
"[",
"'type'",
"]",
"==",
"'network-traffic'",
"and",
"'pro... | Ensure the 'protocols' property of network-traffic objects contains only
values from the IANA Service Name and Transport Protocol Port Number
Registry. | [
"Ensure",
"the",
"protocols",
"property",
"of",
"network",
"-",
"traffic",
"objects",
"contains",
"only",
"values",
"from",
"the",
"IANA",
"Service",
"Name",
"and",
"Transport",
"Protocol",
"Port",
"Number",
"Registry",
"."
] | train | https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L771-L796 |
oasis-open/cti-stix-validator | stix2validator/v21/shoulds.py | ipfix | 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['... | python | 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['... | [
"def",
"ipfix",
"(",
"instance",
")",
":",
"ipf_pattern",
"=",
"re",
".",
"compile",
"(",
"r'^[a-z][a-zA-Z0-9]+'",
")",
"for",
"key",
",",
"obj",
"in",
"instance",
"[",
"'objects'",
"]",
".",
"items",
"(",
")",
":",
"if",
"(",
"'type'",
"in",
"obj",
... | Ensure the 'ipfix' property of network-traffic objects contains only
values from the IANA IP Flow Information Export (IPFIX) Entities Registry. | [
"Ensure",
"the",
"ipfix",
"property",
"of",
"network",
"-",
"traffic",
"objects",
"contains",
"only",
"values",
"from",
"the",
"IANA",
"IP",
"Flow",
"Information",
"Export",
"(",
"IPFIX",
")",
"Entities",
"Registry",
"."
] | train | https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L800-L825 |
oasis-open/cti-stix-validator | stix2validator/v21/shoulds.py | http_request_headers | 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... | python | 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... | [
"def",
"http_request_headers",
"(",
"instance",
")",
":",
"for",
"key",
",",
"obj",
"in",
"instance",
"[",
"'objects'",
"]",
".",
"items",
"(",
")",
":",
"if",
"(",
"'type'",
"in",
"obj",
"and",
"obj",
"[",
"'type'",
"]",
"==",
"'network-traffic'",
")"... | 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... | [
"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",
... | train | https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L829-L850 |
oasis-open/cti-stix-validator | stix2validator/v21/shoulds.py | socket_options | 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:
... | python | 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:
... | [
"def",
"socket_options",
"(",
"instance",
")",
":",
"for",
"key",
",",
"obj",
"in",
"instance",
"[",
"'objects'",
"]",
".",
"items",
"(",
")",
":",
"if",
"(",
"'type'",
"in",
"obj",
"and",
"obj",
"[",
"'type'",
"]",
"==",
"'network-traffic'",
")",
":... | Ensure the keys of the 'options' property of the socket-ext extension of
network-traffic objects are only valid socket options (SO_*). | [
"Ensure",
"the",
"keys",
"of",
"the",
"options",
"property",
"of",
"the",
"socket",
"-",
"ext",
"extension",
"of",
"network",
"-",
"traffic",
"objects",
"are",
"only",
"valid",
"socket",
"options",
"(",
"SO_",
"*",
")",
"."
] | train | https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L854-L870 |
oasis-open/cti-stix-validator | stix2validator/v21/shoulds.py | pdf_doc_info | 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... | python | 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... | [
"def",
"pdf_doc_info",
"(",
"instance",
")",
":",
"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. | [
"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",
"."
] | train | https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L874-L893 |
oasis-open/cti-stix-validator | stix2validator/v21/shoulds.py | countries | 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`... | python | 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`... | [
"def",
"countries",
"(",
"instance",
")",
":",
"if",
"(",
"instance",
"[",
"'type'",
"]",
"==",
"'location'",
"and",
"'country'",
"in",
"instance",
"and",
"not",
"instance",
"[",
"'country'",
"]",
".",
"upper",
"(",
")",
"in",
"enums",
".",
"COUNTRY_CODE... | Ensure that the `country` property of `location` objects is a valid
ISO 3166-1 ALPHA-2 Code. | [
"Ensure",
"that",
"the",
"country",
"property",
"of",
"location",
"objects",
"is",
"a",
"valid",
"ISO",
"3166",
"-",
"1",
"ALPHA",
"-",
"2",
"Code",
"."
] | train | https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L896-L905 |
oasis-open/cti-stix-validator | stix2validator/v21/shoulds.py | windows_process_priority_format | 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... | python | 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... | [
"def",
"windows_process_priority_format",
"(",
"instance",
")",
":",
"class_suffix_re",
"=",
"re",
".",
"compile",
"(",
"r'.+_CLASS$'",
")",
"for",
"key",
",",
"obj",
"in",
"instance",
"[",
"'objects'",
"]",
".",
"items",
"(",
")",
":",
"if",
"'type'",
"in... | Ensure the 'priority' property of windows-process-ext ends in '_CLASS'. | [
"Ensure",
"the",
"priority",
"property",
"of",
"windows",
"-",
"process",
"-",
"ext",
"ends",
"in",
"_CLASS",
"."
] | train | https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L909-L922 |
oasis-open/cti-stix-validator | stix2validator/v21/shoulds.py | hash_length | 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']
... | python | 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']
... | [
"def",
"hash_length",
"(",
"instance",
")",
":",
"for",
"key",
",",
"obj",
"in",
"instance",
"[",
"'objects'",
"]",
".",
"items",
"(",
")",
":",
"if",
"'type'",
"not",
"in",
"obj",
":",
"continue",
"if",
"obj",
"[",
"'type'",
"]",
"==",
"'file'",
"... | Ensure keys in 'hashes'-type properties are no more than 30 characters long. | [
"Ensure",
"keys",
"in",
"hashes",
"-",
"type",
"properties",
"are",
"no",
"more",
"than",
"30",
"characters",
"long",
"."
] | train | https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L926-L1016 |
oasis-open/cti-stix-validator | stix2validator/v21/shoulds.py | duplicate_ids | 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... | python | 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... | [
"def",
"duplicate_ids",
"(",
"instance",
")",
":",
"if",
"instance",
"[",
"'type'",
"]",
"!=",
"'bundle'",
"or",
"'objects'",
"not",
"in",
"instance",
":",
"return",
"unique_ids",
"=",
"{",
"}",
"for",
"obj",
"in",
"instance",
"[",
"'objects'",
"]",
":",... | Ensure objects with duplicate IDs have different `modified` timestamps. | [
"Ensure",
"objects",
"with",
"duplicate",
"IDs",
"have",
"different",
"modified",
"timestamps",
"."
] | train | https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L1028-L1044 |
oasis-open/cti-stix-validator | stix2validator/v21/shoulds.py | list_shoulds | 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... | python | 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... | [
"def",
"list_shoulds",
"(",
"options",
")",
":",
"validator_list",
"=",
"[",
"]",
"# Default: enable all",
"if",
"not",
"options",
".",
"disabled",
"and",
"not",
"options",
".",
"enabled",
":",
"validator_list",
".",
"extend",
"(",
"CHECKS",
"[",
"'all'",
"]... | Construct the list of 'SHOULD' validators to be run by the validator. | [
"Construct",
"the",
"list",
"of",
"SHOULD",
"validators",
"to",
"be",
"run",
"by",
"the",
"validator",
"."
] | train | https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L1193-L1298 |
oasis-open/cti-stix-validator | stix2validator/v20/musts.py | timestamp | 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... | python | 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... | [
"def",
"timestamp",
"(",
"instance",
")",
":",
"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'",
"... | Ensure timestamps contain sane months, days, hours, minutes, seconds. | [
"Ensure",
"timestamps",
"contain",
"sane",
"months",
"days",
"hours",
"minutes",
"seconds",
"."
] | train | https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v20/musts.py#L23-L70 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.