repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
scoutapp/scout_apm_python | src/scout_apm/core/socket.py | CoreAgentSocket.run | def run(self):
"""
Called by the threading system
"""
try:
self._connect()
self._register()
while True:
try:
body = self.command_queue.get(block=True, timeout=1 * SECOND)
except queue.Empty:
... | python | def run(self):
"""
Called by the threading system
"""
try:
self._connect()
self._register()
while True:
try:
body = self.command_queue.get(block=True, timeout=1 * SECOND)
except queue.Empty:
... | [
"def",
"run",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"_connect",
"(",
")",
"self",
".",
"_register",
"(",
")",
"while",
"True",
":",
"try",
":",
"body",
"=",
"self",
".",
"command_queue",
".",
"get",
"(",
"block",
"=",
"True",
",",
"time... | Called by the threading system | [
"Called",
"by",
"the",
"threading",
"system"
] | e5539ee23b8129be9b75d5007c88b6158b51294f | https://github.com/scoutapp/scout_apm_python/blob/e5539ee23b8129be9b75d5007c88b6158b51294f/src/scout_apm/core/socket.py#L95-L132 | train |
scoutapp/scout_apm_python | src/scout_apm/core/config.py | ScoutConfig.set | def set(cls, **kwargs):
"""
Sets a configuration value for the Scout agent. Values set here will
not override values set in ENV.
"""
global SCOUT_PYTHON_VALUES
for key, value in kwargs.items():
SCOUT_PYTHON_VALUES[key] = value | python | def set(cls, **kwargs):
"""
Sets a configuration value for the Scout agent. Values set here will
not override values set in ENV.
"""
global SCOUT_PYTHON_VALUES
for key, value in kwargs.items():
SCOUT_PYTHON_VALUES[key] = value | [
"def",
"set",
"(",
"cls",
",",
"*",
"*",
"kwargs",
")",
":",
"global",
"SCOUT_PYTHON_VALUES",
"for",
"key",
",",
"value",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"SCOUT_PYTHON_VALUES",
"[",
"key",
"]",
"=",
"value"
] | Sets a configuration value for the Scout agent. Values set here will
not override values set in ENV. | [
"Sets",
"a",
"configuration",
"value",
"for",
"the",
"Scout",
"agent",
".",
"Values",
"set",
"here",
"will",
"not",
"override",
"values",
"set",
"in",
"ENV",
"."
] | e5539ee23b8129be9b75d5007c88b6158b51294f | https://github.com/scoutapp/scout_apm_python/blob/e5539ee23b8129be9b75d5007c88b6158b51294f/src/scout_apm/core/config.py#L91-L98 | train |
scoutapp/scout_apm_python | src/scout_apm/api/__init__.py | text | def text(value, encoding="utf-8", errors="strict"):
"""Convert a value to str on Python 3 and unicode on Python 2."""
if isinstance(value, text_type):
return value
elif isinstance(value, bytes):
return text_type(value, encoding, errors)
else:
return text_type(value) | python | def text(value, encoding="utf-8", errors="strict"):
"""Convert a value to str on Python 3 and unicode on Python 2."""
if isinstance(value, text_type):
return value
elif isinstance(value, bytes):
return text_type(value, encoding, errors)
else:
return text_type(value) | [
"def",
"text",
"(",
"value",
",",
"encoding",
"=",
"\"utf-8\"",
",",
"errors",
"=",
"\"strict\"",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"text_type",
")",
":",
"return",
"value",
"elif",
"isinstance",
"(",
"value",
",",
"bytes",
")",
":",
"re... | Convert a value to str on Python 3 and unicode on Python 2. | [
"Convert",
"a",
"value",
"to",
"str",
"on",
"Python",
"3",
"and",
"unicode",
"on",
"Python",
"2",
"."
] | e5539ee23b8129be9b75d5007c88b6158b51294f | https://github.com/scoutapp/scout_apm_python/blob/e5539ee23b8129be9b75d5007c88b6158b51294f/src/scout_apm/api/__init__.py#L35-L42 | train |
scoutapp/scout_apm_python | src/scout_apm/django/instruments/sql.py | SQLInstrument.install | def install():
"""
Installs ScoutApm SQL Instrumentation by monkeypatching the `cursor`
method of BaseDatabaseWrapper, to return a wrapper that instruments any
calls going through it.
"""
@monkeypatch_method(BaseDatabaseWrapper)
def cursor(original, self, *args, ... | python | def install():
"""
Installs ScoutApm SQL Instrumentation by monkeypatching the `cursor`
method of BaseDatabaseWrapper, to return a wrapper that instruments any
calls going through it.
"""
@monkeypatch_method(BaseDatabaseWrapper)
def cursor(original, self, *args, ... | [
"def",
"install",
"(",
")",
":",
"@",
"monkeypatch_method",
"(",
"BaseDatabaseWrapper",
")",
"def",
"cursor",
"(",
"original",
",",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"original",
"(",
"*",
"args",
",",
"*",
"*... | Installs ScoutApm SQL Instrumentation by monkeypatching the `cursor`
method of BaseDatabaseWrapper, to return a wrapper that instruments any
calls going through it. | [
"Installs",
"ScoutApm",
"SQL",
"Instrumentation",
"by",
"monkeypatching",
"the",
"cursor",
"method",
"of",
"BaseDatabaseWrapper",
"to",
"return",
"a",
"wrapper",
"that",
"instruments",
"any",
"calls",
"going",
"through",
"it",
"."
] | e5539ee23b8129be9b75d5007c88b6158b51294f | https://github.com/scoutapp/scout_apm_python/blob/e5539ee23b8129be9b75d5007c88b6158b51294f/src/scout_apm/django/instruments/sql.py#L53-L65 | train |
scoutapp/scout_apm_python | src/scout_apm/flask/__init__.py | ScoutApm.dispatch_request | def dispatch_request(self):
"""Modified version of Flask.dispatch_request to call process_view."""
req = _request_ctx_stack.top.request
app = current_app
# Return flask's default options response. See issue #40
if req.method == "OPTIONS":
return app.make_default_opt... | python | def dispatch_request(self):
"""Modified version of Flask.dispatch_request to call process_view."""
req = _request_ctx_stack.top.request
app = current_app
# Return flask's default options response. See issue #40
if req.method == "OPTIONS":
return app.make_default_opt... | [
"def",
"dispatch_request",
"(",
"self",
")",
":",
"req",
"=",
"_request_ctx_stack",
".",
"top",
".",
"request",
"app",
"=",
"current_app",
"# Return flask's default options response. See issue #40",
"if",
"req",
".",
"method",
"==",
"\"OPTIONS\"",
":",
"return",
"ap... | Modified version of Flask.dispatch_request to call process_view. | [
"Modified",
"version",
"of",
"Flask",
".",
"dispatch_request",
"to",
"call",
"process_view",
"."
] | e5539ee23b8129be9b75d5007c88b6158b51294f | https://github.com/scoutapp/scout_apm_python/blob/e5539ee23b8129be9b75d5007c88b6158b51294f/src/scout_apm/flask/__init__.py#L54-L76 | train |
scoutapp/scout_apm_python | src/scout_apm/flask/__init__.py | ScoutApm.wrap_view_func | def wrap_view_func(self, app, rule, req, view_func, view_kwargs):
""" This method is called just before the flask view is called.
This is done by the dispatch_request method.
"""
operation = view_func.__module__ + "." + view_func.__name__
return self.trace_view_function(
... | python | def wrap_view_func(self, app, rule, req, view_func, view_kwargs):
""" This method is called just before the flask view is called.
This is done by the dispatch_request method.
"""
operation = view_func.__module__ + "." + view_func.__name__
return self.trace_view_function(
... | [
"def",
"wrap_view_func",
"(",
"self",
",",
"app",
",",
"rule",
",",
"req",
",",
"view_func",
",",
"view_kwargs",
")",
":",
"operation",
"=",
"view_func",
".",
"__module__",
"+",
"\".\"",
"+",
"view_func",
".",
"__name__",
"return",
"self",
".",
"trace_view... | This method is called just before the flask view is called.
This is done by the dispatch_request method. | [
"This",
"method",
"is",
"called",
"just",
"before",
"the",
"flask",
"view",
"is",
"called",
".",
"This",
"is",
"done",
"by",
"the",
"dispatch_request",
"method",
"."
] | e5539ee23b8129be9b75d5007c88b6158b51294f | https://github.com/scoutapp/scout_apm_python/blob/e5539ee23b8129be9b75d5007c88b6158b51294f/src/scout_apm/flask/__init__.py#L81-L88 | train |
scoutapp/scout_apm_python | src/scout_apm/django/middleware.py | ViewTimingMiddleware.process_view | def process_view(self, request, view_func, view_args, view_kwargs):
"""
Capture details about the view_func that is about to execute
"""
try:
if ignore_path(request.path):
TrackedRequest.instance().tag("ignore_transaction", True)
view_name = reque... | python | def process_view(self, request, view_func, view_args, view_kwargs):
"""
Capture details about the view_func that is about to execute
"""
try:
if ignore_path(request.path):
TrackedRequest.instance().tag("ignore_transaction", True)
view_name = reque... | [
"def",
"process_view",
"(",
"self",
",",
"request",
",",
"view_func",
",",
"view_args",
",",
"view_kwargs",
")",
":",
"try",
":",
"if",
"ignore_path",
"(",
"request",
".",
"path",
")",
":",
"TrackedRequest",
".",
"instance",
"(",
")",
".",
"tag",
"(",
... | Capture details about the view_func that is about to execute | [
"Capture",
"details",
"about",
"the",
"view_func",
"that",
"is",
"about",
"to",
"execute"
] | e5539ee23b8129be9b75d5007c88b6158b51294f | https://github.com/scoutapp/scout_apm_python/blob/e5539ee23b8129be9b75d5007c88b6158b51294f/src/scout_apm/django/middleware.py#L67-L84 | train |
F-Secure/see | see/context/resources/network.py | create | def create(hypervisor, identifier, configuration):
"""Creates a virtual network according to the given configuration.
@param hypervisor: (libvirt.virConnect) connection to libvirt hypervisor.
@param identifier: (str) UUID for the virtual network.
@param configuration: (dict) network configuration.
... | python | def create(hypervisor, identifier, configuration):
"""Creates a virtual network according to the given configuration.
@param hypervisor: (libvirt.virConnect) connection to libvirt hypervisor.
@param identifier: (str) UUID for the virtual network.
@param configuration: (dict) network configuration.
... | [
"def",
"create",
"(",
"hypervisor",
",",
"identifier",
",",
"configuration",
")",
":",
"counter",
"=",
"count",
"(",
")",
"xml_config",
"=",
"DEFAULT_NETWORK_XML",
"if",
"not",
"{",
"'configuration'",
",",
"'dynamic_address'",
"}",
"&",
"set",
"(",
"configurat... | Creates a virtual network according to the given configuration.
@param hypervisor: (libvirt.virConnect) connection to libvirt hypervisor.
@param identifier: (str) UUID for the virtual network.
@param configuration: (dict) network configuration.
@return: (libvirt.virNetwork) virtual network. | [
"Creates",
"a",
"virtual",
"network",
"according",
"to",
"the",
"given",
"configuration",
"."
] | 3e053e52a45229f96a12db9e98caf7fb3880e811 | https://github.com/F-Secure/see/blob/3e053e52a45229f96a12db9e98caf7fb3880e811/see/context/resources/network.py#L72-L108 | train |
F-Secure/see | see/context/resources/network.py | lookup | def lookup(domain):
"""Find the virNetwork object associated to the domain.
If the domain has more than one network interface,
the first one is returned.
None is returned if the domain is not attached to any network.
"""
xml = domain.XMLDesc(0)
element = etree.fromstring(xml)
subelm = ... | python | def lookup(domain):
"""Find the virNetwork object associated to the domain.
If the domain has more than one network interface,
the first one is returned.
None is returned if the domain is not attached to any network.
"""
xml = domain.XMLDesc(0)
element = etree.fromstring(xml)
subelm = ... | [
"def",
"lookup",
"(",
"domain",
")",
":",
"xml",
"=",
"domain",
".",
"XMLDesc",
"(",
"0",
")",
"element",
"=",
"etree",
".",
"fromstring",
"(",
"xml",
")",
"subelm",
"=",
"element",
".",
"find",
"(",
"'.//interface[@type=\"network\"]'",
")",
"if",
"subel... | Find the virNetwork object associated to the domain.
If the domain has more than one network interface,
the first one is returned.
None is returned if the domain is not attached to any network. | [
"Find",
"the",
"virNetwork",
"object",
"associated",
"to",
"the",
"domain",
"."
] | 3e053e52a45229f96a12db9e98caf7fb3880e811 | https://github.com/F-Secure/see/blob/3e053e52a45229f96a12db9e98caf7fb3880e811/see/context/resources/network.py#L111-L129 | train |
F-Secure/see | see/context/resources/network.py | delete | def delete(network):
"""libvirt network cleanup.
@raise: libvirt.libvirtError.
"""
try:
network.destroy()
except libvirt.libvirtError as error:
raise RuntimeError("Unable to destroy network: {}".format(error)) | python | def delete(network):
"""libvirt network cleanup.
@raise: libvirt.libvirtError.
"""
try:
network.destroy()
except libvirt.libvirtError as error:
raise RuntimeError("Unable to destroy network: {}".format(error)) | [
"def",
"delete",
"(",
"network",
")",
":",
"try",
":",
"network",
".",
"destroy",
"(",
")",
"except",
"libvirt",
".",
"libvirtError",
"as",
"error",
":",
"raise",
"RuntimeError",
"(",
"\"Unable to destroy network: {}\"",
".",
"format",
"(",
"error",
")",
")"... | libvirt network cleanup.
@raise: libvirt.libvirtError. | [
"libvirt",
"network",
"cleanup",
"."
] | 3e053e52a45229f96a12db9e98caf7fb3880e811 | https://github.com/F-Secure/see/blob/3e053e52a45229f96a12db9e98caf7fb3880e811/see/context/resources/network.py#L132-L141 | train |
F-Secure/see | see/context/resources/network.py | set_address | def set_address(network, address):
"""Sets the given address to the network XML element.
Libvirt bridge will have address and DHCP server configured
according to the subnet prefix length.
"""
if network.find('.//ip') is not None:
raise RuntimeError("Address already specified in XML configu... | python | def set_address(network, address):
"""Sets the given address to the network XML element.
Libvirt bridge will have address and DHCP server configured
according to the subnet prefix length.
"""
if network.find('.//ip') is not None:
raise RuntimeError("Address already specified in XML configu... | [
"def",
"set_address",
"(",
"network",
",",
"address",
")",
":",
"if",
"network",
".",
"find",
"(",
"'.//ip'",
")",
"is",
"not",
"None",
":",
"raise",
"RuntimeError",
"(",
"\"Address already specified in XML configuration.\"",
")",
"netmask",
"=",
"str",
"(",
"... | Sets the given address to the network XML element.
Libvirt bridge will have address and DHCP server configured
according to the subnet prefix length. | [
"Sets",
"the",
"given",
"address",
"to",
"the",
"network",
"XML",
"element",
"."
] | 3e053e52a45229f96a12db9e98caf7fb3880e811 | https://github.com/F-Secure/see/blob/3e053e52a45229f96a12db9e98caf7fb3880e811/see/context/resources/network.py#L167-L184 | train |
F-Secure/see | see/context/resources/network.py | generate_address | def generate_address(hypervisor, configuration):
"""Generate a valid IP address according to the configuration."""
ipv4 = configuration['ipv4']
prefix = configuration['prefix']
subnet_prefix = configuration['subnet_prefix']
subnet_address = ipaddress.IPv4Network(u'/'.join((str(ipv4), str(prefix))))
... | python | def generate_address(hypervisor, configuration):
"""Generate a valid IP address according to the configuration."""
ipv4 = configuration['ipv4']
prefix = configuration['prefix']
subnet_prefix = configuration['subnet_prefix']
subnet_address = ipaddress.IPv4Network(u'/'.join((str(ipv4), str(prefix))))
... | [
"def",
"generate_address",
"(",
"hypervisor",
",",
"configuration",
")",
":",
"ipv4",
"=",
"configuration",
"[",
"'ipv4'",
"]",
"prefix",
"=",
"configuration",
"[",
"'prefix'",
"]",
"subnet_prefix",
"=",
"configuration",
"[",
"'subnet_prefix'",
"]",
"subnet_addres... | Generate a valid IP address according to the configuration. | [
"Generate",
"a",
"valid",
"IP",
"address",
"according",
"to",
"the",
"configuration",
"."
] | 3e053e52a45229f96a12db9e98caf7fb3880e811 | https://github.com/F-Secure/see/blob/3e053e52a45229f96a12db9e98caf7fb3880e811/see/context/resources/network.py#L187-L195 | train |
F-Secure/see | see/context/resources/network.py | address_lookup | def address_lookup(hypervisor, address_pool):
"""Retrieves a valid and available network IP address."""
address_pool = set(address_pool)
active_addresses = set(active_network_addresses(hypervisor))
try:
return random.choice(tuple(address_pool - active_addresses))
except IndexError:
... | python | def address_lookup(hypervisor, address_pool):
"""Retrieves a valid and available network IP address."""
address_pool = set(address_pool)
active_addresses = set(active_network_addresses(hypervisor))
try:
return random.choice(tuple(address_pool - active_addresses))
except IndexError:
... | [
"def",
"address_lookup",
"(",
"hypervisor",
",",
"address_pool",
")",
":",
"address_pool",
"=",
"set",
"(",
"address_pool",
")",
"active_addresses",
"=",
"set",
"(",
"active_network_addresses",
"(",
"hypervisor",
")",
")",
"try",
":",
"return",
"random",
".",
... | Retrieves a valid and available network IP address. | [
"Retrieves",
"a",
"valid",
"and",
"available",
"network",
"IP",
"address",
"."
] | 3e053e52a45229f96a12db9e98caf7fb3880e811 | https://github.com/F-Secure/see/blob/3e053e52a45229f96a12db9e98caf7fb3880e811/see/context/resources/network.py#L198-L206 | train |
F-Secure/see | see/context/resources/network.py | active_network_addresses | def active_network_addresses(hypervisor):
"""Query libvirt for the already reserved addresses."""
active = []
for network in hypervisor.listNetworks():
try:
xml = hypervisor.networkLookupByName(network).XMLDesc(0)
except libvirt.libvirtError: # network has been destroyed meanwh... | python | def active_network_addresses(hypervisor):
"""Query libvirt for the already reserved addresses."""
active = []
for network in hypervisor.listNetworks():
try:
xml = hypervisor.networkLookupByName(network).XMLDesc(0)
except libvirt.libvirtError: # network has been destroyed meanwh... | [
"def",
"active_network_addresses",
"(",
"hypervisor",
")",
":",
"active",
"=",
"[",
"]",
"for",
"network",
"in",
"hypervisor",
".",
"listNetworks",
"(",
")",
":",
"try",
":",
"xml",
"=",
"hypervisor",
".",
"networkLookupByName",
"(",
"network",
")",
".",
"... | Query libvirt for the already reserved addresses. | [
"Query",
"libvirt",
"for",
"the",
"already",
"reserved",
"addresses",
"."
] | 3e053e52a45229f96a12db9e98caf7fb3880e811 | https://github.com/F-Secure/see/blob/3e053e52a45229f96a12db9e98caf7fb3880e811/see/context/resources/network.py#L209-L226 | train |
F-Secure/see | see/context/context.py | interface_lookup | def interface_lookup(interfaces, hwaddr, address_type):
"""Search the address within the interface list."""
for interface in interfaces.values():
if interface.get('hwaddr') == hwaddr:
for address in interface.get('addrs'):
if address.get('type') == address_type:
... | python | def interface_lookup(interfaces, hwaddr, address_type):
"""Search the address within the interface list."""
for interface in interfaces.values():
if interface.get('hwaddr') == hwaddr:
for address in interface.get('addrs'):
if address.get('type') == address_type:
... | [
"def",
"interface_lookup",
"(",
"interfaces",
",",
"hwaddr",
",",
"address_type",
")",
":",
"for",
"interface",
"in",
"interfaces",
".",
"values",
"(",
")",
":",
"if",
"interface",
".",
"get",
"(",
"'hwaddr'",
")",
"==",
"hwaddr",
":",
"for",
"address",
... | Search the address within the interface list. | [
"Search",
"the",
"address",
"within",
"the",
"interface",
"list",
"."
] | 3e053e52a45229f96a12db9e98caf7fb3880e811 | https://github.com/F-Secure/see/blob/3e053e52a45229f96a12db9e98caf7fb3880e811/see/context/context.py#L356-L362 | train |
F-Secure/see | see/context/context.py | SeeContext.mac_address | def mac_address(self):
"""Returns the MAC address of the network interface.
If multiple interfaces are provided,
the address of the first found is returned.
"""
if self._mac_address is None:
self._mac_address = self._get_mac_address()
return self._mac_addre... | python | def mac_address(self):
"""Returns the MAC address of the network interface.
If multiple interfaces are provided,
the address of the first found is returned.
"""
if self._mac_address is None:
self._mac_address = self._get_mac_address()
return self._mac_addre... | [
"def",
"mac_address",
"(",
"self",
")",
":",
"if",
"self",
".",
"_mac_address",
"is",
"None",
":",
"self",
".",
"_mac_address",
"=",
"self",
".",
"_get_mac_address",
"(",
")",
"return",
"self",
".",
"_mac_address"
] | Returns the MAC address of the network interface.
If multiple interfaces are provided,
the address of the first found is returned. | [
"Returns",
"the",
"MAC",
"address",
"of",
"the",
"network",
"interface",
"."
] | 3e053e52a45229f96a12db9e98caf7fb3880e811 | https://github.com/F-Secure/see/blob/3e053e52a45229f96a12db9e98caf7fb3880e811/see/context/context.py#L159-L169 | train |
F-Secure/see | see/context/context.py | SeeContext.ip4_address | def ip4_address(self):
"""Returns the IPv4 address of the network interface.
If multiple interfaces are provided,
the address of the first found is returned.
"""
if self._ip4_address is None and self.network is not None:
self._ip4_address = self._get_ip_address(
... | python | def ip4_address(self):
"""Returns the IPv4 address of the network interface.
If multiple interfaces are provided,
the address of the first found is returned.
"""
if self._ip4_address is None and self.network is not None:
self._ip4_address = self._get_ip_address(
... | [
"def",
"ip4_address",
"(",
"self",
")",
":",
"if",
"self",
".",
"_ip4_address",
"is",
"None",
"and",
"self",
".",
"network",
"is",
"not",
"None",
":",
"self",
".",
"_ip4_address",
"=",
"self",
".",
"_get_ip_address",
"(",
"libvirt",
".",
"VIR_IP_ADDR_TYPE_... | Returns the IPv4 address of the network interface.
If multiple interfaces are provided,
the address of the first found is returned. | [
"Returns",
"the",
"IPv4",
"address",
"of",
"the",
"network",
"interface",
"."
] | 3e053e52a45229f96a12db9e98caf7fb3880e811 | https://github.com/F-Secure/see/blob/3e053e52a45229f96a12db9e98caf7fb3880e811/see/context/context.py#L178-L189 | train |
F-Secure/see | see/context/context.py | SeeContext.ip6_address | def ip6_address(self):
"""Returns the IPv6 address of the network interface.
If multiple interfaces are provided,
the address of the first found is returned.
"""
if self._ip6_address is None and self.network is not None:
self._ip6_address = self._get_ip_address(
... | python | def ip6_address(self):
"""Returns the IPv6 address of the network interface.
If multiple interfaces are provided,
the address of the first found is returned.
"""
if self._ip6_address is None and self.network is not None:
self._ip6_address = self._get_ip_address(
... | [
"def",
"ip6_address",
"(",
"self",
")",
":",
"if",
"self",
".",
"_ip6_address",
"is",
"None",
"and",
"self",
".",
"network",
"is",
"not",
"None",
":",
"self",
".",
"_ip6_address",
"=",
"self",
".",
"_get_ip_address",
"(",
"libvirt",
".",
"VIR_IP_ADDR_TYPE_... | Returns the IPv6 address of the network interface.
If multiple interfaces are provided,
the address of the first found is returned. | [
"Returns",
"the",
"IPv6",
"address",
"of",
"the",
"network",
"interface",
"."
] | 3e053e52a45229f96a12db9e98caf7fb3880e811 | https://github.com/F-Secure/see/blob/3e053e52a45229f96a12db9e98caf7fb3880e811/see/context/context.py#L192-L203 | train |
F-Secure/see | see/context/context.py | SeeContext.shutdown | def shutdown(self, timeout=None, **kwargs):
"""
Shuts down the Context. Sends an ACPI request to the OS for a clean
shutdown.
Triggered events::
* pre_poweroff
* post_poweroff
.. note::
The Guest OS needs to support ACPI requests sent from the hos... | python | def shutdown(self, timeout=None, **kwargs):
"""
Shuts down the Context. Sends an ACPI request to the OS for a clean
shutdown.
Triggered events::
* pre_poweroff
* post_poweroff
.. note::
The Guest OS needs to support ACPI requests sent from the hos... | [
"def",
"shutdown",
"(",
"self",
",",
"timeout",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_assert_transition",
"(",
"'shutdown'",
")",
"self",
".",
"trigger",
"(",
"'pre_shutdown'",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"_execu... | Shuts down the Context. Sends an ACPI request to the OS for a clean
shutdown.
Triggered events::
* pre_poweroff
* post_poweroff
.. note::
The Guest OS needs to support ACPI requests sent from the host,
the completion of the operation is not ensured by ... | [
"Shuts",
"down",
"the",
"Context",
".",
"Sends",
"an",
"ACPI",
"request",
"to",
"the",
"OS",
"for",
"a",
"clean",
"shutdown",
"."
] | 3e053e52a45229f96a12db9e98caf7fb3880e811 | https://github.com/F-Secure/see/blob/3e053e52a45229f96a12db9e98caf7fb3880e811/see/context/context.py#L272-L295 | train |
F-Secure/see | see/context/context.py | SeeContext._command | def _command(self, event, command, *args, **kwargs):
"""
Context state controller.
Check whether the transition is possible or not, it executes it and
triggers the Hooks with the pre_* and post_* events.
@param event: (str) event generated by the command.
@param command... | python | def _command(self, event, command, *args, **kwargs):
"""
Context state controller.
Check whether the transition is possible or not, it executes it and
triggers the Hooks with the pre_* and post_* events.
@param event: (str) event generated by the command.
@param command... | [
"def",
"_command",
"(",
"self",
",",
"event",
",",
"command",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_assert_transition",
"(",
"event",
")",
"self",
".",
"trigger",
"(",
"'pre_%s'",
"%",
"event",
",",
"*",
"*",
"kwargs",
... | Context state controller.
Check whether the transition is possible or not, it executes it and
triggers the Hooks with the pre_* and post_* events.
@param event: (str) event generated by the command.
@param command: (virDomain.method) state transition to impose.
@raise: RuntimeE... | [
"Context",
"state",
"controller",
"."
] | 3e053e52a45229f96a12db9e98caf7fb3880e811 | https://github.com/F-Secure/see/blob/3e053e52a45229f96a12db9e98caf7fb3880e811/see/context/context.py#L325-L340 | train |
F-Secure/see | see/context/context.py | SeeContext._assert_transition | def _assert_transition(self, event):
"""Asserts the state transition validity."""
state = self.domain.state()[0]
if event not in STATES_MAP[state]:
raise RuntimeError("State transition %s not allowed" % event) | python | def _assert_transition(self, event):
"""Asserts the state transition validity."""
state = self.domain.state()[0]
if event not in STATES_MAP[state]:
raise RuntimeError("State transition %s not allowed" % event) | [
"def",
"_assert_transition",
"(",
"self",
",",
"event",
")",
":",
"state",
"=",
"self",
".",
"domain",
".",
"state",
"(",
")",
"[",
"0",
"]",
"if",
"event",
"not",
"in",
"STATES_MAP",
"[",
"state",
"]",
":",
"raise",
"RuntimeError",
"(",
"\"State trans... | Asserts the state transition validity. | [
"Asserts",
"the",
"state",
"transition",
"validity",
"."
] | 3e053e52a45229f96a12db9e98caf7fb3880e811 | https://github.com/F-Secure/see/blob/3e053e52a45229f96a12db9e98caf7fb3880e811/see/context/context.py#L342-L346 | train |
F-Secure/see | see/context/context.py | SeeContext._execute_command | def _execute_command(self, command, *args):
"""Execute the state transition command."""
try:
command(*args)
except libvirt.libvirtError as error:
raise RuntimeError("Unable to execute command. %s" % error) | python | def _execute_command(self, command, *args):
"""Execute the state transition command."""
try:
command(*args)
except libvirt.libvirtError as error:
raise RuntimeError("Unable to execute command. %s" % error) | [
"def",
"_execute_command",
"(",
"self",
",",
"command",
",",
"*",
"args",
")",
":",
"try",
":",
"command",
"(",
"*",
"args",
")",
"except",
"libvirt",
".",
"libvirtError",
"as",
"error",
":",
"raise",
"RuntimeError",
"(",
"\"Unable to execute command. %s\"",
... | Execute the state transition command. | [
"Execute",
"the",
"state",
"transition",
"command",
"."
] | 3e053e52a45229f96a12db9e98caf7fb3880e811 | https://github.com/F-Secure/see/blob/3e053e52a45229f96a12db9e98caf7fb3880e811/see/context/context.py#L348-L353 | train |
F-Secure/see | plugins/disk.py | snapshot_to_checkpoint | def snapshot_to_checkpoint(volume, snapshot, folder_path):
"""Turns a QEMU internal snapshot into a QCOW file."""
create_folder(folder_path)
name = snapshot.getName()
path = os.path.join(folder_path, '%s.qcow2' % name)
process = launch_process(QEMU_IMG, "convert", "-f", "qcow2", "-o",
... | python | def snapshot_to_checkpoint(volume, snapshot, folder_path):
"""Turns a QEMU internal snapshot into a QCOW file."""
create_folder(folder_path)
name = snapshot.getName()
path = os.path.join(folder_path, '%s.qcow2' % name)
process = launch_process(QEMU_IMG, "convert", "-f", "qcow2", "-o",
... | [
"def",
"snapshot_to_checkpoint",
"(",
"volume",
",",
"snapshot",
",",
"folder_path",
")",
":",
"create_folder",
"(",
"folder_path",
")",
"name",
"=",
"snapshot",
".",
"getName",
"(",
")",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"folder_path",
","... | Turns a QEMU internal snapshot into a QCOW file. | [
"Turns",
"a",
"QEMU",
"internal",
"snapshot",
"into",
"a",
"QCOW",
"file",
"."
] | 3e053e52a45229f96a12db9e98caf7fb3880e811 | https://github.com/F-Secure/see/blob/3e053e52a45229f96a12db9e98caf7fb3880e811/plugins/disk.py#L214-L227 | train |
F-Secure/see | plugins/disk.py | compare_disks | def compare_disks(disk0, disk1, configuration):
"""Compares two disks according to the given configuration."""
with DiskComparator(disk0, disk1) as comparator:
results = comparator.compare(
size=configuration.get('get_file_size', False),
identify=configuration.get('identify_files... | python | def compare_disks(disk0, disk1, configuration):
"""Compares two disks according to the given configuration."""
with DiskComparator(disk0, disk1) as comparator:
results = comparator.compare(
size=configuration.get('get_file_size', False),
identify=configuration.get('identify_files... | [
"def",
"compare_disks",
"(",
"disk0",
",",
"disk1",
",",
"configuration",
")",
":",
"with",
"DiskComparator",
"(",
"disk0",
",",
"disk1",
")",
"as",
"comparator",
":",
"results",
"=",
"comparator",
".",
"compare",
"(",
"size",
"=",
"configuration",
".",
"g... | Compares two disks according to the given configuration. | [
"Compares",
"two",
"disks",
"according",
"to",
"the",
"given",
"configuration",
"."
] | 3e053e52a45229f96a12db9e98caf7fb3880e811 | https://github.com/F-Secure/see/blob/3e053e52a45229f96a12db9e98caf7fb3880e811/plugins/disk.py#L230-L249 | train |
F-Secure/see | plugins/disk.py | DiskStateAnalyser.start_processing_handler | def start_processing_handler(self, event):
"""Asynchronous handler starting the disk analysis process."""
results_path = os.path.join(self.configuration['results_folder'],
"filesystem.json")
self.logger.debug("Event %s: start comparing %s with %s.",
... | python | def start_processing_handler(self, event):
"""Asynchronous handler starting the disk analysis process."""
results_path = os.path.join(self.configuration['results_folder'],
"filesystem.json")
self.logger.debug("Event %s: start comparing %s with %s.",
... | [
"def",
"start_processing_handler",
"(",
"self",
",",
"event",
")",
":",
"results_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"configuration",
"[",
"'results_folder'",
"]",
",",
"\"filesystem.json\"",
")",
"self",
".",
"logger",
".",
"debug"... | Asynchronous handler starting the disk analysis process. | [
"Asynchronous",
"handler",
"starting",
"the",
"disk",
"analysis",
"process",
"."
] | 3e053e52a45229f96a12db9e98caf7fb3880e811 | https://github.com/F-Secure/see/blob/3e053e52a45229f96a12db9e98caf7fb3880e811/plugins/disk.py#L192-L205 | train |
F-Secure/see | see/helpers.py | lookup_class | def lookup_class(fully_qualified_name):
"""
Given its fully qualified name, finds the desired class and imports it.
Returns the Class object if found.
"""
module_name, class_name = str(fully_qualified_name).rsplit(".", 1)
module = __import__(module_name, globals(), locals(), [class_name], 0)
... | python | def lookup_class(fully_qualified_name):
"""
Given its fully qualified name, finds the desired class and imports it.
Returns the Class object if found.
"""
module_name, class_name = str(fully_qualified_name).rsplit(".", 1)
module = __import__(module_name, globals(), locals(), [class_name], 0)
... | [
"def",
"lookup_class",
"(",
"fully_qualified_name",
")",
":",
"module_name",
",",
"class_name",
"=",
"str",
"(",
"fully_qualified_name",
")",
".",
"rsplit",
"(",
"\".\"",
",",
"1",
")",
"module",
"=",
"__import__",
"(",
"module_name",
",",
"globals",
"(",
")... | Given its fully qualified name, finds the desired class and imports it.
Returns the Class object if found. | [
"Given",
"its",
"fully",
"qualified",
"name",
"finds",
"the",
"desired",
"class",
"and",
"imports",
"it",
".",
"Returns",
"the",
"Class",
"object",
"if",
"found",
"."
] | 3e053e52a45229f96a12db9e98caf7fb3880e811 | https://github.com/F-Secure/see/blob/3e053e52a45229f96a12db9e98caf7fb3880e811/see/helpers.py#L18-L31 | train |
F-Secure/see | see/observer.py | prime_event | def prime_event(event, source, **kwargs):
"""
Returns the event ready to be triggered.
If the given event is a string an Event instance is generated from it.
"""
if not isinstance(event, Event):
event = Event(event, source=source, **kwargs)
return event | python | def prime_event(event, source, **kwargs):
"""
Returns the event ready to be triggered.
If the given event is a string an Event instance is generated from it.
"""
if not isinstance(event, Event):
event = Event(event, source=source, **kwargs)
return event | [
"def",
"prime_event",
"(",
"event",
",",
"source",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"event",
",",
"Event",
")",
":",
"event",
"=",
"Event",
"(",
"event",
",",
"source",
"=",
"source",
",",
"*",
"*",
"kwargs",
")",
... | Returns the event ready to be triggered.
If the given event is a string an Event instance is generated from it. | [
"Returns",
"the",
"event",
"ready",
"to",
"be",
"triggered",
"."
] | 3e053e52a45229f96a12db9e98caf7fb3880e811 | https://github.com/F-Secure/see/blob/3e053e52a45229f96a12db9e98caf7fb3880e811/see/observer.py#L116-L125 | train |
F-Secure/see | see/observer.py | asynchronous | def asynchronous(function, event):
"""
Runs the function asynchronously taking care of exceptions.
"""
thread = Thread(target=synchronous, args=(function, event))
thread.daemon = True
thread.start() | python | def asynchronous(function, event):
"""
Runs the function asynchronously taking care of exceptions.
"""
thread = Thread(target=synchronous, args=(function, event))
thread.daemon = True
thread.start() | [
"def",
"asynchronous",
"(",
"function",
",",
"event",
")",
":",
"thread",
"=",
"Thread",
"(",
"target",
"=",
"synchronous",
",",
"args",
"=",
"(",
"function",
",",
"event",
")",
")",
"thread",
".",
"daemon",
"=",
"True",
"thread",
".",
"start",
"(",
... | Runs the function asynchronously taking care of exceptions. | [
"Runs",
"the",
"function",
"asynchronously",
"taking",
"care",
"of",
"exceptions",
"."
] | 3e053e52a45229f96a12db9e98caf7fb3880e811 | https://github.com/F-Secure/see/blob/3e053e52a45229f96a12db9e98caf7fb3880e811/see/observer.py#L128-L134 | train |
F-Secure/see | see/observer.py | synchronous | def synchronous(function, event):
"""
Runs the function synchronously taking care of exceptions.
"""
try:
function(event)
except Exception as error:
logger = get_function_logger(function)
logger.exception(error) | python | def synchronous(function, event):
"""
Runs the function synchronously taking care of exceptions.
"""
try:
function(event)
except Exception as error:
logger = get_function_logger(function)
logger.exception(error) | [
"def",
"synchronous",
"(",
"function",
",",
"event",
")",
":",
"try",
":",
"function",
"(",
"event",
")",
"except",
"Exception",
"as",
"error",
":",
"logger",
"=",
"get_function_logger",
"(",
"function",
")",
"logger",
".",
"exception",
"(",
"error",
")"
] | Runs the function synchronously taking care of exceptions. | [
"Runs",
"the",
"function",
"synchronously",
"taking",
"care",
"of",
"exceptions",
"."
] | 3e053e52a45229f96a12db9e98caf7fb3880e811 | https://github.com/F-Secure/see/blob/3e053e52a45229f96a12db9e98caf7fb3880e811/see/observer.py#L137-L145 | train |
F-Secure/see | see/observer.py | Observable.subscribe | def subscribe(self, event, handler):
"""
Subscribes a Handler for the given Event.
@param event: (str|see.Event) event to react to.
@param handler: (callable) function or method to subscribe.
"""
self._handlers.sync_handlers[event].append(handler) | python | def subscribe(self, event, handler):
"""
Subscribes a Handler for the given Event.
@param event: (str|see.Event) event to react to.
@param handler: (callable) function or method to subscribe.
"""
self._handlers.sync_handlers[event].append(handler) | [
"def",
"subscribe",
"(",
"self",
",",
"event",
",",
"handler",
")",
":",
"self",
".",
"_handlers",
".",
"sync_handlers",
"[",
"event",
"]",
".",
"append",
"(",
"handler",
")"
] | Subscribes a Handler for the given Event.
@param event: (str|see.Event) event to react to.
@param handler: (callable) function or method to subscribe. | [
"Subscribes",
"a",
"Handler",
"for",
"the",
"given",
"Event",
"."
] | 3e053e52a45229f96a12db9e98caf7fb3880e811 | https://github.com/F-Secure/see/blob/3e053e52a45229f96a12db9e98caf7fb3880e811/see/observer.py#L54-L61 | train |
F-Secure/see | see/observer.py | Observable.subscribe_async | def subscribe_async(self, event, handler):
"""
Subscribes an asynchronous Handler for the given Event.
An asynchronous handler is executed concurrently to the others
without blocking the Events flow.
@param event: (str|see.Event) event to react to.
@param handler: (call... | python | def subscribe_async(self, event, handler):
"""
Subscribes an asynchronous Handler for the given Event.
An asynchronous handler is executed concurrently to the others
without blocking the Events flow.
@param event: (str|see.Event) event to react to.
@param handler: (call... | [
"def",
"subscribe_async",
"(",
"self",
",",
"event",
",",
"handler",
")",
":",
"self",
".",
"_handlers",
".",
"async_handlers",
"[",
"event",
"]",
".",
"append",
"(",
"handler",
")"
] | Subscribes an asynchronous Handler for the given Event.
An asynchronous handler is executed concurrently to the others
without blocking the Events flow.
@param event: (str|see.Event) event to react to.
@param handler: (callable) function or method to subscribe. | [
"Subscribes",
"an",
"asynchronous",
"Handler",
"for",
"the",
"given",
"Event",
"."
] | 3e053e52a45229f96a12db9e98caf7fb3880e811 | https://github.com/F-Secure/see/blob/3e053e52a45229f96a12db9e98caf7fb3880e811/see/observer.py#L63-L73 | train |
F-Secure/see | see/observer.py | Observable.unsubscribe | def unsubscribe(self, event, handler):
"""
Unsubscribes the Handler from the given Event.
Both synchronous and asynchronous handlers are removed.
@param event: (str|see.Event) event to which the handler is subscribed.
@param handler: (callable) function or method to unsubscribe.... | python | def unsubscribe(self, event, handler):
"""
Unsubscribes the Handler from the given Event.
Both synchronous and asynchronous handlers are removed.
@param event: (str|see.Event) event to which the handler is subscribed.
@param handler: (callable) function or method to unsubscribe.... | [
"def",
"unsubscribe",
"(",
"self",
",",
"event",
",",
"handler",
")",
":",
"try",
":",
"self",
".",
"_handlers",
".",
"sync_handlers",
"[",
"event",
"]",
".",
"remove",
"(",
"handler",
")",
"except",
"ValueError",
":",
"self",
".",
"_handlers",
".",
"a... | Unsubscribes the Handler from the given Event.
Both synchronous and asynchronous handlers are removed.
@param event: (str|see.Event) event to which the handler is subscribed.
@param handler: (callable) function or method to unsubscribe. | [
"Unsubscribes",
"the",
"Handler",
"from",
"the",
"given",
"Event",
".",
"Both",
"synchronous",
"and",
"asynchronous",
"handlers",
"are",
"removed",
"."
] | 3e053e52a45229f96a12db9e98caf7fb3880e811 | https://github.com/F-Secure/see/blob/3e053e52a45229f96a12db9e98caf7fb3880e811/see/observer.py#L75-L91 | train |
F-Secure/see | see/observer.py | Observable.trigger | def trigger(self, event, **kwargs):
"""
Triggers an event.
All subscribed handlers will be executed, asynchronous ones
won't block this call.
@param event: (str|see.Event) event intended to be raised.
"""
with self._handlers.trigger_mutex:
event = pr... | python | def trigger(self, event, **kwargs):
"""
Triggers an event.
All subscribed handlers will be executed, asynchronous ones
won't block this call.
@param event: (str|see.Event) event intended to be raised.
"""
with self._handlers.trigger_mutex:
event = pr... | [
"def",
"trigger",
"(",
"self",
",",
"event",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"self",
".",
"_handlers",
".",
"trigger_mutex",
":",
"event",
"=",
"prime_event",
"(",
"event",
",",
"self",
".",
"__class__",
".",
"__name__",
",",
"*",
"*",
"kw... | Triggers an event.
All subscribed handlers will be executed, asynchronous ones
won't block this call.
@param event: (str|see.Event) event intended to be raised. | [
"Triggers",
"an",
"event",
"."
] | 3e053e52a45229f96a12db9e98caf7fb3880e811 | https://github.com/F-Secure/see/blob/3e053e52a45229f96a12db9e98caf7fb3880e811/see/observer.py#L93-L108 | train |
F-Secure/see | see/context/resources/resources.py | Resources.provider_image | def provider_image(self):
"""Image path getter.
This method uses a pluggable image provider to retrieve an
image's path.
"""
if self._image is None:
if isinstance(self.configuration['disk']['image'], dict):
ProviderClass = lookup_provider_class(
... | python | def provider_image(self):
"""Image path getter.
This method uses a pluggable image provider to retrieve an
image's path.
"""
if self._image is None:
if isinstance(self.configuration['disk']['image'], dict):
ProviderClass = lookup_provider_class(
... | [
"def",
"provider_image",
"(",
"self",
")",
":",
"if",
"self",
".",
"_image",
"is",
"None",
":",
"if",
"isinstance",
"(",
"self",
".",
"configuration",
"[",
"'disk'",
"]",
"[",
"'image'",
"]",
",",
"dict",
")",
":",
"ProviderClass",
"=",
"lookup_provider_... | Image path getter.
This method uses a pluggable image provider to retrieve an
image's path. | [
"Image",
"path",
"getter",
"."
] | 3e053e52a45229f96a12db9e98caf7fb3880e811 | https://github.com/F-Secure/see/blob/3e053e52a45229f96a12db9e98caf7fb3880e811/see/context/resources/resources.py#L109-L126 | train |
F-Secure/see | plugins/agent.py | run_command | def run_command(args, asynchronous=False):
"""Executes a command returning its exit code and output."""
logging.info("Executing %s command %s.",
asynchronous and 'asynchronous' or 'synchronous', args)
process = subprocess.Popen(args,
shell=True,
... | python | def run_command(args, asynchronous=False):
"""Executes a command returning its exit code and output."""
logging.info("Executing %s command %s.",
asynchronous and 'asynchronous' or 'synchronous', args)
process = subprocess.Popen(args,
shell=True,
... | [
"def",
"run_command",
"(",
"args",
",",
"asynchronous",
"=",
"False",
")",
":",
"logging",
".",
"info",
"(",
"\"Executing %s command %s.\"",
",",
"asynchronous",
"and",
"'asynchronous'",
"or",
"'synchronous'",
",",
"args",
")",
"process",
"=",
"subprocess",
".",... | Executes a command returning its exit code and output. | [
"Executes",
"a",
"command",
"returning",
"its",
"exit",
"code",
"and",
"output",
"."
] | 3e053e52a45229f96a12db9e98caf7fb3880e811 | https://github.com/F-Secure/see/blob/3e053e52a45229f96a12db9e98caf7fb3880e811/plugins/agent.py#L108-L127 | train |
F-Secure/see | plugins/agent.py | Agent.respond | def respond(self, output):
"""Generates server response."""
response = {'exit_code': output.code,
'command_output': output.log}
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
self.wfile.write(bytes(js... | python | def respond(self, output):
"""Generates server response."""
response = {'exit_code': output.code,
'command_output': output.log}
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
self.wfile.write(bytes(js... | [
"def",
"respond",
"(",
"self",
",",
"output",
")",
":",
"response",
"=",
"{",
"'exit_code'",
":",
"output",
".",
"code",
",",
"'command_output'",
":",
"output",
".",
"log",
"}",
"self",
".",
"send_response",
"(",
"200",
")",
"self",
".",
"send_header",
... | Generates server response. | [
"Generates",
"server",
"response",
"."
] | 3e053e52a45229f96a12db9e98caf7fb3880e811 | https://github.com/F-Secure/see/blob/3e053e52a45229f96a12db9e98caf7fb3880e811/plugins/agent.py#L85-L95 | train |
F-Secure/see | plugins/agent.py | Agent.store_file | def store_file(self, folder, name):
"""Stores the uploaded file in the given path."""
path = os.path.join(folder, name)
length = self.headers['content-length']
with open(path, 'wb') as sample:
sample.write(self.rfile.read(int(length)))
return path | python | def store_file(self, folder, name):
"""Stores the uploaded file in the given path."""
path = os.path.join(folder, name)
length = self.headers['content-length']
with open(path, 'wb') as sample:
sample.write(self.rfile.read(int(length)))
return path | [
"def",
"store_file",
"(",
"self",
",",
"folder",
",",
"name",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"folder",
",",
"name",
")",
"length",
"=",
"self",
".",
"headers",
"[",
"'content-length'",
"]",
"with",
"open",
"(",
"path",
... | Stores the uploaded file in the given path. | [
"Stores",
"the",
"uploaded",
"file",
"in",
"the",
"given",
"path",
"."
] | 3e053e52a45229f96a12db9e98caf7fb3880e811 | https://github.com/F-Secure/see/blob/3e053e52a45229f96a12db9e98caf7fb3880e811/plugins/agent.py#L97-L105 | train |
F-Secure/see | plugins/memory.py | VolatilityHook.start_processing_handler | def start_processing_handler(self, event):
"""Asynchronous handler starting the Volatility processes."""
self.logger.debug("Event %s: starting Volatility process(es).", event)
for snapshot in self.snapshots:
self.process_snapshot(snapshot)
self.processing_done.set() | python | def start_processing_handler(self, event):
"""Asynchronous handler starting the Volatility processes."""
self.logger.debug("Event %s: starting Volatility process(es).", event)
for snapshot in self.snapshots:
self.process_snapshot(snapshot)
self.processing_done.set() | [
"def",
"start_processing_handler",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Event %s: starting Volatility process(es).\"",
",",
"event",
")",
"for",
"snapshot",
"in",
"self",
".",
"snapshots",
":",
"self",
".",
"process_s... | Asynchronous handler starting the Volatility processes. | [
"Asynchronous",
"handler",
"starting",
"the",
"Volatility",
"processes",
"."
] | 3e053e52a45229f96a12db9e98caf7fb3880e811 | https://github.com/F-Secure/see/blob/3e053e52a45229f96a12db9e98caf7fb3880e811/plugins/memory.py#L170-L177 | train |
F-Secure/see | see/context/resources/qemu.py | disk_xml | def disk_xml(identifier, pool_xml, base_volume_xml, cow):
"""Clones volume_xml updating the required fields.
* name
* target path
* backingStore
"""
pool = etree.fromstring(pool_xml)
base_volume = etree.fromstring(base_volume_xml)
pool_path = pool.find('.//path').text
base_path ... | python | def disk_xml(identifier, pool_xml, base_volume_xml, cow):
"""Clones volume_xml updating the required fields.
* name
* target path
* backingStore
"""
pool = etree.fromstring(pool_xml)
base_volume = etree.fromstring(base_volume_xml)
pool_path = pool.find('.//path').text
base_path ... | [
"def",
"disk_xml",
"(",
"identifier",
",",
"pool_xml",
",",
"base_volume_xml",
",",
"cow",
")",
":",
"pool",
"=",
"etree",
".",
"fromstring",
"(",
"pool_xml",
")",
"base_volume",
"=",
"etree",
".",
"fromstring",
"(",
"base_volume_xml",
")",
"pool_path",
"=",... | Clones volume_xml updating the required fields.
* name
* target path
* backingStore | [
"Clones",
"volume_xml",
"updating",
"the",
"required",
"fields",
"."
] | 3e053e52a45229f96a12db9e98caf7fb3880e811 | https://github.com/F-Secure/see/blob/3e053e52a45229f96a12db9e98caf7fb3880e811/see/context/resources/qemu.py#L166-L190 | train |
F-Secure/see | see/context/resources/qemu.py | pool_create | def pool_create(hypervisor, identifier, pool_path):
"""Storage pool creation.
The following values are set in the XML configuration:
* name
* target/path
* target/permission/label
"""
path = os.path.join(pool_path, identifier)
if not os.path.exists(path):
os.makedirs(pat... | python | def pool_create(hypervisor, identifier, pool_path):
"""Storage pool creation.
The following values are set in the XML configuration:
* name
* target/path
* target/permission/label
"""
path = os.path.join(pool_path, identifier)
if not os.path.exists(path):
os.makedirs(pat... | [
"def",
"pool_create",
"(",
"hypervisor",
",",
"identifier",
",",
"pool_path",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"pool_path",
",",
"identifier",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"os",... | Storage pool creation.
The following values are set in the XML configuration:
* name
* target/path
* target/permission/label | [
"Storage",
"pool",
"creation",
"."
] | 3e053e52a45229f96a12db9e98caf7fb3880e811 | https://github.com/F-Secure/see/blob/3e053e52a45229f96a12db9e98caf7fb3880e811/see/context/resources/qemu.py#L225-L241 | train |
F-Secure/see | see/context/resources/qemu.py | pool_lookup | def pool_lookup(hypervisor, disk_path):
"""Storage pool lookup.
Retrieves the the virStoragepool which contains the disk at the given path.
"""
try:
volume = hypervisor.storageVolLookupByPath(disk_path)
return volume.storagePoolLookupByVolume()
except libvirt.libvirtError:
... | python | def pool_lookup(hypervisor, disk_path):
"""Storage pool lookup.
Retrieves the the virStoragepool which contains the disk at the given path.
"""
try:
volume = hypervisor.storageVolLookupByPath(disk_path)
return volume.storagePoolLookupByVolume()
except libvirt.libvirtError:
... | [
"def",
"pool_lookup",
"(",
"hypervisor",
",",
"disk_path",
")",
":",
"try",
":",
"volume",
"=",
"hypervisor",
".",
"storageVolLookupByPath",
"(",
"disk_path",
")",
"return",
"volume",
".",
"storagePoolLookupByVolume",
"(",
")",
"except",
"libvirt",
".",
"libvirt... | Storage pool lookup.
Retrieves the the virStoragepool which contains the disk at the given path. | [
"Storage",
"pool",
"lookup",
"."
] | 3e053e52a45229f96a12db9e98caf7fb3880e811 | https://github.com/F-Secure/see/blob/3e053e52a45229f96a12db9e98caf7fb3880e811/see/context/resources/qemu.py#L244-L255 | train |
F-Secure/see | see/context/resources/qemu.py | pool_delete | def pool_delete(storage_pool, logger):
"""Storage Pool deletion, removes all the created disk images within the pool and the pool itself."""
path = etree.fromstring(storage_pool.XMLDesc(0)).find('.//path').text
volumes_delete(storage_pool, logger)
try:
storage_pool.destroy()
except libvirt... | python | def pool_delete(storage_pool, logger):
"""Storage Pool deletion, removes all the created disk images within the pool and the pool itself."""
path = etree.fromstring(storage_pool.XMLDesc(0)).find('.//path').text
volumes_delete(storage_pool, logger)
try:
storage_pool.destroy()
except libvirt... | [
"def",
"pool_delete",
"(",
"storage_pool",
",",
"logger",
")",
":",
"path",
"=",
"etree",
".",
"fromstring",
"(",
"storage_pool",
".",
"XMLDesc",
"(",
"0",
")",
")",
".",
"find",
"(",
"'.//path'",
")",
".",
"text",
"volumes_delete",
"(",
"storage_pool",
... | Storage Pool deletion, removes all the created disk images within the pool and the pool itself. | [
"Storage",
"Pool",
"deletion",
"removes",
"all",
"the",
"created",
"disk",
"images",
"within",
"the",
"pool",
"and",
"the",
"pool",
"itself",
"."
] | 3e053e52a45229f96a12db9e98caf7fb3880e811 | https://github.com/F-Secure/see/blob/3e053e52a45229f96a12db9e98caf7fb3880e811/see/context/resources/qemu.py#L258-L272 | train |
F-Secure/see | see/context/resources/qemu.py | volumes_delete | def volumes_delete(storage_pool, logger):
"""Deletes all storage volume disks contained in the given storage pool."""
try:
for vol_name in storage_pool.listVolumes():
try:
vol = storage_pool.storageVolLookupByName(vol_name)
vol.delete(0)
except lib... | python | def volumes_delete(storage_pool, logger):
"""Deletes all storage volume disks contained in the given storage pool."""
try:
for vol_name in storage_pool.listVolumes():
try:
vol = storage_pool.storageVolLookupByName(vol_name)
vol.delete(0)
except lib... | [
"def",
"volumes_delete",
"(",
"storage_pool",
",",
"logger",
")",
":",
"try",
":",
"for",
"vol_name",
"in",
"storage_pool",
".",
"listVolumes",
"(",
")",
":",
"try",
":",
"vol",
"=",
"storage_pool",
".",
"storageVolLookupByName",
"(",
"vol_name",
")",
"vol",... | Deletes all storage volume disks contained in the given storage pool. | [
"Deletes",
"all",
"storage",
"volume",
"disks",
"contained",
"in",
"the",
"given",
"storage",
"pool",
"."
] | 3e053e52a45229f96a12db9e98caf7fb3880e811 | https://github.com/F-Secure/see/blob/3e053e52a45229f96a12db9e98caf7fb3880e811/see/context/resources/qemu.py#L275-L286 | train |
F-Secure/see | see/context/resources/qemu.py | disk_clone | def disk_clone(hypervisor, identifier, storage_pool, configuration, image, logger):
"""Disk image cloning.
Given an original disk image it clones it into a new one, the clone will be created within the storage pool.
The following values are set into the disk XML configuration:
* name
* target... | python | def disk_clone(hypervisor, identifier, storage_pool, configuration, image, logger):
"""Disk image cloning.
Given an original disk image it clones it into a new one, the clone will be created within the storage pool.
The following values are set into the disk XML configuration:
* name
* target... | [
"def",
"disk_clone",
"(",
"hypervisor",
",",
"identifier",
",",
"storage_pool",
",",
"configuration",
",",
"image",
",",
"logger",
")",
":",
"cow",
"=",
"configuration",
".",
"get",
"(",
"'copy_on_write'",
",",
"False",
")",
"try",
":",
"volume",
"=",
"hyp... | Disk image cloning.
Given an original disk image it clones it into a new one, the clone will be created within the storage pool.
The following values are set into the disk XML configuration:
* name
* target/path
* target/permission/label
* backingStore/path if copy on write is enabled | [
"Disk",
"image",
"cloning",
"."
] | 3e053e52a45229f96a12db9e98caf7fb3880e811 | https://github.com/F-Secure/see/blob/3e053e52a45229f96a12db9e98caf7fb3880e811/see/context/resources/qemu.py#L289-L326 | train |
F-Secure/see | see/context/resources/qemu.py | QEMUResources._clone_disk | def _clone_disk(self, configuration):
"""Clones the disk and returns the path to the new disk."""
disk_clone(self._hypervisor, self.identifier, self._storage_pool,
configuration, self.provider_image, self.logger)
disk_name = self._storage_pool.listVolumes()[0]
return ... | python | def _clone_disk(self, configuration):
"""Clones the disk and returns the path to the new disk."""
disk_clone(self._hypervisor, self.identifier, self._storage_pool,
configuration, self.provider_image, self.logger)
disk_name = self._storage_pool.listVolumes()[0]
return ... | [
"def",
"_clone_disk",
"(",
"self",
",",
"configuration",
")",
":",
"disk_clone",
"(",
"self",
".",
"_hypervisor",
",",
"self",
".",
"identifier",
",",
"self",
".",
"_storage_pool",
",",
"configuration",
",",
"self",
".",
"provider_image",
",",
"self",
".",
... | Clones the disk and returns the path to the new disk. | [
"Clones",
"the",
"disk",
"and",
"returns",
"the",
"path",
"to",
"the",
"new",
"disk",
"."
] | 3e053e52a45229f96a12db9e98caf7fb3880e811 | https://github.com/F-Secure/see/blob/3e053e52a45229f96a12db9e98caf7fb3880e811/see/context/resources/qemu.py#L412-L418 | train |
F-Secure/see | see/environment.py | load_configuration | def load_configuration(configuration):
"""Returns a dictionary, accepts a dictionary or a path to a JSON file."""
if isinstance(configuration, dict):
return configuration
else:
with open(configuration) as configfile:
return json.load(configfile) | python | def load_configuration(configuration):
"""Returns a dictionary, accepts a dictionary or a path to a JSON file."""
if isinstance(configuration, dict):
return configuration
else:
with open(configuration) as configfile:
return json.load(configfile) | [
"def",
"load_configuration",
"(",
"configuration",
")",
":",
"if",
"isinstance",
"(",
"configuration",
",",
"dict",
")",
":",
"return",
"configuration",
"else",
":",
"with",
"open",
"(",
"configuration",
")",
"as",
"configfile",
":",
"return",
"json",
".",
"... | Returns a dictionary, accepts a dictionary or a path to a JSON file. | [
"Returns",
"a",
"dictionary",
"accepts",
"a",
"dictionary",
"or",
"a",
"path",
"to",
"a",
"JSON",
"file",
"."
] | 3e053e52a45229f96a12db9e98caf7fb3880e811 | https://github.com/F-Secure/see/blob/3e053e52a45229f96a12db9e98caf7fb3880e811/see/environment.py#L102-L108 | train |
F-Secure/see | see/environment.py | cleanup | def cleanup(logger, *args):
"""Environment's cleanup routine."""
for obj in args:
if obj is not None and hasattr(obj, 'cleanup'):
try:
obj.cleanup()
except NotImplementedError:
pass
except Exception:
logger.exception("Un... | python | def cleanup(logger, *args):
"""Environment's cleanup routine."""
for obj in args:
if obj is not None and hasattr(obj, 'cleanup'):
try:
obj.cleanup()
except NotImplementedError:
pass
except Exception:
logger.exception("Un... | [
"def",
"cleanup",
"(",
"logger",
",",
"*",
"args",
")",
":",
"for",
"obj",
"in",
"args",
":",
"if",
"obj",
"is",
"not",
"None",
"and",
"hasattr",
"(",
"obj",
",",
"'cleanup'",
")",
":",
"try",
":",
"obj",
".",
"cleanup",
"(",
")",
"except",
"NotI... | Environment's cleanup routine. | [
"Environment",
"s",
"cleanup",
"routine",
"."
] | 3e053e52a45229f96a12db9e98caf7fb3880e811 | https://github.com/F-Secure/see/blob/3e053e52a45229f96a12db9e98caf7fb3880e811/see/environment.py#L111-L120 | train |
F-Secure/see | see/environment.py | Environment.allocate | def allocate(self):
"""Builds the context and the Hooks."""
self.logger.debug("Allocating environment.")
self._allocate()
self.logger.debug("Environment successfully allocated.") | python | def allocate(self):
"""Builds the context and the Hooks."""
self.logger.debug("Allocating environment.")
self._allocate()
self.logger.debug("Environment successfully allocated.") | [
"def",
"allocate",
"(",
"self",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Allocating environment.\"",
")",
"self",
".",
"_allocate",
"(",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Environment successfully allocated.\"",
")"
] | Builds the context and the Hooks. | [
"Builds",
"the",
"context",
"and",
"the",
"Hooks",
"."
] | 3e053e52a45229f96a12db9e98caf7fb3880e811 | https://github.com/F-Secure/see/blob/3e053e52a45229f96a12db9e98caf7fb3880e811/see/environment.py#L77-L81 | train |
F-Secure/see | see/environment.py | Environment.deallocate | def deallocate(self):
"""Cleans up the context and the Hooks."""
self.logger.debug("Deallocating environment.")
self._deallocate()
self.logger.debug("Environment successfully deallocated.") | python | def deallocate(self):
"""Cleans up the context and the Hooks."""
self.logger.debug("Deallocating environment.")
self._deallocate()
self.logger.debug("Environment successfully deallocated.") | [
"def",
"deallocate",
"(",
"self",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Deallocating environment.\"",
")",
"self",
".",
"_deallocate",
"(",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Environment successfully deallocated.\"",
")"
] | Cleans up the context and the Hooks. | [
"Cleans",
"up",
"the",
"context",
"and",
"the",
"Hooks",
"."
] | 3e053e52a45229f96a12db9e98caf7fb3880e811 | https://github.com/F-Secure/see/blob/3e053e52a45229f96a12db9e98caf7fb3880e811/see/environment.py#L90-L94 | train |
F-Secure/see | see/hooks.py | hooks_factory | def hooks_factory(identifier, configuration, context):
"""
Returns the initialized hooks.
"""
manager = HookManager(identifier, configuration)
manager.load_hooks(context)
return manager | python | def hooks_factory(identifier, configuration, context):
"""
Returns the initialized hooks.
"""
manager = HookManager(identifier, configuration)
manager.load_hooks(context)
return manager | [
"def",
"hooks_factory",
"(",
"identifier",
",",
"configuration",
",",
"context",
")",
":",
"manager",
"=",
"HookManager",
"(",
"identifier",
",",
"configuration",
")",
"manager",
".",
"load_hooks",
"(",
"context",
")",
"return",
"manager"
] | Returns the initialized hooks. | [
"Returns",
"the",
"initialized",
"hooks",
"."
] | 3e053e52a45229f96a12db9e98caf7fb3880e811 | https://github.com/F-Secure/see/blob/3e053e52a45229f96a12db9e98caf7fb3880e811/see/hooks.py#L28-L35 | train |
F-Secure/see | see/hooks.py | HookManager.load_hooks | def load_hooks(self, context):
"""
Initializes the Hooks and loads them within the Environment.
"""
for hook in self.configuration.get('hooks', ()):
config = hook.get('configuration', {})
config.update(self.configuration.get('configuration', {}))
try:... | python | def load_hooks(self, context):
"""
Initializes the Hooks and loads them within the Environment.
"""
for hook in self.configuration.get('hooks', ()):
config = hook.get('configuration', {})
config.update(self.configuration.get('configuration', {}))
try:... | [
"def",
"load_hooks",
"(",
"self",
",",
"context",
")",
":",
"for",
"hook",
"in",
"self",
".",
"configuration",
".",
"get",
"(",
"'hooks'",
",",
"(",
")",
")",
":",
"config",
"=",
"hook",
".",
"get",
"(",
"'configuration'",
",",
"{",
"}",
")",
"conf... | Initializes the Hooks and loads them within the Environment. | [
"Initializes",
"the",
"Hooks",
"and",
"loads",
"them",
"within",
"the",
"Environment",
"."
] | 3e053e52a45229f96a12db9e98caf7fb3880e811 | https://github.com/F-Secure/see/blob/3e053e52a45229f96a12db9e98caf7fb3880e811/see/hooks.py#L50-L61 | train |
hyperledger-archives/indy-anoncreds | anoncreds/protocol/utils.py | get_hash_as_int | def get_hash_as_int(*args, group: cmod.PairingGroup = None):
"""
Enumerate over the input tuple and generate a hash using the tuple values
:param args: sequence of either group or integer elements
:param group: pairing group if an element is a group element
:return:
"""
group = group if gr... | python | def get_hash_as_int(*args, group: cmod.PairingGroup = None):
"""
Enumerate over the input tuple and generate a hash using the tuple values
:param args: sequence of either group or integer elements
:param group: pairing group if an element is a group element
:return:
"""
group = group if gr... | [
"def",
"get_hash_as_int",
"(",
"*",
"args",
",",
"group",
":",
"cmod",
".",
"PairingGroup",
"=",
"None",
")",
":",
"group",
"=",
"group",
"if",
"group",
"else",
"cmod",
".",
"PairingGroup",
"(",
"PAIRING_GROUP",
")",
"h_challenge",
"=",
"sha256",
"(",
")... | Enumerate over the input tuple and generate a hash using the tuple values
:param args: sequence of either group or integer elements
:param group: pairing group if an element is a group element
:return: | [
"Enumerate",
"over",
"the",
"input",
"tuple",
"and",
"generate",
"a",
"hash",
"using",
"the",
"tuple",
"values"
] | 9d9cda3d505c312257d99a13d74d8f05dac3091a | https://github.com/hyperledger-archives/indy-anoncreds/blob/9d9cda3d505c312257d99a13d74d8f05dac3091a/anoncreds/protocol/utils.py#L29-L47 | train |
hyperledger-archives/indy-anoncreds | anoncreds/protocol/utils.py | randomString | def randomString(size: int = 20,
chars: str = string.ascii_letters + string.digits) -> str:
"""
Generate a random string of the specified size.
Ensure that the size is less than the length of chars as this function uses random.choice
which uses random sampling without replacement.
... | python | def randomString(size: int = 20,
chars: str = string.ascii_letters + string.digits) -> str:
"""
Generate a random string of the specified size.
Ensure that the size is less than the length of chars as this function uses random.choice
which uses random sampling without replacement.
... | [
"def",
"randomString",
"(",
"size",
":",
"int",
"=",
"20",
",",
"chars",
":",
"str",
"=",
"string",
".",
"ascii_letters",
"+",
"string",
".",
"digits",
")",
"->",
"str",
":",
"return",
"''",
".",
"join",
"(",
"sample",
"(",
"chars",
",",
"size",
")... | Generate a random string of the specified size.
Ensure that the size is less than the length of chars as this function uses random.choice
which uses random sampling without replacement.
:param size: size of the random string to generate
:param chars: the set of characters to use to generate the random... | [
"Generate",
"a",
"random",
"string",
"of",
"the",
"specified",
"size",
"."
] | 9d9cda3d505c312257d99a13d74d8f05dac3091a | https://github.com/hyperledger-archives/indy-anoncreds/blob/9d9cda3d505c312257d99a13d74d8f05dac3091a/anoncreds/protocol/utils.py#L200-L213 | train |
hyperledger-archives/indy-anoncreds | anoncreds/protocol/utils.py | genPrime | def genPrime():
"""
Generate 2 large primes `p_prime` and `q_prime` and use them
to generate another 2 primes `p` and `q` of 1024 bits
"""
prime = cmod.randomPrime(LARGE_PRIME)
i = 0
while not cmod.isPrime(2 * prime + 1):
prime = cmod.randomPrime(LARGE_PRIME)
i += 1
retur... | python | def genPrime():
"""
Generate 2 large primes `p_prime` and `q_prime` and use them
to generate another 2 primes `p` and `q` of 1024 bits
"""
prime = cmod.randomPrime(LARGE_PRIME)
i = 0
while not cmod.isPrime(2 * prime + 1):
prime = cmod.randomPrime(LARGE_PRIME)
i += 1
retur... | [
"def",
"genPrime",
"(",
")",
":",
"prime",
"=",
"cmod",
".",
"randomPrime",
"(",
"LARGE_PRIME",
")",
"i",
"=",
"0",
"while",
"not",
"cmod",
".",
"isPrime",
"(",
"2",
"*",
"prime",
"+",
"1",
")",
":",
"prime",
"=",
"cmod",
".",
"randomPrime",
"(",
... | Generate 2 large primes `p_prime` and `q_prime` and use them
to generate another 2 primes `p` and `q` of 1024 bits | [
"Generate",
"2",
"large",
"primes",
"p_prime",
"and",
"q_prime",
"and",
"use",
"them",
"to",
"generate",
"another",
"2",
"primes",
"p",
"and",
"q",
"of",
"1024",
"bits"
] | 9d9cda3d505c312257d99a13d74d8f05dac3091a | https://github.com/hyperledger-archives/indy-anoncreds/blob/9d9cda3d505c312257d99a13d74d8f05dac3091a/anoncreds/protocol/utils.py#L264-L274 | train |
hyperledger-archives/indy-anoncreds | anoncreds/protocol/types.py | Attribs.encoded | def encoded(self):
"""
This function will encode all the attributes to 256 bit integers
:return:
"""
encoded = {}
for i in range(len(self.credType.names)):
self.credType.names[i]
attr_types = self.credType.attrTypes[i]
for at in attr... | python | def encoded(self):
"""
This function will encode all the attributes to 256 bit integers
:return:
"""
encoded = {}
for i in range(len(self.credType.names)):
self.credType.names[i]
attr_types = self.credType.attrTypes[i]
for at in attr... | [
"def",
"encoded",
"(",
"self",
")",
":",
"encoded",
"=",
"{",
"}",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"credType",
".",
"names",
")",
")",
":",
"self",
".",
"credType",
".",
"names",
"[",
"i",
"]",
"attr_types",
"=",
"self",
... | This function will encode all the attributes to 256 bit integers
:return: | [
"This",
"function",
"will",
"encode",
"all",
"the",
"attributes",
"to",
"256",
"bit",
"integers"
] | 9d9cda3d505c312257d99a13d74d8f05dac3091a | https://github.com/hyperledger-archives/indy-anoncreds/blob/9d9cda3d505c312257d99a13d74d8f05dac3091a/anoncreds/protocol/types.py#L77-L96 | train |
hyperledger-archives/indy-anoncreds | anoncreds/protocol/issuer.py | Issuer.genSchema | async def genSchema(self, name, version, attrNames) -> Schema:
"""
Generates and submits Schema.
:param name: schema name
:param version: schema version
:param attrNames: a list of attributes the schema contains
:return: submitted Schema
"""
schema = Sche... | python | async def genSchema(self, name, version, attrNames) -> Schema:
"""
Generates and submits Schema.
:param name: schema name
:param version: schema version
:param attrNames: a list of attributes the schema contains
:return: submitted Schema
"""
schema = Sche... | [
"async",
"def",
"genSchema",
"(",
"self",
",",
"name",
",",
"version",
",",
"attrNames",
")",
"->",
"Schema",
":",
"schema",
"=",
"Schema",
"(",
"name",
",",
"version",
",",
"attrNames",
",",
"self",
".",
"issuerId",
")",
"return",
"await",
"self",
"."... | Generates and submits Schema.
:param name: schema name
:param version: schema version
:param attrNames: a list of attributes the schema contains
:return: submitted Schema | [
"Generates",
"and",
"submits",
"Schema",
"."
] | 9d9cda3d505c312257d99a13d74d8f05dac3091a | https://github.com/hyperledger-archives/indy-anoncreds/blob/9d9cda3d505c312257d99a13d74d8f05dac3091a/anoncreds/protocol/issuer.py#L34-L44 | train |
hyperledger-archives/indy-anoncreds | anoncreds/protocol/issuer.py | Issuer.issueAccumulator | async def issueAccumulator(self, schemaId: ID, iA,
L) -> AccumulatorPublicKey:
"""
Issues and submits an accumulator used for non-revocation proof.
:param schemaId: The schema ID (reference to claim
definition schema)
:param iA: accumulator ID
... | python | async def issueAccumulator(self, schemaId: ID, iA,
L) -> AccumulatorPublicKey:
"""
Issues and submits an accumulator used for non-revocation proof.
:param schemaId: The schema ID (reference to claim
definition schema)
:param iA: accumulator ID
... | [
"async",
"def",
"issueAccumulator",
"(",
"self",
",",
"schemaId",
":",
"ID",
",",
"iA",
",",
"L",
")",
"->",
"AccumulatorPublicKey",
":",
"accum",
",",
"tails",
",",
"accPK",
",",
"accSK",
"=",
"await",
"self",
".",
"_nonRevocationIssuer",
".",
"issueAccum... | Issues and submits an accumulator used for non-revocation proof.
:param schemaId: The schema ID (reference to claim
definition schema)
:param iA: accumulator ID
:param L: maximum number of claims within accumulator.
:return: Submitted accumulator public key | [
"Issues",
"and",
"submits",
"an",
"accumulator",
"used",
"for",
"non",
"-",
"revocation",
"proof",
"."
] | 9d9cda3d505c312257d99a13d74d8f05dac3091a | https://github.com/hyperledger-archives/indy-anoncreds/blob/9d9cda3d505c312257d99a13d74d8f05dac3091a/anoncreds/protocol/issuer.py#L66-L84 | train |
hyperledger-archives/indy-anoncreds | anoncreds/protocol/issuer.py | Issuer.revoke | async def revoke(self, schemaId: ID, i):
"""
Performs revocation of a Claim.
:param schemaId: The schema ID (reference to claim
definition schema)
:param i: claim's sequence number within accumulator
"""
acc, ts = await self._nonRevocationIssuer.revoke(schemaId, ... | python | async def revoke(self, schemaId: ID, i):
"""
Performs revocation of a Claim.
:param schemaId: The schema ID (reference to claim
definition schema)
:param i: claim's sequence number within accumulator
"""
acc, ts = await self._nonRevocationIssuer.revoke(schemaId, ... | [
"async",
"def",
"revoke",
"(",
"self",
",",
"schemaId",
":",
"ID",
",",
"i",
")",
":",
"acc",
",",
"ts",
"=",
"await",
"self",
".",
"_nonRevocationIssuer",
".",
"revoke",
"(",
"schemaId",
",",
"i",
")",
"await",
"self",
".",
"wallet",
".",
"submitAcc... | Performs revocation of a Claim.
:param schemaId: The schema ID (reference to claim
definition schema)
:param i: claim's sequence number within accumulator | [
"Performs",
"revocation",
"of",
"a",
"Claim",
"."
] | 9d9cda3d505c312257d99a13d74d8f05dac3091a | https://github.com/hyperledger-archives/indy-anoncreds/blob/9d9cda3d505c312257d99a13d74d8f05dac3091a/anoncreds/protocol/issuer.py#L86-L96 | train |
hyperledger-archives/indy-anoncreds | anoncreds/protocol/issuer.py | Issuer.issueClaim | async def issueClaim(self, schemaId: ID, claimRequest: ClaimRequest,
iA=None,
i=None) -> (Claims, Dict[str, ClaimAttributeValues]):
"""
Issue a claim for the given user and schema.
:param schemaId: The schema ID (reference to claim
defin... | python | async def issueClaim(self, schemaId: ID, claimRequest: ClaimRequest,
iA=None,
i=None) -> (Claims, Dict[str, ClaimAttributeValues]):
"""
Issue a claim for the given user and schema.
:param schemaId: The schema ID (reference to claim
defin... | [
"async",
"def",
"issueClaim",
"(",
"self",
",",
"schemaId",
":",
"ID",
",",
"claimRequest",
":",
"ClaimRequest",
",",
"iA",
"=",
"None",
",",
"i",
"=",
"None",
")",
"->",
"(",
"Claims",
",",
"Dict",
"[",
"str",
",",
"ClaimAttributeValues",
"]",
")",
... | Issue a claim for the given user and schema.
:param schemaId: The schema ID (reference to claim
definition schema)
:param claimRequest: A claim request containing prover ID and
prover-generated values
:param iA: accumulator ID
:param i: claim's sequence number within acc... | [
"Issue",
"a",
"claim",
"for",
"the",
"given",
"user",
"and",
"schema",
"."
] | 9d9cda3d505c312257d99a13d74d8f05dac3091a | https://github.com/hyperledger-archives/indy-anoncreds/blob/9d9cda3d505c312257d99a13d74d8f05dac3091a/anoncreds/protocol/issuer.py#L98-L132 | train |
hyperledger-archives/indy-anoncreds | anoncreds/protocol/issuer.py | Issuer.issueClaims | async def issueClaims(self, allClaimRequest: Dict[ID, ClaimRequest]) -> \
Dict[ID, Claims]:
"""
Issue claims for the given users and schemas.
:param allClaimRequest: a map of schema ID to a claim
request containing prover ID and prover-generated values
:return: The c... | python | async def issueClaims(self, allClaimRequest: Dict[ID, ClaimRequest]) -> \
Dict[ID, Claims]:
"""
Issue claims for the given users and schemas.
:param allClaimRequest: a map of schema ID to a claim
request containing prover ID and prover-generated values
:return: The c... | [
"async",
"def",
"issueClaims",
"(",
"self",
",",
"allClaimRequest",
":",
"Dict",
"[",
"ID",
",",
"ClaimRequest",
"]",
")",
"->",
"Dict",
"[",
"ID",
",",
"Claims",
"]",
":",
"res",
"=",
"{",
"}",
"for",
"schemaId",
",",
"claimReq",
"in",
"allClaimReques... | Issue claims for the given users and schemas.
:param allClaimRequest: a map of schema ID to a claim
request containing prover ID and prover-generated values
:return: The claims (both primary and non-revocation) | [
"Issue",
"claims",
"for",
"the",
"given",
"users",
"and",
"schemas",
"."
] | 9d9cda3d505c312257d99a13d74d8f05dac3091a | https://github.com/hyperledger-archives/indy-anoncreds/blob/9d9cda3d505c312257d99a13d74d8f05dac3091a/anoncreds/protocol/issuer.py#L134-L146 | train |
hyperledger-archives/indy-anoncreds | anoncreds/protocol/verifier.py | Verifier.verify | async def verify(self, proofRequest: ProofRequest, proof: FullProof):
"""
Verifies a proof from the prover.
:param proofRequest: description of a proof to be presented (revealed
attributes, predicates, timestamps for non-revocation)
:param proof: a proof
:return: True if... | python | async def verify(self, proofRequest: ProofRequest, proof: FullProof):
"""
Verifies a proof from the prover.
:param proofRequest: description of a proof to be presented (revealed
attributes, predicates, timestamps for non-revocation)
:param proof: a proof
:return: True if... | [
"async",
"def",
"verify",
"(",
"self",
",",
"proofRequest",
":",
"ProofRequest",
",",
"proof",
":",
"FullProof",
")",
":",
"if",
"proofRequest",
".",
"verifiableAttributes",
".",
"keys",
"(",
")",
"!=",
"proof",
".",
"requestedProof",
".",
"revealed_attrs",
... | Verifies a proof from the prover.
:param proofRequest: description of a proof to be presented (revealed
attributes, predicates, timestamps for non-revocation)
:param proof: a proof
:return: True if verified successfully and false otherwise. | [
"Verifies",
"a",
"proof",
"from",
"the",
"prover",
"."
] | 9d9cda3d505c312257d99a13d74d8f05dac3091a | https://github.com/hyperledger-archives/indy-anoncreds/blob/9d9cda3d505c312257d99a13d74d8f05dac3091a/anoncreds/protocol/verifier.py#L27-L59 | train |
hyperledger-archives/indy-anoncreds | anoncreds/protocol/prover.py | Prover.processClaim | async def processClaim(self, schemaId: ID, claimAttributes: Dict[str, ClaimAttributeValues], signature: Claims):
"""
Processes and saves a received Claim for the given Schema.
:param schemaId: The schema ID (reference to claim
definition schema)
:param claims: claims to be proce... | python | async def processClaim(self, schemaId: ID, claimAttributes: Dict[str, ClaimAttributeValues], signature: Claims):
"""
Processes and saves a received Claim for the given Schema.
:param schemaId: The schema ID (reference to claim
definition schema)
:param claims: claims to be proce... | [
"async",
"def",
"processClaim",
"(",
"self",
",",
"schemaId",
":",
"ID",
",",
"claimAttributes",
":",
"Dict",
"[",
"str",
",",
"ClaimAttributeValues",
"]",
",",
"signature",
":",
"Claims",
")",
":",
"await",
"self",
".",
"wallet",
".",
"submitContextAttr",
... | Processes and saves a received Claim for the given Schema.
:param schemaId: The schema ID (reference to claim
definition schema)
:param claims: claims to be processed and saved | [
"Processes",
"and",
"saves",
"a",
"received",
"Claim",
"for",
"the",
"given",
"Schema",
"."
] | 9d9cda3d505c312257d99a13d74d8f05dac3091a | https://github.com/hyperledger-archives/indy-anoncreds/blob/9d9cda3d505c312257d99a13d74d8f05dac3091a/anoncreds/protocol/prover.py#L75-L88 | train |
hyperledger-archives/indy-anoncreds | anoncreds/protocol/prover.py | Prover.processClaims | async def processClaims(self, allClaims: Dict[ID, Claims]):
"""
Processes and saves received Claims.
:param claims: claims to be processed and saved for each claim
definition.
"""
res = []
for schemaId, (claim_signature, claim_attributes) in allClaims.items():
... | python | async def processClaims(self, allClaims: Dict[ID, Claims]):
"""
Processes and saves received Claims.
:param claims: claims to be processed and saved for each claim
definition.
"""
res = []
for schemaId, (claim_signature, claim_attributes) in allClaims.items():
... | [
"async",
"def",
"processClaims",
"(",
"self",
",",
"allClaims",
":",
"Dict",
"[",
"ID",
",",
"Claims",
"]",
")",
":",
"res",
"=",
"[",
"]",
"for",
"schemaId",
",",
"(",
"claim_signature",
",",
"claim_attributes",
")",
"in",
"allClaims",
".",
"items",
"... | Processes and saves received Claims.
:param claims: claims to be processed and saved for each claim
definition. | [
"Processes",
"and",
"saves",
"received",
"Claims",
"."
] | 9d9cda3d505c312257d99a13d74d8f05dac3091a | https://github.com/hyperledger-archives/indy-anoncreds/blob/9d9cda3d505c312257d99a13d74d8f05dac3091a/anoncreds/protocol/prover.py#L90-L100 | train |
hyperledger-archives/indy-anoncreds | anoncreds/protocol/prover.py | Prover.presentProof | async def presentProof(self, proofRequest: ProofRequest) -> FullProof:
"""
Presents a proof to the verifier.
:param proofRequest: description of a proof to be presented (revealed
attributes, predicates, timestamps for non-revocation)
:return: a proof (both primary and non-revoca... | python | async def presentProof(self, proofRequest: ProofRequest) -> FullProof:
"""
Presents a proof to the verifier.
:param proofRequest: description of a proof to be presented (revealed
attributes, predicates, timestamps for non-revocation)
:return: a proof (both primary and non-revoca... | [
"async",
"def",
"presentProof",
"(",
"self",
",",
"proofRequest",
":",
"ProofRequest",
")",
"->",
"FullProof",
":",
"claims",
",",
"requestedProof",
"=",
"await",
"self",
".",
"_findClaims",
"(",
"proofRequest",
")",
"proof",
"=",
"await",
"self",
".",
"_pre... | Presents a proof to the verifier.
:param proofRequest: description of a proof to be presented (revealed
attributes, predicates, timestamps for non-revocation)
:return: a proof (both primary and non-revocation) and revealed attributes (initial non-encoded values) | [
"Presents",
"a",
"proof",
"to",
"the",
"verifier",
"."
] | 9d9cda3d505c312257d99a13d74d8f05dac3091a | https://github.com/hyperledger-archives/indy-anoncreds/blob/9d9cda3d505c312257d99a13d74d8f05dac3091a/anoncreds/protocol/prover.py#L102-L112 | train |
aio-libs/aiozipkin | aiozipkin/utils.py | unsigned_hex_to_signed_int | def unsigned_hex_to_signed_int(hex_string: str) -> int:
"""Converts a 64-bit hex string to a signed int value.
This is due to the fact that Apache Thrift only has signed values.
Examples:
'17133d482ba4f605' => 1662740067609015813
'b6dbb1c2b362bf51' => -5270423489115668655
:param hex_s... | python | def unsigned_hex_to_signed_int(hex_string: str) -> int:
"""Converts a 64-bit hex string to a signed int value.
This is due to the fact that Apache Thrift only has signed values.
Examples:
'17133d482ba4f605' => 1662740067609015813
'b6dbb1c2b362bf51' => -5270423489115668655
:param hex_s... | [
"def",
"unsigned_hex_to_signed_int",
"(",
"hex_string",
":",
"str",
")",
"->",
"int",
":",
"v",
"=",
"struct",
".",
"unpack",
"(",
"'q'",
",",
"struct",
".",
"pack",
"(",
"'Q'",
",",
"int",
"(",
"hex_string",
",",
"16",
")",
")",
")",
"[",
"0",
"]"... | Converts a 64-bit hex string to a signed int value.
This is due to the fact that Apache Thrift only has signed values.
Examples:
'17133d482ba4f605' => 1662740067609015813
'b6dbb1c2b362bf51' => -5270423489115668655
:param hex_string: the string representation of a zipkin ID
:returns: s... | [
"Converts",
"a",
"64",
"-",
"bit",
"hex",
"string",
"to",
"a",
"signed",
"int",
"value",
"."
] | 970d6096719819b6b83435e279e04a850c12d985 | https://github.com/aio-libs/aiozipkin/blob/970d6096719819b6b83435e279e04a850c12d985/aiozipkin/utils.py#L27-L41 | train |
aio-libs/aiozipkin | aiozipkin/utils.py | signed_int_to_unsigned_hex | def signed_int_to_unsigned_hex(signed_int: int) -> str:
"""Converts a signed int value to a 64-bit hex string.
Examples:
1662740067609015813 => '17133d482ba4f605'
-5270423489115668655 => 'b6dbb1c2b362bf51'
:param signed_int: an int to convert
:returns: unsigned hex string
"""
... | python | def signed_int_to_unsigned_hex(signed_int: int) -> str:
"""Converts a signed int value to a 64-bit hex string.
Examples:
1662740067609015813 => '17133d482ba4f605'
-5270423489115668655 => 'b6dbb1c2b362bf51'
:param signed_int: an int to convert
:returns: unsigned hex string
"""
... | [
"def",
"signed_int_to_unsigned_hex",
"(",
"signed_int",
":",
"int",
")",
"->",
"str",
":",
"hex_string",
"=",
"hex",
"(",
"struct",
".",
"unpack",
"(",
"'Q'",
",",
"struct",
".",
"pack",
"(",
"'q'",
",",
"signed_int",
")",
")",
"[",
"0",
"]",
")",
"[... | Converts a signed int value to a 64-bit hex string.
Examples:
1662740067609015813 => '17133d482ba4f605'
-5270423489115668655 => 'b6dbb1c2b362bf51'
:param signed_int: an int to convert
:returns: unsigned hex string | [
"Converts",
"a",
"signed",
"int",
"value",
"to",
"a",
"64",
"-",
"bit",
"hex",
"string",
"."
] | 970d6096719819b6b83435e279e04a850c12d985 | https://github.com/aio-libs/aiozipkin/blob/970d6096719819b6b83435e279e04a850c12d985/aiozipkin/utils.py#L44-L57 | train |
aio-libs/aiozipkin | aiozipkin/aiohttp_helpers.py | setup | def setup(app: Application,
tracer: Tracer, *,
skip_routes: Optional[AbstractRoute] = None,
tracer_key: str = APP_AIOZIPKIN_KEY,
request_key: str = REQUEST_AIOZIPKIN_KEY) -> Application:
"""Sets required parameters in aiohttp applications for aiozipkin.
Tracer added into... | python | def setup(app: Application,
tracer: Tracer, *,
skip_routes: Optional[AbstractRoute] = None,
tracer_key: str = APP_AIOZIPKIN_KEY,
request_key: str = REQUEST_AIOZIPKIN_KEY) -> Application:
"""Sets required parameters in aiohttp applications for aiozipkin.
Tracer added into... | [
"def",
"setup",
"(",
"app",
":",
"Application",
",",
"tracer",
":",
"Tracer",
",",
"*",
",",
"skip_routes",
":",
"Optional",
"[",
"AbstractRoute",
"]",
"=",
"None",
",",
"tracer_key",
":",
"str",
"=",
"APP_AIOZIPKIN_KEY",
",",
"request_key",
":",
"str",
... | Sets required parameters in aiohttp applications for aiozipkin.
Tracer added into application context and cleaned after application
shutdown. You can provide custom tracer_key, if default name is not
suitable. | [
"Sets",
"required",
"parameters",
"in",
"aiohttp",
"applications",
"for",
"aiozipkin",
"."
] | 970d6096719819b6b83435e279e04a850c12d985 | https://github.com/aio-libs/aiozipkin/blob/970d6096719819b6b83435e279e04a850c12d985/aiozipkin/aiohttp_helpers.py#L155-L178 | train |
aio-libs/aiozipkin | aiozipkin/aiohttp_helpers.py | get_tracer | def get_tracer(
app: Application, tracer_key: str = APP_AIOZIPKIN_KEY) -> Tracer:
"""Returns tracer object from application context.
By default tracer has APP_AIOZIPKIN_KEY in aiohttp application context,
you can provide own key, if for some reason default one is not suitable.
"""
return ca... | python | def get_tracer(
app: Application, tracer_key: str = APP_AIOZIPKIN_KEY) -> Tracer:
"""Returns tracer object from application context.
By default tracer has APP_AIOZIPKIN_KEY in aiohttp application context,
you can provide own key, if for some reason default one is not suitable.
"""
return ca... | [
"def",
"get_tracer",
"(",
"app",
":",
"Application",
",",
"tracer_key",
":",
"str",
"=",
"APP_AIOZIPKIN_KEY",
")",
"->",
"Tracer",
":",
"return",
"cast",
"(",
"Tracer",
",",
"app",
"[",
"tracer_key",
"]",
")"
] | Returns tracer object from application context.
By default tracer has APP_AIOZIPKIN_KEY in aiohttp application context,
you can provide own key, if for some reason default one is not suitable. | [
"Returns",
"tracer",
"object",
"from",
"application",
"context",
"."
] | 970d6096719819b6b83435e279e04a850c12d985 | https://github.com/aio-libs/aiozipkin/blob/970d6096719819b6b83435e279e04a850c12d985/aiozipkin/aiohttp_helpers.py#L181-L188 | train |
aio-libs/aiozipkin | aiozipkin/aiohttp_helpers.py | request_span | def request_span(request: Request,
request_key: str = REQUEST_AIOZIPKIN_KEY) -> SpanAbc:
"""Returns span created by middleware from request context, you can use it
as parent on next child span.
"""
return cast(SpanAbc, request[request_key]) | python | def request_span(request: Request,
request_key: str = REQUEST_AIOZIPKIN_KEY) -> SpanAbc:
"""Returns span created by middleware from request context, you can use it
as parent on next child span.
"""
return cast(SpanAbc, request[request_key]) | [
"def",
"request_span",
"(",
"request",
":",
"Request",
",",
"request_key",
":",
"str",
"=",
"REQUEST_AIOZIPKIN_KEY",
")",
"->",
"SpanAbc",
":",
"return",
"cast",
"(",
"SpanAbc",
",",
"request",
"[",
"request_key",
"]",
")"
] | Returns span created by middleware from request context, you can use it
as parent on next child span. | [
"Returns",
"span",
"created",
"by",
"middleware",
"from",
"request",
"context",
"you",
"can",
"use",
"it",
"as",
"parent",
"on",
"next",
"child",
"span",
"."
] | 970d6096719819b6b83435e279e04a850c12d985 | https://github.com/aio-libs/aiozipkin/blob/970d6096719819b6b83435e279e04a850c12d985/aiozipkin/aiohttp_helpers.py#L191-L196 | train |
aio-libs/aiozipkin | aiozipkin/aiohttp_helpers.py | make_trace_config | def make_trace_config(tracer: Tracer) -> aiohttp.TraceConfig:
"""Creates aiohttp.TraceConfig with enabled aiozipking instrumentation
for aiohttp client.
"""
trace_config = aiohttp.TraceConfig()
zipkin = ZipkinClientSignals(tracer)
trace_config.on_request_start.append(zipkin.on_request_start)
... | python | def make_trace_config(tracer: Tracer) -> aiohttp.TraceConfig:
"""Creates aiohttp.TraceConfig with enabled aiozipking instrumentation
for aiohttp client.
"""
trace_config = aiohttp.TraceConfig()
zipkin = ZipkinClientSignals(tracer)
trace_config.on_request_start.append(zipkin.on_request_start)
... | [
"def",
"make_trace_config",
"(",
"tracer",
":",
"Tracer",
")",
"->",
"aiohttp",
".",
"TraceConfig",
":",
"trace_config",
"=",
"aiohttp",
".",
"TraceConfig",
"(",
")",
"zipkin",
"=",
"ZipkinClientSignals",
"(",
"tracer",
")",
"trace_config",
".",
"on_request_star... | Creates aiohttp.TraceConfig with enabled aiozipking instrumentation
for aiohttp client. | [
"Creates",
"aiohttp",
".",
"TraceConfig",
"with",
"enabled",
"aiozipking",
"instrumentation",
"for",
"aiohttp",
"client",
"."
] | 970d6096719819b6b83435e279e04a850c12d985 | https://github.com/aio-libs/aiozipkin/blob/970d6096719819b6b83435e279e04a850c12d985/aiozipkin/aiohttp_helpers.py#L277-L287 | train |
aio-libs/aiozipkin | aiozipkin/helpers.py | create_endpoint | def create_endpoint(service_name: str, *,
ipv4: OptStr = None,
ipv6: OptStr = None,
port: OptInt = None) -> Endpoint:
"""Factory function to create Endpoint object.
"""
return Endpoint(service_name, ipv4, ipv6, port) | python | def create_endpoint(service_name: str, *,
ipv4: OptStr = None,
ipv6: OptStr = None,
port: OptInt = None) -> Endpoint:
"""Factory function to create Endpoint object.
"""
return Endpoint(service_name, ipv4, ipv6, port) | [
"def",
"create_endpoint",
"(",
"service_name",
":",
"str",
",",
"*",
",",
"ipv4",
":",
"OptStr",
"=",
"None",
",",
"ipv6",
":",
"OptStr",
"=",
"None",
",",
"port",
":",
"OptInt",
"=",
"None",
")",
"->",
"Endpoint",
":",
"return",
"Endpoint",
"(",
"se... | Factory function to create Endpoint object. | [
"Factory",
"function",
"to",
"create",
"Endpoint",
"object",
"."
] | 970d6096719819b6b83435e279e04a850c12d985 | https://github.com/aio-libs/aiozipkin/blob/970d6096719819b6b83435e279e04a850c12d985/aiozipkin/helpers.py#L62-L68 | train |
aio-libs/aiozipkin | aiozipkin/helpers.py | make_headers | def make_headers(context: TraceContext) -> Headers:
"""Creates dict with zipkin headers from supplied trace context.
"""
headers = {
TRACE_ID_HEADER: context.trace_id,
SPAN_ID_HEADER: context.span_id,
FLAGS_HEADER: '0',
SAMPLED_ID_HEADER: '1' if context.sampled else '0',
... | python | def make_headers(context: TraceContext) -> Headers:
"""Creates dict with zipkin headers from supplied trace context.
"""
headers = {
TRACE_ID_HEADER: context.trace_id,
SPAN_ID_HEADER: context.span_id,
FLAGS_HEADER: '0',
SAMPLED_ID_HEADER: '1' if context.sampled else '0',
... | [
"def",
"make_headers",
"(",
"context",
":",
"TraceContext",
")",
"->",
"Headers",
":",
"headers",
"=",
"{",
"TRACE_ID_HEADER",
":",
"context",
".",
"trace_id",
",",
"SPAN_ID_HEADER",
":",
"context",
".",
"span_id",
",",
"FLAGS_HEADER",
":",
"'0'",
",",
"SAMP... | Creates dict with zipkin headers from supplied trace context. | [
"Creates",
"dict",
"with",
"zipkin",
"headers",
"from",
"supplied",
"trace",
"context",
"."
] | 970d6096719819b6b83435e279e04a850c12d985 | https://github.com/aio-libs/aiozipkin/blob/970d6096719819b6b83435e279e04a850c12d985/aiozipkin/helpers.py#L79-L90 | train |
aio-libs/aiozipkin | aiozipkin/helpers.py | make_single_header | def make_single_header(context: TraceContext) -> Headers:
"""Creates dict with zipkin single header format.
"""
# b3={TraceId}-{SpanId}-{SamplingState}-{ParentSpanId}
c = context
# encode sampled flag
if c.debug:
sampled = 'd'
elif c.sampled:
sampled = '1'
else:
... | python | def make_single_header(context: TraceContext) -> Headers:
"""Creates dict with zipkin single header format.
"""
# b3={TraceId}-{SpanId}-{SamplingState}-{ParentSpanId}
c = context
# encode sampled flag
if c.debug:
sampled = 'd'
elif c.sampled:
sampled = '1'
else:
... | [
"def",
"make_single_header",
"(",
"context",
":",
"TraceContext",
")",
"->",
"Headers",
":",
"# b3={TraceId}-{SpanId}-{SamplingState}-{ParentSpanId}",
"c",
"=",
"context",
"# encode sampled flag",
"if",
"c",
".",
"debug",
":",
"sampled",
"=",
"'d'",
"elif",
"c",
"."... | Creates dict with zipkin single header format. | [
"Creates",
"dict",
"with",
"zipkin",
"single",
"header",
"format",
"."
] | 970d6096719819b6b83435e279e04a850c12d985 | https://github.com/aio-libs/aiozipkin/blob/970d6096719819b6b83435e279e04a850c12d985/aiozipkin/helpers.py#L93-L113 | train |
aio-libs/aiozipkin | aiozipkin/helpers.py | make_context | def make_context(headers: Headers) -> Optional[TraceContext]:
"""Converts available headers to TraceContext, if headers mapping does
not contain zipkin headers, function returns None.
"""
# TODO: add validation for trace_id/span_id/parent_id
# normalize header names just in case someone passed regu... | python | def make_context(headers: Headers) -> Optional[TraceContext]:
"""Converts available headers to TraceContext, if headers mapping does
not contain zipkin headers, function returns None.
"""
# TODO: add validation for trace_id/span_id/parent_id
# normalize header names just in case someone passed regu... | [
"def",
"make_context",
"(",
"headers",
":",
"Headers",
")",
"->",
"Optional",
"[",
"TraceContext",
"]",
":",
"# TODO: add validation for trace_id/span_id/parent_id",
"# normalize header names just in case someone passed regular dict",
"# instead dict with case insensitive keys",
"hea... | Converts available headers to TraceContext, if headers mapping does
not contain zipkin headers, function returns None. | [
"Converts",
"available",
"headers",
"to",
"TraceContext",
"if",
"headers",
"mapping",
"does",
"not",
"contain",
"zipkin",
"headers",
"function",
"returns",
"None",
"."
] | 970d6096719819b6b83435e279e04a850c12d985 | https://github.com/aio-libs/aiozipkin/blob/970d6096719819b6b83435e279e04a850c12d985/aiozipkin/helpers.py#L177-L206 | train |
aio-libs/aiozipkin | aiozipkin/helpers.py | filter_none | def filter_none(data: Dict[str, Any],
keys: OptKeys = None) -> Dict[str, Any]:
"""Filter keys from dict with None values.
Check occurs only on root level. If list of keys specified, filter
works only for selected keys
"""
def limited_filter(k: str, v: Any) -> bool:
return k... | python | def filter_none(data: Dict[str, Any],
keys: OptKeys = None) -> Dict[str, Any]:
"""Filter keys from dict with None values.
Check occurs only on root level. If list of keys specified, filter
works only for selected keys
"""
def limited_filter(k: str, v: Any) -> bool:
return k... | [
"def",
"filter_none",
"(",
"data",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
",",
"keys",
":",
"OptKeys",
"=",
"None",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"def",
"limited_filter",
"(",
"k",
":",
"str",
",",
"v",
":",
"Any",
")"... | Filter keys from dict with None values.
Check occurs only on root level. If list of keys specified, filter
works only for selected keys | [
"Filter",
"keys",
"from",
"dict",
"with",
"None",
"values",
"."
] | 970d6096719819b6b83435e279e04a850c12d985 | https://github.com/aio-libs/aiozipkin/blob/970d6096719819b6b83435e279e04a850c12d985/aiozipkin/helpers.py#L212-L227 | train |
gem/oq-engine | openquake/hazardlib/gsim/cauzzi_faccioli_2008.py | CauzziFaccioli2008._compute_faulting_style_term | def _compute_faulting_style_term(self, C, rake):
"""
Compute faulting style term as a function of rake angle value as given
in equation 5 page 465.
"""
if rake > -120.0 and rake <= -60.0:
return C['aN']
elif rake > 30.0 and rake <= 150.0:
return C[... | python | def _compute_faulting_style_term(self, C, rake):
"""
Compute faulting style term as a function of rake angle value as given
in equation 5 page 465.
"""
if rake > -120.0 and rake <= -60.0:
return C['aN']
elif rake > 30.0 and rake <= 150.0:
return C[... | [
"def",
"_compute_faulting_style_term",
"(",
"self",
",",
"C",
",",
"rake",
")",
":",
"if",
"rake",
">",
"-",
"120.0",
"and",
"rake",
"<=",
"-",
"60.0",
":",
"return",
"C",
"[",
"'aN'",
"]",
"elif",
"rake",
">",
"30.0",
"and",
"rake",
"<=",
"150.0",
... | Compute faulting style term as a function of rake angle value as given
in equation 5 page 465. | [
"Compute",
"faulting",
"style",
"term",
"as",
"a",
"function",
"of",
"rake",
"angle",
"value",
"as",
"given",
"in",
"equation",
"5",
"page",
"465",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/cauzzi_faccioli_2008.py#L141-L151 | train |
gem/oq-engine | openquake/hazardlib/gsim/cauzzi_faccioli_2008.py | CauzziFaccioli2008._compute_mean | def _compute_mean(self, C, mag, dists, vs30, rake, imt):
"""
Compute mean value for PGV, PGA and Displacement responce spectrum,
as given in equation 2, page 462 with the addition of the faulting
style term as given in equation 5, page 465. Converts also
displacement responce spe... | python | def _compute_mean(self, C, mag, dists, vs30, rake, imt):
"""
Compute mean value for PGV, PGA and Displacement responce spectrum,
as given in equation 2, page 462 with the addition of the faulting
style term as given in equation 5, page 465. Converts also
displacement responce spe... | [
"def",
"_compute_mean",
"(",
"self",
",",
"C",
",",
"mag",
",",
"dists",
",",
"vs30",
",",
"rake",
",",
"imt",
")",
":",
"mean",
"=",
"(",
"self",
".",
"_compute_term_1_2",
"(",
"C",
",",
"mag",
")",
"+",
"self",
".",
"_compute_term_3",
"(",
"C",
... | Compute mean value for PGV, PGA and Displacement responce spectrum,
as given in equation 2, page 462 with the addition of the faulting
style term as given in equation 5, page 465. Converts also
displacement responce spectrum values to SA. | [
"Compute",
"mean",
"value",
"for",
"PGV",
"PGA",
"and",
"Displacement",
"responce",
"spectrum",
"as",
"given",
"in",
"equation",
"2",
"page",
"462",
"with",
"the",
"addition",
"of",
"the",
"faulting",
"style",
"term",
"as",
"given",
"in",
"equation",
"5",
... | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/cauzzi_faccioli_2008.py#L153-L175 | train |
gem/oq-engine | openquake/hazardlib/calc/gmf.py | ground_motion_fields | def ground_motion_fields(rupture, sites, imts, gsim, truncation_level,
realizations, correlation_model=None, seed=None):
"""
Given an earthquake rupture, the ground motion field calculator computes
ground shaking over a set of sites, by randomly sampling a ground shaking
intensi... | python | def ground_motion_fields(rupture, sites, imts, gsim, truncation_level,
realizations, correlation_model=None, seed=None):
"""
Given an earthquake rupture, the ground motion field calculator computes
ground shaking over a set of sites, by randomly sampling a ground shaking
intensi... | [
"def",
"ground_motion_fields",
"(",
"rupture",
",",
"sites",
",",
"imts",
",",
"gsim",
",",
"truncation_level",
",",
"realizations",
",",
"correlation_model",
"=",
"None",
",",
"seed",
"=",
"None",
")",
":",
"cmaker",
"=",
"ContextMaker",
"(",
"rupture",
"."... | Given an earthquake rupture, the ground motion field calculator computes
ground shaking over a set of sites, by randomly sampling a ground shaking
intensity model. A ground motion field represents a possible 'realization'
of the ground shaking due to an earthquake rupture.
.. note::
This calculat... | [
"Given",
"an",
"earthquake",
"rupture",
"the",
"ground",
"motion",
"field",
"calculator",
"computes",
"ground",
"shaking",
"over",
"a",
"set",
"of",
"sites",
"by",
"randomly",
"sampling",
"a",
"ground",
"shaking",
"intensity",
"model",
".",
"A",
"ground",
"mot... | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/calc/gmf.py#L229-L277 | train |
gem/oq-engine | openquake/commands/restore.py | restore | def restore(archive, oqdata):
"""
Build a new oqdata directory from the data contained in the zip archive
"""
if os.path.exists(oqdata):
sys.exit('%s exists already' % oqdata)
if '://' in archive:
# get the zip archive from an URL
resp = requests.get(archive)
_, archi... | python | def restore(archive, oqdata):
"""
Build a new oqdata directory from the data contained in the zip archive
"""
if os.path.exists(oqdata):
sys.exit('%s exists already' % oqdata)
if '://' in archive:
# get the zip archive from an URL
resp = requests.get(archive)
_, archi... | [
"def",
"restore",
"(",
"archive",
",",
"oqdata",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"oqdata",
")",
":",
"sys",
".",
"exit",
"(",
"'%s exists already'",
"%",
"oqdata",
")",
"if",
"'://'",
"in",
"archive",
":",
"# get the zip archive fr... | Build a new oqdata directory from the data contained in the zip archive | [
"Build",
"a",
"new",
"oqdata",
"directory",
"from",
"the",
"data",
"contained",
"in",
"the",
"zip",
"archive"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commands/restore.py#L33-L67 | train |
gem/oq-engine | openquake/hazardlib/source/complex_fault.py | _float_ruptures | def _float_ruptures(rupture_area, rupture_length, cell_area, cell_length):
"""
Get all possible unique rupture placements on the fault surface.
:param rupture_area:
The area of the rupture to float on the fault surface, in squared km.
:param rupture_length:
The target length (spatial ex... | python | def _float_ruptures(rupture_area, rupture_length, cell_area, cell_length):
"""
Get all possible unique rupture placements on the fault surface.
:param rupture_area:
The area of the rupture to float on the fault surface, in squared km.
:param rupture_length:
The target length (spatial ex... | [
"def",
"_float_ruptures",
"(",
"rupture_area",
",",
"rupture_length",
",",
"cell_area",
",",
"cell_length",
")",
":",
"nrows",
",",
"ncols",
"=",
"cell_length",
".",
"shape",
"if",
"rupture_area",
">=",
"numpy",
".",
"sum",
"(",
"cell_area",
")",
":",
"# req... | Get all possible unique rupture placements on the fault surface.
:param rupture_area:
The area of the rupture to float on the fault surface, in squared km.
:param rupture_length:
The target length (spatial extension along fault trace) of the rupture,
in km.
:param cell_area:
... | [
"Get",
"all",
"possible",
"unique",
"rupture",
"placements",
"on",
"the",
"fault",
"surface",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/source/complex_fault.py#L34-L127 | train |
gem/oq-engine | openquake/hazardlib/gsim/germany_2018.py | rhypo_to_rjb | def rhypo_to_rjb(rhypo, mag):
"""
Converts hypocentral distance to an equivalent Joyner-Boore distance
dependent on the magnitude
"""
epsilon = rhypo - (4.853 + 1.347E-6 * (mag ** 8.163))
rjb = np.zeros_like(rhypo)
idx = epsilon >= 3.
rjb[idx] = np.sqrt((epsilon[idx] ** 2.) - 9.0)
rj... | python | def rhypo_to_rjb(rhypo, mag):
"""
Converts hypocentral distance to an equivalent Joyner-Boore distance
dependent on the magnitude
"""
epsilon = rhypo - (4.853 + 1.347E-6 * (mag ** 8.163))
rjb = np.zeros_like(rhypo)
idx = epsilon >= 3.
rjb[idx] = np.sqrt((epsilon[idx] ** 2.) - 9.0)
rj... | [
"def",
"rhypo_to_rjb",
"(",
"rhypo",
",",
"mag",
")",
":",
"epsilon",
"=",
"rhypo",
"-",
"(",
"4.853",
"+",
"1.347E-6",
"*",
"(",
"mag",
"**",
"8.163",
")",
")",
"rjb",
"=",
"np",
".",
"zeros_like",
"(",
"rhypo",
")",
"idx",
"=",
"epsilon",
">=",
... | Converts hypocentral distance to an equivalent Joyner-Boore distance
dependent on the magnitude | [
"Converts",
"hypocentral",
"distance",
"to",
"an",
"equivalent",
"Joyner",
"-",
"Boore",
"distance",
"dependent",
"on",
"the",
"magnitude"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/germany_2018.py#L45-L55 | train |
gem/oq-engine | openquake/hazardlib/gsim/germany_2018.py | DerrasEtAl2014RhypoGermany.get_pn | def get_pn(self, rup, sites, dists, sof):
"""
Normalise the input parameters within their upper and lower
defined range
"""
# List must be in following order
p_n = []
# Rjb
# Note that Rjb must be clipped at 0.1 km
rjb = rhypo_to_rjb(dists.rhypo, r... | python | def get_pn(self, rup, sites, dists, sof):
"""
Normalise the input parameters within their upper and lower
defined range
"""
# List must be in following order
p_n = []
# Rjb
# Note that Rjb must be clipped at 0.1 km
rjb = rhypo_to_rjb(dists.rhypo, r... | [
"def",
"get_pn",
"(",
"self",
",",
"rup",
",",
"sites",
",",
"dists",
",",
"sof",
")",
":",
"# List must be in following order",
"p_n",
"=",
"[",
"]",
"# Rjb",
"# Note that Rjb must be clipped at 0.1 km",
"rjb",
"=",
"rhypo_to_rjb",
"(",
"dists",
".",
"rhypo",
... | Normalise the input parameters within their upper and lower
defined range | [
"Normalise",
"the",
"input",
"parameters",
"within",
"their",
"upper",
"and",
"lower",
"defined",
"range"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/germany_2018.py#L152-L182 | train |
gem/oq-engine | openquake/hazardlib/gsim/base.py | _truncnorm_sf | def _truncnorm_sf(truncation_level, values):
"""
Survival function for truncated normal distribution.
Assumes zero mean, standard deviation equal to one and symmetric
truncation.
:param truncation_level:
Positive float number representing the truncation on both sides
around the mea... | python | def _truncnorm_sf(truncation_level, values):
"""
Survival function for truncated normal distribution.
Assumes zero mean, standard deviation equal to one and symmetric
truncation.
:param truncation_level:
Positive float number representing the truncation on both sides
around the mea... | [
"def",
"_truncnorm_sf",
"(",
"truncation_level",
",",
"values",
")",
":",
"# notation from http://en.wikipedia.org/wiki/Truncated_normal_distribution.",
"# given that mu = 0 and sigma = 1, we have alpha = a and beta = b.",
"# \"CDF\" in comments refers to cumulative distribution function",
"# ... | Survival function for truncated normal distribution.
Assumes zero mean, standard deviation equal to one and symmetric
truncation.
:param truncation_level:
Positive float number representing the truncation on both sides
around the mean, in units of sigma.
:param values:
Numpy ar... | [
"Survival",
"function",
"for",
"truncated",
"normal",
"distribution",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/base.py#L468-L512 | train |
gem/oq-engine | openquake/hazardlib/gsim/base.py | GMPE.to_distribution_values | def to_distribution_values(self, values):
"""
Returns numpy array of natural logarithms of ``values``.
"""
with warnings.catch_warnings():
warnings.simplefilter("ignore")
# avoid RuntimeWarning: divide by zero encountered in log
return numpy.log(values... | python | def to_distribution_values(self, values):
"""
Returns numpy array of natural logarithms of ``values``.
"""
with warnings.catch_warnings():
warnings.simplefilter("ignore")
# avoid RuntimeWarning: divide by zero encountered in log
return numpy.log(values... | [
"def",
"to_distribution_values",
"(",
"self",
",",
"values",
")",
":",
"with",
"warnings",
".",
"catch_warnings",
"(",
")",
":",
"warnings",
".",
"simplefilter",
"(",
"\"ignore\"",
")",
"# avoid RuntimeWarning: divide by zero encountered in log",
"return",
"numpy",
".... | Returns numpy array of natural logarithms of ``values``. | [
"Returns",
"numpy",
"array",
"of",
"natural",
"logarithms",
"of",
"values",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/base.py#L547-L554 | train |
gem/oq-engine | openquake/hazardlib/gsim/base.py | GMPE.set_parameters | def set_parameters(self):
"""
Combines the parameters of the GMPE provided at the construction level
with the ones originally assigned to the backbone modified GMPE.
"""
for key in (ADMITTED_STR_PARAMETERS + ADMITTED_FLOAT_PARAMETERS +
ADMITTED_SET_PARAMETERS)... | python | def set_parameters(self):
"""
Combines the parameters of the GMPE provided at the construction level
with the ones originally assigned to the backbone modified GMPE.
"""
for key in (ADMITTED_STR_PARAMETERS + ADMITTED_FLOAT_PARAMETERS +
ADMITTED_SET_PARAMETERS)... | [
"def",
"set_parameters",
"(",
"self",
")",
":",
"for",
"key",
"in",
"(",
"ADMITTED_STR_PARAMETERS",
"+",
"ADMITTED_FLOAT_PARAMETERS",
"+",
"ADMITTED_SET_PARAMETERS",
")",
":",
"try",
":",
"val",
"=",
"getattr",
"(",
"self",
".",
"gmpe",
",",
"key",
")",
"exc... | Combines the parameters of the GMPE provided at the construction level
with the ones originally assigned to the backbone modified GMPE. | [
"Combines",
"the",
"parameters",
"of",
"the",
"GMPE",
"provided",
"at",
"the",
"construction",
"level",
"with",
"the",
"ones",
"originally",
"assigned",
"to",
"the",
"backbone",
"modified",
"GMPE",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/base.py#L562-L574 | train |
gem/oq-engine | openquake/hazardlib/gsim/base.py | CoeffsTable._setup_table_from_str | def _setup_table_from_str(self, table, sa_damping):
"""
Builds the input tables from a string definition
"""
table = table.strip().splitlines()
header = table.pop(0).split()
if not header[0].upper() == "IMT":
raise ValueError('first column in a table must be I... | python | def _setup_table_from_str(self, table, sa_damping):
"""
Builds the input tables from a string definition
"""
table = table.strip().splitlines()
header = table.pop(0).split()
if not header[0].upper() == "IMT":
raise ValueError('first column in a table must be I... | [
"def",
"_setup_table_from_str",
"(",
"self",
",",
"table",
",",
"sa_damping",
")",
":",
"table",
"=",
"table",
".",
"strip",
"(",
")",
".",
"splitlines",
"(",
")",
"header",
"=",
"table",
".",
"pop",
"(",
"0",
")",
".",
"split",
"(",
")",
"if",
"no... | Builds the input tables from a string definition | [
"Builds",
"the",
"input",
"tables",
"from",
"a",
"string",
"definition"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/base.py#L732-L760 | train |
gem/oq-engine | openquake/hazardlib/gsim/bommer_2009.py | BommerEtAl2009RSD.get_distance_term | def get_distance_term(self, C, rrup, mag):
"""
Returns distance scaling term
"""
return (C["r1"] + C["r2"] * mag) *\
np.log(np.sqrt(rrup ** 2. + C["h1"] ** 2.)) | python | def get_distance_term(self, C, rrup, mag):
"""
Returns distance scaling term
"""
return (C["r1"] + C["r2"] * mag) *\
np.log(np.sqrt(rrup ** 2. + C["h1"] ** 2.)) | [
"def",
"get_distance_term",
"(",
"self",
",",
"C",
",",
"rrup",
",",
"mag",
")",
":",
"return",
"(",
"C",
"[",
"\"r1\"",
"]",
"+",
"C",
"[",
"\"r2\"",
"]",
"*",
"mag",
")",
"*",
"np",
".",
"log",
"(",
"np",
".",
"sqrt",
"(",
"rrup",
"**",
"2.... | Returns distance scaling term | [
"Returns",
"distance",
"scaling",
"term"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/bommer_2009.py#L85-L90 | train |
gem/oq-engine | openquake/hazardlib/gsim/can15/western.py | get_sigma | def get_sigma(imt):
"""
Return the value of the total sigma
:param float imt:
An :class:`openquake.hazardlib.imt.IMT` instance
:returns:
A float representing the total sigma value
"""
if imt.period < 0.2:
return np.log(10**0.23)
elif imt.period > 1.0:
return ... | python | def get_sigma(imt):
"""
Return the value of the total sigma
:param float imt:
An :class:`openquake.hazardlib.imt.IMT` instance
:returns:
A float representing the total sigma value
"""
if imt.period < 0.2:
return np.log(10**0.23)
elif imt.period > 1.0:
return ... | [
"def",
"get_sigma",
"(",
"imt",
")",
":",
"if",
"imt",
".",
"period",
"<",
"0.2",
":",
"return",
"np",
".",
"log",
"(",
"10",
"**",
"0.23",
")",
"elif",
"imt",
".",
"period",
">",
"1.0",
":",
"return",
"np",
".",
"log",
"(",
"10",
"**",
"0.27",... | Return the value of the total sigma
:param float imt:
An :class:`openquake.hazardlib.imt.IMT` instance
:returns:
A float representing the total sigma value | [
"Return",
"the",
"value",
"of",
"the",
"total",
"sigma"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/can15/western.py#L31-L45 | train |
gem/oq-engine | openquake/hmtk/registry.py | CatalogueFunctionRegistry.check_config | def check_config(self, config, fields_spec):
"""
Check that `config` has each field in `fields_spec` if a default
has not been provided.
"""
for field, type_info in fields_spec.items():
has_default = not isinstance(type_info, type)
if field not in config a... | python | def check_config(self, config, fields_spec):
"""
Check that `config` has each field in `fields_spec` if a default
has not been provided.
"""
for field, type_info in fields_spec.items():
has_default = not isinstance(type_info, type)
if field not in config a... | [
"def",
"check_config",
"(",
"self",
",",
"config",
",",
"fields_spec",
")",
":",
"for",
"field",
",",
"type_info",
"in",
"fields_spec",
".",
"items",
"(",
")",
":",
"has_default",
"=",
"not",
"isinstance",
"(",
"type_info",
",",
"type",
")",
"if",
"field... | Check that `config` has each field in `fields_spec` if a default
has not been provided. | [
"Check",
"that",
"config",
"has",
"each",
"field",
"in",
"fields_spec",
"if",
"a",
"default",
"has",
"not",
"been",
"provided",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/registry.py#L57-L66 | train |
gem/oq-engine | openquake/hmtk/registry.py | CatalogueFunctionRegistry.set_defaults | def set_defaults(self, config, fields_spec):
"""
Set default values got from `fields_spec` into the `config`
dictionary
"""
defaults = dict([(f, d)
for f, d in fields_spec.items()
if not isinstance(d, type)])
for field, de... | python | def set_defaults(self, config, fields_spec):
"""
Set default values got from `fields_spec` into the `config`
dictionary
"""
defaults = dict([(f, d)
for f, d in fields_spec.items()
if not isinstance(d, type)])
for field, de... | [
"def",
"set_defaults",
"(",
"self",
",",
"config",
",",
"fields_spec",
")",
":",
"defaults",
"=",
"dict",
"(",
"[",
"(",
"f",
",",
"d",
")",
"for",
"f",
",",
"d",
"in",
"fields_spec",
".",
"items",
"(",
")",
"if",
"not",
"isinstance",
"(",
"d",
"... | Set default values got from `fields_spec` into the `config`
dictionary | [
"Set",
"default",
"values",
"got",
"from",
"fields_spec",
"into",
"the",
"config",
"dictionary"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/registry.py#L68-L78 | train |
gem/oq-engine | openquake/hmtk/registry.py | CatalogueFunctionRegistry.add | def add(self, method_name, completeness=False, **fields):
"""
Class decorator.
Decorate `method_name` by adding a call to `set_defaults` and
`check_config`. Then, save into the registry a callable
function with the same signature of the original method.
:param str metho... | python | def add(self, method_name, completeness=False, **fields):
"""
Class decorator.
Decorate `method_name` by adding a call to `set_defaults` and
`check_config`. Then, save into the registry a callable
function with the same signature of the original method.
:param str metho... | [
"def",
"add",
"(",
"self",
",",
"method_name",
",",
"completeness",
"=",
"False",
",",
"*",
"*",
"fields",
")",
":",
"def",
"class_decorator",
"(",
"class_obj",
")",
":",
"original_method",
"=",
"getattr",
"(",
"class_obj",
",",
"method_name",
")",
"if",
... | Class decorator.
Decorate `method_name` by adding a call to `set_defaults` and
`check_config`. Then, save into the registry a callable
function with the same signature of the original method.
:param str method_name:
the method to decorate
:param bool completeness:
... | [
"Class",
"decorator",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/registry.py#L80-L120 | train |
gem/oq-engine | openquake/hazardlib/gsim/afshari_stewart_2016.py | AfshariStewart2016.get_magnitude_term | def get_magnitude_term(self, C, rup):
"""
Returns the magnitude scaling term in equation 3
"""
b0, stress_drop = self._get_sof_terms(C, rup.rake)
if rup.mag <= C["m1"]:
return b0
else:
# Calculate moment (equation 5)
m_0 = 10.0 ** (1.5 ... | python | def get_magnitude_term(self, C, rup):
"""
Returns the magnitude scaling term in equation 3
"""
b0, stress_drop = self._get_sof_terms(C, rup.rake)
if rup.mag <= C["m1"]:
return b0
else:
# Calculate moment (equation 5)
m_0 = 10.0 ** (1.5 ... | [
"def",
"get_magnitude_term",
"(",
"self",
",",
"C",
",",
"rup",
")",
":",
"b0",
",",
"stress_drop",
"=",
"self",
".",
"_get_sof_terms",
"(",
"C",
",",
"rup",
".",
"rake",
")",
"if",
"rup",
".",
"mag",
"<=",
"C",
"[",
"\"m1\"",
"]",
":",
"return",
... | Returns the magnitude scaling term in equation 3 | [
"Returns",
"the",
"magnitude",
"scaling",
"term",
"in",
"equation",
"3"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/afshari_stewart_2016.py#L83-L102 | train |
gem/oq-engine | openquake/hazardlib/gsim/afshari_stewart_2016.py | AfshariStewart2016.get_distance_term | def get_distance_term(self, C, rrup):
"""
Returns the distance scaling term in equation 7
"""
f_p = C["c1"] * rrup
idx = np.logical_and(rrup > self.CONSTANTS["r1"],
rrup <= self.CONSTANTS["r2"])
f_p[idx] = (C["c1"] * self.CONSTANTS["r1"]) +\
... | python | def get_distance_term(self, C, rrup):
"""
Returns the distance scaling term in equation 7
"""
f_p = C["c1"] * rrup
idx = np.logical_and(rrup > self.CONSTANTS["r1"],
rrup <= self.CONSTANTS["r2"])
f_p[idx] = (C["c1"] * self.CONSTANTS["r1"]) +\
... | [
"def",
"get_distance_term",
"(",
"self",
",",
"C",
",",
"rrup",
")",
":",
"f_p",
"=",
"C",
"[",
"\"c1\"",
"]",
"*",
"rrup",
"idx",
"=",
"np",
".",
"logical_and",
"(",
"rrup",
">",
"self",
".",
"CONSTANTS",
"[",
"\"r1\"",
"]",
",",
"rrup",
"<=",
"... | Returns the distance scaling term in equation 7 | [
"Returns",
"the",
"distance",
"scaling",
"term",
"in",
"equation",
"7"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/afshari_stewart_2016.py#L104-L117 | train |
gem/oq-engine | openquake/hazardlib/gsim/afshari_stewart_2016.py | AfshariStewart2016._get_sof_terms | def _get_sof_terms(self, C, rake):
"""
Returns the style-of-faulting scaling parameters
"""
if rake >= 45.0 and rake <= 135.0:
# Reverse faulting
return C["b0R"], C["b1R"]
elif rake <= -45. and rake >= -135.0:
# Normal faulting
retu... | python | def _get_sof_terms(self, C, rake):
"""
Returns the style-of-faulting scaling parameters
"""
if rake >= 45.0 and rake <= 135.0:
# Reverse faulting
return C["b0R"], C["b1R"]
elif rake <= -45. and rake >= -135.0:
# Normal faulting
retu... | [
"def",
"_get_sof_terms",
"(",
"self",
",",
"C",
",",
"rake",
")",
":",
"if",
"rake",
">=",
"45.0",
"and",
"rake",
"<=",
"135.0",
":",
"# Reverse faulting",
"return",
"C",
"[",
"\"b0R\"",
"]",
",",
"C",
"[",
"\"b1R\"",
"]",
"elif",
"rake",
"<=",
"-",
... | Returns the style-of-faulting scaling parameters | [
"Returns",
"the",
"style",
"-",
"of",
"-",
"faulting",
"scaling",
"parameters"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/afshari_stewart_2016.py#L119-L131 | train |
gem/oq-engine | openquake/hazardlib/gsim/afshari_stewart_2016.py | AfshariStewart2016.get_site_amplification | def get_site_amplification(self, C, sites):
"""
Returns the site amplification term
"""
# Gets delta normalised z1
dz1 = sites.z1pt0 - np.exp(self._get_lnmu_z1(sites.vs30))
f_s = C["c5"] * dz1
# Calculates site amplification term
f_s[dz1 > self.CONSTANTS["... | python | def get_site_amplification(self, C, sites):
"""
Returns the site amplification term
"""
# Gets delta normalised z1
dz1 = sites.z1pt0 - np.exp(self._get_lnmu_z1(sites.vs30))
f_s = C["c5"] * dz1
# Calculates site amplification term
f_s[dz1 > self.CONSTANTS["... | [
"def",
"get_site_amplification",
"(",
"self",
",",
"C",
",",
"sites",
")",
":",
"# Gets delta normalised z1",
"dz1",
"=",
"sites",
".",
"z1pt0",
"-",
"np",
".",
"exp",
"(",
"self",
".",
"_get_lnmu_z1",
"(",
"sites",
".",
"vs30",
")",
")",
"f_s",
"=",
"... | Returns the site amplification term | [
"Returns",
"the",
"site",
"amplification",
"term"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/afshari_stewart_2016.py#L141-L155 | train |
gem/oq-engine | openquake/hazardlib/gsim/garcia_2005.py | GarciaEtAl2005SSlab._compute_mean | def _compute_mean(self, C, g, mag, hypo_depth, dists, imt):
"""
Compute mean according to equation on Table 2, page 2275.
"""
delta = 0.00750 * 10 ** (0.507 * mag)
# computing R for different values of mag
if mag < 6.5:
R = np.sqrt(dists.rhypo ** 2 + delta *... | python | def _compute_mean(self, C, g, mag, hypo_depth, dists, imt):
"""
Compute mean according to equation on Table 2, page 2275.
"""
delta = 0.00750 * 10 ** (0.507 * mag)
# computing R for different values of mag
if mag < 6.5:
R = np.sqrt(dists.rhypo ** 2 + delta *... | [
"def",
"_compute_mean",
"(",
"self",
",",
"C",
",",
"g",
",",
"mag",
",",
"hypo_depth",
",",
"dists",
",",
"imt",
")",
":",
"delta",
"=",
"0.00750",
"*",
"10",
"**",
"(",
"0.507",
"*",
"mag",
")",
"# computing R for different values of mag",
"if",
"mag",... | Compute mean according to equation on Table 2, page 2275. | [
"Compute",
"mean",
"according",
"to",
"equation",
"on",
"Table",
"2",
"page",
"2275",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/garcia_2005.py#L111-L140 | train |
gem/oq-engine | openquake/commands/run.py | get_pstats | def get_pstats(pstatfile, n):
"""
Return profiling information as an RST table.
:param pstatfile: path to a .pstat file
:param n: the maximum number of stats to retrieve
"""
with tempfile.TemporaryFile(mode='w+') as stream:
ps = pstats.Stats(pstatfile, stream=stream)
ps.sort_sta... | python | def get_pstats(pstatfile, n):
"""
Return profiling information as an RST table.
:param pstatfile: path to a .pstat file
:param n: the maximum number of stats to retrieve
"""
with tempfile.TemporaryFile(mode='w+') as stream:
ps = pstats.Stats(pstatfile, stream=stream)
ps.sort_sta... | [
"def",
"get_pstats",
"(",
"pstatfile",
",",
"n",
")",
":",
"with",
"tempfile",
".",
"TemporaryFile",
"(",
"mode",
"=",
"'w+'",
")",
"as",
"stream",
":",
"ps",
"=",
"pstats",
".",
"Stats",
"(",
"pstatfile",
",",
"stream",
"=",
"stream",
")",
"ps",
"."... | Return profiling information as an RST table.
:param pstatfile: path to a .pstat file
:param n: the maximum number of stats to retrieve | [
"Return",
"profiling",
"information",
"as",
"an",
"RST",
"table",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commands/run.py#L40-L72 | train |
gem/oq-engine | openquake/commands/run.py | run2 | def run2(job_haz, job_risk, calc_id, concurrent_tasks, pdb, loglevel,
exports, params):
"""
Run both hazard and risk, one after the other
"""
hcalc = base.calculators(readinput.get_oqparam(job_haz), calc_id)
hcalc.run(concurrent_tasks=concurrent_tasks, pdb=pdb,
exports=exports... | python | def run2(job_haz, job_risk, calc_id, concurrent_tasks, pdb, loglevel,
exports, params):
"""
Run both hazard and risk, one after the other
"""
hcalc = base.calculators(readinput.get_oqparam(job_haz), calc_id)
hcalc.run(concurrent_tasks=concurrent_tasks, pdb=pdb,
exports=exports... | [
"def",
"run2",
"(",
"job_haz",
",",
"job_risk",
",",
"calc_id",
",",
"concurrent_tasks",
",",
"pdb",
",",
"loglevel",
",",
"exports",
",",
"params",
")",
":",
"hcalc",
"=",
"base",
".",
"calculators",
"(",
"readinput",
".",
"get_oqparam",
"(",
"job_haz",
... | Run both hazard and risk, one after the other | [
"Run",
"both",
"hazard",
"and",
"risk",
"one",
"after",
"the",
"other"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commands/run.py#L75-L88 | train |
gem/oq-engine | openquake/commands/run.py | run | def run(job_ini, slowest=False, hc=None, param='', concurrent_tasks=None,
exports='', loglevel='info', pdb=None):
"""
Run a calculation bypassing the database layer
"""
dbserver.ensure_on()
if param:
params = oqvalidation.OqParam.check(
dict(p.split('=', 1) for p in param... | python | def run(job_ini, slowest=False, hc=None, param='', concurrent_tasks=None,
exports='', loglevel='info', pdb=None):
"""
Run a calculation bypassing the database layer
"""
dbserver.ensure_on()
if param:
params = oqvalidation.OqParam.check(
dict(p.split('=', 1) for p in param... | [
"def",
"run",
"(",
"job_ini",
",",
"slowest",
"=",
"False",
",",
"hc",
"=",
"None",
",",
"param",
"=",
"''",
",",
"concurrent_tasks",
"=",
"None",
",",
"exports",
"=",
"''",
",",
"loglevel",
"=",
"'info'",
",",
"pdb",
"=",
"None",
")",
":",
"dbserv... | Run a calculation bypassing the database layer | [
"Run",
"a",
"calculation",
"bypassing",
"the",
"database",
"layer"
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commands/run.py#L131-L152 | train |
gem/oq-engine | openquake/hazardlib/scalerel/__init__.py | _get_available_class | def _get_available_class(base_class):
'''
Return an ordered dictionary with the available classes in the
scalerel submodule with classes that derives from `base_class`,
keyed by class name.
'''
gsims = {}
for fname in os.listdir(os.path.dirname(__file__)):
if fname.endswith('.py'):
... | python | def _get_available_class(base_class):
'''
Return an ordered dictionary with the available classes in the
scalerel submodule with classes that derives from `base_class`,
keyed by class name.
'''
gsims = {}
for fname in os.listdir(os.path.dirname(__file__)):
if fname.endswith('.py'):
... | [
"def",
"_get_available_class",
"(",
"base_class",
")",
":",
"gsims",
"=",
"{",
"}",
"for",
"fname",
"in",
"os",
".",
"listdir",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
")",
":",
"if",
"fname",
".",
"endswith",
"(",
"'.py'",
")",... | Return an ordered dictionary with the available classes in the
scalerel submodule with classes that derives from `base_class`,
keyed by class name. | [
"Return",
"an",
"ordered",
"dictionary",
"with",
"the",
"available",
"classes",
"in",
"the",
"scalerel",
"submodule",
"with",
"classes",
"that",
"derives",
"from",
"base_class",
"keyed",
"by",
"class",
"name",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/scalerel/__init__.py#L42-L59 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.