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 listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
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:
body = None
if body is not None:
result = self._send(body)
if result:
self.command_queue.task_done()
else:
# Something was wrong with the socket.
self._disconnect()
self._connect()
self._register()
# Check for stop event after a read from the queue. This is to
# allow you to open a socket, immediately send to it, and then
# stop it. We do this in the Metadata send at application start
# time
if self._stop_event.is_set():
logger.debug("CoreAgentSocket thread stopping.")
break
except Exception:
logger.debug("CoreAgentSocket thread exception.")
finally:
self._started_event.clear()
self._stop_event.clear()
self._stopped_event.set()
logger.debug("CoreAgentSocket thread stopped.") | 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:
body = None
if body is not None:
result = self._send(body)
if result:
self.command_queue.task_done()
else:
# Something was wrong with the socket.
self._disconnect()
self._connect()
self._register()
# Check for stop event after a read from the queue. This is to
# allow you to open a socket, immediately send to it, and then
# stop it. We do this in the Metadata send at application start
# time
if self._stop_event.is_set():
logger.debug("CoreAgentSocket thread stopping.")
break
except Exception:
logger.debug("CoreAgentSocket thread exception.")
finally:
self._started_event.clear()
self._stop_event.clear()
self._stopped_event.set()
logger.debug("CoreAgentSocket thread stopped.") | [
"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 | 213,800 |
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 | 213,801 |
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 | 213,802 |
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, **kwargs):
result = original(*args, **kwargs)
return _DetailedTracingCursorWrapper(result, self)
logger.debug("Monkey patched SQL") | 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, **kwargs):
result = original(*args, **kwargs)
return _DetailedTracingCursorWrapper(result, self)
logger.debug("Monkey patched SQL") | [
"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 | 213,803 |
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_options_response()
if req.routing_exception is not None:
app.raise_routing_exception(req)
# The routing rule has some handy attributes to extract how Flask found
# this endpoint
rule = req.url_rule
# Wrap the real view_func
view_func = self.wrap_view_func(
app, rule, req, app.view_functions[rule.endpoint], req.view_args
)
return view_func(**req.view_args) | 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_options_response()
if req.routing_exception is not None:
app.raise_routing_exception(req)
# The routing rule has some handy attributes to extract how Flask found
# this endpoint
rule = req.url_rule
# Wrap the real view_func
view_func = self.wrap_view_func(
app, rule, req, app.view_functions[rule.endpoint], req.view_args
)
return view_func(**req.view_args) | [
"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 | 213,804 |
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(
view_func, ("Controller", {"path": req.path, "name": operation})
) | 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(
view_func, ("Controller", {"path": req.path, "name": operation})
) | [
"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 | 213,805 |
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 = request.resolver_match._func_path
span = TrackedRequest.instance().current_span()
if span is not None:
span.operation = "Controller/" + view_name
Context.add("path", request.path)
Context.add("user_ip", RemoteIp.lookup_from_headers(request.META))
if getattr(request, "user", None) is not None:
Context.add("username", request.user.get_username())
except Exception:
pass | 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 = request.resolver_match._func_path
span = TrackedRequest.instance().current_span()
if span is not None:
span.operation = "Controller/" + view_name
Context.add("path", request.path)
Context.add("user_ip", RemoteIp.lookup_from_headers(request.META))
if getattr(request, "user", None) is not None:
Context.add("username", request.user.get_username())
except Exception:
pass | [
"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 | 213,806 |
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.
@return: (libvirt.virNetwork) virtual network.
"""
counter = count()
xml_config = DEFAULT_NETWORK_XML
if not {'configuration', 'dynamic_address'} & set(configuration.keys()):
raise RuntimeError(
"Either configuration or dynamic_address must be specified")
if 'configuration' in configuration:
with open(configuration['configuration']) as xml_file:
xml_config = xml_file.read()
while True:
if 'dynamic_address' in configuration:
address = generate_address(hypervisor,
configuration['dynamic_address'])
xml_string = network_xml(identifier, xml_config, address=address)
else:
xml_string = network_xml(identifier, xml_config)
try:
return hypervisor.networkCreateXML(xml_string)
except libvirt.libvirtError as error:
if next(counter) > MAX_ATTEMPTS:
raise RuntimeError(
"Exceeded failed attempts ({}) to get IP address.".format(
MAX_ATTEMPTS),
"Last error: {}".format(error)) | 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.
@return: (libvirt.virNetwork) virtual network.
"""
counter = count()
xml_config = DEFAULT_NETWORK_XML
if not {'configuration', 'dynamic_address'} & set(configuration.keys()):
raise RuntimeError(
"Either configuration or dynamic_address must be specified")
if 'configuration' in configuration:
with open(configuration['configuration']) as xml_file:
xml_config = xml_file.read()
while True:
if 'dynamic_address' in configuration:
address = generate_address(hypervisor,
configuration['dynamic_address'])
xml_string = network_xml(identifier, xml_config, address=address)
else:
xml_string = network_xml(identifier, xml_config)
try:
return hypervisor.networkCreateXML(xml_string)
except libvirt.libvirtError as error:
if next(counter) > MAX_ATTEMPTS:
raise RuntimeError(
"Exceeded failed attempts ({}) to get IP address.".format(
MAX_ATTEMPTS),
"Last error: {}".format(error)) | [
"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 | 213,807 |
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 = element.find('.//interface[@type="network"]')
if subelm is not None:
network = subelm.find('.//source').get('network')
hypervisor = domain.connect()
return hypervisor.networkLookupByName(network)
return None | 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 = element.find('.//interface[@type="network"]')
if subelm is not None:
network = subelm.find('.//source').get('network')
hypervisor = domain.connect()
return hypervisor.networkLookupByName(network)
return None | [
"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 | 213,808 |
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 | 213,809 |
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 configuration.")
netmask = str(address.netmask)
ipv4 = str(address[1])
dhcp_start = str(address[2])
dhcp_end = str(address[-2])
ip = etree.SubElement(network, 'ip', address=ipv4, netmask=netmask)
dhcp = etree.SubElement(ip, 'dhcp')
etree.SubElement(dhcp, 'range', start=dhcp_start, end=dhcp_end) | 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 configuration.")
netmask = str(address.netmask)
ipv4 = str(address[1])
dhcp_start = str(address[2])
dhcp_end = str(address[-2])
ip = etree.SubElement(network, 'ip', address=ipv4, netmask=netmask)
dhcp = etree.SubElement(ip, 'dhcp')
etree.SubElement(dhcp, 'range', start=dhcp_start, end=dhcp_end) | [
"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 | 213,810 |
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))))
net_address_pool = subnet_address.subnets(new_prefix=subnet_prefix)
return address_lookup(hypervisor, net_address_pool) | 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))))
net_address_pool = subnet_address.subnets(new_prefix=subnet_prefix)
return address_lookup(hypervisor, net_address_pool) | [
"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 | 213,811 |
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:
raise RuntimeError("All IP addresses are in use") | 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:
raise RuntimeError("All IP addresses are in use") | [
"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 | 213,812 |
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 meanwhile
continue
else:
ip_element = etree.fromstring(xml).find('.//ip')
address = ip_element.get('address')
netmask = ip_element.get('netmask')
active.append(ipaddress.IPv4Network(u'/'.join((address, netmask)),
strict=False))
return active | 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 meanwhile
continue
else:
ip_element = etree.fromstring(xml).find('.//ip')
address = ip_element.get('address')
netmask = ip_element.get('netmask')
active.append(ipaddress.IPv4Network(u'/'.join((address, netmask)),
strict=False))
return active | [
"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 | 213,813 |
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:
return address.get('addr') | 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:
return address.get('addr') | [
"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 | 213,814 |
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_address | 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_address | [
"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 | 213,815 |
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(
libvirt.VIR_IP_ADDR_TYPE_IPV4)
return self._ip4_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(
libvirt.VIR_IP_ADDR_TYPE_IPV4)
return self._ip4_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 | 213,816 |
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(
libvirt.VIR_IP_ADDR_TYPE_IPV6)
return self._ip6_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(
libvirt.VIR_IP_ADDR_TYPE_IPV6)
return self._ip6_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 | 213,817 |
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 host,
the completion of the operation is not ensured by the platform.
If the Guest OS is still running after the given timeout,
a RuntimeError will be raised.
@param timeout: (int) amout of seconds to wait for the machine shutdown.
@param kwargs: keyword arguments to pass altogether with the events.
"""
self._assert_transition('shutdown')
self.trigger('pre_shutdown', **kwargs)
self._execute_command(self.domain.shutdown)
self._wait_for_shutdown(timeout)
self.trigger('post_shutdown', **kwargs) | 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 host,
the completion of the operation is not ensured by the platform.
If the Guest OS is still running after the given timeout,
a RuntimeError will be raised.
@param timeout: (int) amout of seconds to wait for the machine shutdown.
@param kwargs: keyword arguments to pass altogether with the events.
"""
self._assert_transition('shutdown')
self.trigger('pre_shutdown', **kwargs)
self._execute_command(self.domain.shutdown)
self._wait_for_shutdown(timeout)
self.trigger('post_shutdown', **kwargs) | [
"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 the platform.
If the Guest OS is still running after the given timeout,
a RuntimeError will be raised.
@param timeout: (int) amout of seconds to wait for the machine shutdown.
@param kwargs: keyword arguments to pass altogether with the events. | [
"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 | 213,818 |
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: (virDomain.method) state transition to impose.
@raise: RuntimeError.
"""
self._assert_transition(event)
self.trigger('pre_%s' % event, **kwargs)
self._execute_command(command, *args)
self.trigger('post_%s' % event, **kwargs) | 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: (virDomain.method) state transition to impose.
@raise: RuntimeError.
"""
self._assert_transition(event)
self.trigger('pre_%s' % event, **kwargs)
self._execute_command(command, *args)
self.trigger('post_%s' % event, **kwargs) | [
"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: RuntimeError. | [
"Context",
"state",
"controller",
"."
] | 3e053e52a45229f96a12db9e98caf7fb3880e811 | https://github.com/F-Secure/see/blob/3e053e52a45229f96a12db9e98caf7fb3880e811/see/context/context.py#L325-L340 | train | 213,819 |
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 | 213,820 |
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 | 213,821 |
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",
"backing_file=%s" % volume_backing_path(volume),
"-O", "qcow2", "-s", name,
volume_path(volume), path)
collect_process_output(process)
return path | 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",
"backing_file=%s" % volume_backing_path(volume),
"-O", "qcow2", "-s", name,
volume_path(volume), path)
collect_process_output(process)
return path | [
"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 | 213,822 |
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', False),
concurrent=configuration.get('use_concurrency', False))
if configuration.get('extract_files', False):
extract = results['created_files'] + results['modified_files']
files = comparator.extract(1, extract,
path=configuration['results_folder'])
results.update(files)
if configuration.get('compare_registries', False):
results['registry'] = comparator.compare_registry(
concurrent=configuration.get('use_concurrency', False))
return results | 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', False),
concurrent=configuration.get('use_concurrency', False))
if configuration.get('extract_files', False):
extract = results['created_files'] + results['modified_files']
files = comparator.extract(1, extract,
path=configuration['results_folder'])
results.update(files)
if configuration.get('compare_registries', False):
results['registry'] = comparator.compare_registry(
concurrent=configuration.get('use_concurrency', False))
return results | [
"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 | 213,823 |
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.",
event, self.checkpoints[0], self.checkpoints[1])
results = compare_disks(self.checkpoints[0], self.checkpoints[1],
self.configuration)
with open(results_path, 'w') as results_file:
json.dump(results, results_file)
self.processing_done.set() | 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.",
event, self.checkpoints[0], self.checkpoints[1])
results = compare_disks(self.checkpoints[0], self.checkpoints[1],
self.configuration)
with open(results_path, 'w') as results_file:
json.dump(results, results_file)
self.processing_done.set() | [
"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 | 213,824 |
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)
Class = getattr(module, class_name)
if not inspect.isclass(Class):
raise TypeError(
"%s is not of type class: %s" % (class_name, type(Class)))
return Class | 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)
Class = getattr(module, class_name)
if not inspect.isclass(Class):
raise TypeError(
"%s is not of type class: %s" % (class_name, type(Class)))
return Class | [
"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 | 213,825 |
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 | 213,826 |
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 | 213,827 |
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 | 213,828 |
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 | 213,829 |
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: (callable) function or method to subscribe.
"""
self._handlers.async_handlers[event].append(handler) | 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: (callable) function or method to subscribe.
"""
self._handlers.async_handlers[event].append(handler) | [
"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 | 213,830 |
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.
"""
try:
self._handlers.sync_handlers[event].remove(handler)
except ValueError:
self._handlers.async_handlers[event].remove(handler)
else:
try:
self._handlers.async_handlers[event].remove(handler)
except ValueError:
pass | 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.
"""
try:
self._handlers.sync_handlers[event].remove(handler)
except ValueError:
self._handlers.async_handlers[event].remove(handler)
else:
try:
self._handlers.async_handlers[event].remove(handler)
except ValueError:
pass | [
"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 | 213,831 |
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 = prime_event(event, self.__class__.__name__, **kwargs)
for handler in self._handlers.async_handlers[event]:
asynchronous(handler, event)
for handler in self._handlers.sync_handlers[event]:
synchronous(handler, event) | 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 = prime_event(event, self.__class__.__name__, **kwargs)
for handler in self._handlers.async_handlers[event]:
asynchronous(handler, event)
for handler in self._handlers.sync_handlers[event]:
synchronous(handler, event) | [
"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 | 213,832 |
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(
self.configuration['disk']['image']['provider'])
self._image = ProviderClass(
self.configuration['disk']['image']).image
else:
# If image is not a dictionary, return it as is for backwards
# compatibility
self._image = self.configuration['disk']['image']
return self._image | 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(
self.configuration['disk']['image']['provider'])
self._image = ProviderClass(
self.configuration['disk']['image']).image
else:
# If image is not a dictionary, return it as is for backwards
# compatibility
self._image = self.configuration['disk']['image']
return self._image | [
"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 | 213,833 |
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,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
try:
timeout = asynchronous and 1 or None
output = process.communicate(timeout=timeout)[0].decode('utf8')
except subprocess.TimeoutExpired:
pass
if asynchronous:
return PopenOutput(None, 'Asynchronous call.')
else:
return PopenOutput(process.returncode, output) | 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,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
try:
timeout = asynchronous and 1 or None
output = process.communicate(timeout=timeout)[0].decode('utf8')
except subprocess.TimeoutExpired:
pass
if asynchronous:
return PopenOutput(None, 'Asynchronous call.')
else:
return PopenOutput(process.returncode, output) | [
"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 | 213,834 |
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(json.dumps(response), "utf8")) | 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(json.dumps(response), "utf8")) | [
"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 | 213,835 |
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 | 213,836 |
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 | 213,837 |
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 = base_volume.find('.//target/path').text
target_path = os.path.join(pool_path, '%s.qcow2' % identifier)
volume_xml = VOLUME_DEFAULT_CONFIG.format(identifier, target_path)
volume = etree.fromstring(volume_xml)
base_volume_capacity = base_volume.find(".//capacity")
volume.append(base_volume_capacity)
if cow:
backing_xml = BACKING_STORE_DEFAULT_CONFIG.format(base_path)
backing_store = etree.fromstring(backing_xml)
volume.append(backing_store)
return etree.tostring(volume).decode('utf-8') | 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 = base_volume.find('.//target/path').text
target_path = os.path.join(pool_path, '%s.qcow2' % identifier)
volume_xml = VOLUME_DEFAULT_CONFIG.format(identifier, target_path)
volume = etree.fromstring(volume_xml)
base_volume_capacity = base_volume.find(".//capacity")
volume.append(base_volume_capacity)
if cow:
backing_xml = BACKING_STORE_DEFAULT_CONFIG.format(base_path)
backing_store = etree.fromstring(backing_xml)
volume.append(backing_store)
return etree.tostring(volume).decode('utf-8') | [
"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 | 213,838 |
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(path)
xml = POOL_DEFAULT_CONFIG.format(identifier, path)
return hypervisor.storagePoolCreateXML(xml, 0) | 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(path)
xml = POOL_DEFAULT_CONFIG.format(identifier, path)
return hypervisor.storagePoolCreateXML(xml, 0) | [
"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 | 213,839 |
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:
return None | 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:
return None | [
"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 | 213,840 |
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.libvirtError:
logger.exception("Unable to delete storage pool.")
try:
if os.path.exists(path):
shutil.rmtree(path)
except EnvironmentError:
logger.exception("Unable to delete storage pool folder.") | 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.libvirtError:
logger.exception("Unable to delete storage pool.")
try:
if os.path.exists(path):
shutil.rmtree(path)
except EnvironmentError:
logger.exception("Unable to delete storage pool folder.") | [
"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 | 213,841 |
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 libvirt.libvirtError:
logger.exception(
"Unable to delete storage volume %s.", vol_name)
except libvirt.libvirtError:
logger.exception("Unable to delete storage volumes.") | 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 libvirt.libvirtError:
logger.exception(
"Unable to delete storage volume %s.", vol_name)
except libvirt.libvirtError:
logger.exception("Unable to delete storage volumes.") | [
"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 | 213,842 |
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/path
* target/permission/label
* backingStore/path if copy on write is enabled
"""
cow = configuration.get('copy_on_write', False)
try:
volume = hypervisor.storageVolLookupByPath(image)
except libvirt.libvirtError:
if os.path.exists(image):
pool_path = os.path.dirname(image)
logger.info("LibVirt pool does not exist, creating {} pool".format(
pool_path.replace('/', '_')))
pool = hypervisor.storagePoolDefineXML(BASE_POOL_CONFIG.format(
pool_path.replace('/', '_'), pool_path))
pool.setAutostart(True)
pool.create()
pool.refresh()
volume = hypervisor.storageVolLookupByPath(image)
else:
raise RuntimeError(
"%s disk does not exist." % image)
xml = disk_xml(identifier, storage_pool.XMLDesc(0), volume.XMLDesc(0), cow)
if cow:
storage_pool.createXML(xml, 0)
else:
storage_pool.createXMLFrom(xml, volume, 0) | 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/path
* target/permission/label
* backingStore/path if copy on write is enabled
"""
cow = configuration.get('copy_on_write', False)
try:
volume = hypervisor.storageVolLookupByPath(image)
except libvirt.libvirtError:
if os.path.exists(image):
pool_path = os.path.dirname(image)
logger.info("LibVirt pool does not exist, creating {} pool".format(
pool_path.replace('/', '_')))
pool = hypervisor.storagePoolDefineXML(BASE_POOL_CONFIG.format(
pool_path.replace('/', '_'), pool_path))
pool.setAutostart(True)
pool.create()
pool.refresh()
volume = hypervisor.storageVolLookupByPath(image)
else:
raise RuntimeError(
"%s disk does not exist." % image)
xml = disk_xml(identifier, storage_pool.XMLDesc(0), volume.XMLDesc(0), cow)
if cow:
storage_pool.createXML(xml, 0)
else:
storage_pool.createXMLFrom(xml, volume, 0) | [
"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 | 213,843 |
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 self._storage_pool.storageVolLookupByName(disk_name).path() | 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 self._storage_pool.storageVolLookupByName(disk_name).path() | [
"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 | 213,844 |
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 | 213,845 |
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("Unable to cleanup %s object", obj) | 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("Unable to cleanup %s object", obj) | [
"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 | 213,846 |
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 | 213,847 |
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 | 213,848 |
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 | 213,849 |
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:
self._load_hook(hook['name'], config, context)
except KeyError:
self.logger.exception('Provided hook has no name: %s.', hook) | 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:
self._load_hook(hook['name'], config, context)
except KeyError:
self.logger.exception('Provided hook has no name: %s.', hook) | [
"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 | 213,850 |
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 group else cmod.PairingGroup(PAIRING_GROUP)
h_challenge = sha256()
serialedArgs = [group.serialize(arg) if isGroupElement(arg)
else cmod.Conversion.IP2OS(arg)
for arg in args]
for arg in sorted(serialedArgs):
h_challenge.update(arg)
return bytes_to_int(h_challenge.digest()) | 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 group else cmod.PairingGroup(PAIRING_GROUP)
h_challenge = sha256()
serialedArgs = [group.serialize(arg) if isGroupElement(arg)
else cmod.Conversion.IP2OS(arg)
for arg in args]
for arg in sorted(serialedArgs):
h_challenge.update(arg)
return bytes_to_int(h_challenge.digest()) | [
"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 | 213,851 |
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.
:param size: size of the random string to generate
:param chars: the set of characters to use to generate the random string. Uses alphanumerics by default.
:return: the random string generated
"""
return ''.join(sample(chars, size)) | 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.
:param size: size of the random string to generate
:param chars: the set of characters to use to generate the random string. Uses alphanumerics by default.
:return: the random string generated
"""
return ''.join(sample(chars, size)) | [
"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 string. Uses alphanumerics by default.
:return: the random string generated | [
"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 | 213,852 |
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
return prime | 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
return prime | [
"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 | 213,853 |
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_types:
attrName = at.name
if attrName in self._vals:
if at.encode:
encoded[attrName] = encodeAttr(self._vals[attrName])
else:
encoded[attrName] = self._vals[at.name]
return encoded | 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_types:
attrName = at.name
if attrName in self._vals:
if at.encode:
encoded[attrName] = encodeAttr(self._vals[attrName])
else:
encoded[attrName] = self._vals[at.name]
return encoded | [
"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 | 213,854 |
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 = Schema(name, version, attrNames, self.issuerId)
return await self.wallet.submitSchema(schema) | 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 = Schema(name, version, attrNames, self.issuerId)
return await self.wallet.submitSchema(schema) | [
"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 | 213,855 |
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
:param L: maximum number of claims within accumulator.
:return: Submitted accumulator public key
"""
accum, tails, accPK, accSK = await self._nonRevocationIssuer.issueAccumulator(
schemaId, iA, L)
accPK = await self.wallet.submitAccumPublic(schemaId=schemaId,
accumPK=accPK,
accum=accum, tails=tails)
await self.wallet.submitAccumSecret(schemaId=schemaId,
accumSK=accSK)
return accPK | 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
:param L: maximum number of claims within accumulator.
:return: Submitted accumulator public key
"""
accum, tails, accPK, accSK = await self._nonRevocationIssuer.issueAccumulator(
schemaId, iA, L)
accPK = await self.wallet.submitAccumPublic(schemaId=schemaId,
accumPK=accPK,
accum=accum, tails=tails)
await self.wallet.submitAccumSecret(schemaId=schemaId,
accumSK=accSK)
return accPK | [
"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 | 213,856 |
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, i)
await self.wallet.submitAccumUpdate(schemaId=schemaId, accum=acc,
timestampMs=ts) | 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, i)
await self.wallet.submitAccumUpdate(schemaId=schemaId, accum=acc,
timestampMs=ts) | [
"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 | 213,857 |
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
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 accumulator
:return: The claim (both primary and non-revocation)
"""
schemaKey = (await self.wallet.getSchema(schemaId)).getKey()
attributes = self._attrRepo.getAttributes(schemaKey,
claimRequest.userId)
# TODO re-enable when revocation registry is implemented
# iA = iA if iA else (await self.wallet.getAccumulator(schemaId)).iA
# TODO this has un-obvious side-effects
await self._genContxt(schemaId, iA, claimRequest.userId)
(c1, claim) = await self._issuePrimaryClaim(schemaId, attributes,
claimRequest.U)
# TODO re-enable when revocation registry is fully implemented
c2 = await self._issueNonRevocationClaim(schemaId, claimRequest.Ur,
iA,
i) if claimRequest.Ur else None
signature = Claims(primaryClaim=c1, nonRevocClaim=c2)
return (signature, claim) | 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
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 accumulator
:return: The claim (both primary and non-revocation)
"""
schemaKey = (await self.wallet.getSchema(schemaId)).getKey()
attributes = self._attrRepo.getAttributes(schemaKey,
claimRequest.userId)
# TODO re-enable when revocation registry is implemented
# iA = iA if iA else (await self.wallet.getAccumulator(schemaId)).iA
# TODO this has un-obvious side-effects
await self._genContxt(schemaId, iA, claimRequest.userId)
(c1, claim) = await self._issuePrimaryClaim(schemaId, attributes,
claimRequest.U)
# TODO re-enable when revocation registry is fully implemented
c2 = await self._issueNonRevocationClaim(schemaId, claimRequest.Ur,
iA,
i) if claimRequest.Ur else None
signature = Claims(primaryClaim=c1, nonRevocClaim=c2)
return (signature, claim) | [
"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 accumulator
:return: The claim (both primary and non-revocation) | [
"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 | 213,858 |
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 claims (both primary and non-revocation)
"""
res = {}
for schemaId, claimReq in allClaimRequest.items():
res[schemaId] = await self.issueClaim(schemaId, claimReq)
return res | 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 claims (both primary and non-revocation)
"""
res = {}
for schemaId, claimReq in allClaimRequest.items():
res[schemaId] = await self.issueClaim(schemaId, claimReq)
return res | [
"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 | 213,859 |
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 verified successfully and false otherwise.
"""
if proofRequest.verifiableAttributes.keys() != proof.requestedProof.revealed_attrs.keys():
raise ValueError('Received attributes ={} do not correspond to requested={}'.format(
proof.requestedProof.revealed_attrs.keys(), proofRequest.verifiableAttributes.keys()))
if proofRequest.predicates.keys() != proof.requestedProof.predicates.keys():
raise ValueError('Received predicates ={} do not correspond to requested={}'.format(
proof.requestedProof.predicates.keys(), proofRequest.predicates.keys()))
TauList = []
for (uuid, proofItem) in proof.proofs.items():
if proofItem.proof.nonRevocProof:
TauList += await self._nonRevocVerifier.verifyNonRevocation(
proofRequest, proofItem.schema_seq_no, proof.aggregatedProof.cHash,
proofItem.proof.nonRevocProof)
if proofItem.proof.primaryProof:
TauList += await self._primaryVerifier.verify(proofItem.schema_seq_no,
proof.aggregatedProof.cHash,
proofItem.proof.primaryProof)
CHver = self._get_hash(proof.aggregatedProof.CList, self._prepare_collection(TauList),
cmod.integer(proofRequest.nonce))
return CHver == proof.aggregatedProof.cHash | 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 verified successfully and false otherwise.
"""
if proofRequest.verifiableAttributes.keys() != proof.requestedProof.revealed_attrs.keys():
raise ValueError('Received attributes ={} do not correspond to requested={}'.format(
proof.requestedProof.revealed_attrs.keys(), proofRequest.verifiableAttributes.keys()))
if proofRequest.predicates.keys() != proof.requestedProof.predicates.keys():
raise ValueError('Received predicates ={} do not correspond to requested={}'.format(
proof.requestedProof.predicates.keys(), proofRequest.predicates.keys()))
TauList = []
for (uuid, proofItem) in proof.proofs.items():
if proofItem.proof.nonRevocProof:
TauList += await self._nonRevocVerifier.verifyNonRevocation(
proofRequest, proofItem.schema_seq_no, proof.aggregatedProof.cHash,
proofItem.proof.nonRevocProof)
if proofItem.proof.primaryProof:
TauList += await self._primaryVerifier.verify(proofItem.schema_seq_no,
proof.aggregatedProof.cHash,
proofItem.proof.primaryProof)
CHver = self._get_hash(proof.aggregatedProof.CList, self._prepare_collection(TauList),
cmod.integer(proofRequest.nonce))
return CHver == proof.aggregatedProof.cHash | [
"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 | 213,860 |
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 processed and saved
"""
await self.wallet.submitContextAttr(schemaId, signature.primaryClaim.m2)
await self.wallet.submitClaimAttributes(schemaId, claimAttributes)
await self._initPrimaryClaim(schemaId, signature.primaryClaim)
if signature.nonRevocClaim:
await self._initNonRevocationClaim(schemaId, signature.nonRevocClaim) | 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 processed and saved
"""
await self.wallet.submitContextAttr(schemaId, signature.primaryClaim.m2)
await self.wallet.submitClaimAttributes(schemaId, claimAttributes)
await self._initPrimaryClaim(schemaId, signature.primaryClaim)
if signature.nonRevocClaim:
await self._initNonRevocationClaim(schemaId, signature.nonRevocClaim) | [
"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 | 213,861 |
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():
res.append(await self.processClaim(schemaId, claim_attributes, claim_signature))
return res | 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():
res.append(await self.processClaim(schemaId, claim_attributes, claim_signature))
return res | [
"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 | 213,862 |
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-revocation) and revealed attributes (initial non-encoded values)
"""
claims, requestedProof = await self._findClaims(proofRequest)
proof = await self._prepareProof(claims, proofRequest.nonce, requestedProof)
return proof | 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-revocation) and revealed attributes (initial non-encoded values)
"""
claims, requestedProof = await self._findClaims(proofRequest)
proof = await self._prepareProof(claims, proofRequest.nonce, requestedProof)
return proof | [
"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 | 213,863 |
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_string: the string representation of a zipkin ID
:returns: signed int representation
"""
v = struct.unpack(
'q', struct.pack('Q', int(hex_string, 16)))[0] # type: int
return v | 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_string: the string representation of a zipkin ID
:returns: signed int representation
"""
v = struct.unpack(
'q', struct.pack('Q', int(hex_string, 16)))[0] # type: int
return v | [
"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: signed int representation | [
"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 | 213,864 |
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
"""
hex_string = hex(struct.unpack('Q', struct.pack('q', signed_int))[0])[2:]
if hex_string.endswith('L'):
return hex_string[:-1]
return 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
"""
hex_string = hex(struct.unpack('Q', struct.pack('q', signed_int))[0])[2:]
if hex_string.endswith('L'):
return hex_string[:-1]
return 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 | 213,865 |
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 application context and cleaned after application
shutdown. You can provide custom tracer_key, if default name is not
suitable.
"""
app[tracer_key] = tracer
m = middleware_maker(skip_routes=skip_routes,
tracer_key=tracer_key,
request_key=request_key)
app.middlewares.append(m)
# register cleanup signal to close zipkin transport connections
async def close_aiozipkin(app: Application) -> None:
await app[tracer_key].close()
app.on_cleanup.append(close_aiozipkin)
return app | 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 application context and cleaned after application
shutdown. You can provide custom tracer_key, if default name is not
suitable.
"""
app[tracer_key] = tracer
m = middleware_maker(skip_routes=skip_routes,
tracer_key=tracer_key,
request_key=request_key)
app.middlewares.append(m)
# register cleanup signal to close zipkin transport connections
async def close_aiozipkin(app: Application) -> None:
await app[tracer_key].close()
app.on_cleanup.append(close_aiozipkin)
return app | [
"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 | 213,866 |
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 cast(Tracer, app[tracer_key]) | 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 cast(Tracer, app[tracer_key]) | [
"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 | 213,867 |
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 | 213,868 |
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)
trace_config.on_request_end.append(zipkin.on_request_end)
trace_config.on_request_exception.append(zipkin.on_request_exception)
return trace_config | 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)
trace_config.on_request_end.append(zipkin.on_request_end)
trace_config.on_request_exception.append(zipkin.on_request_exception)
return trace_config | [
"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 | 213,869 |
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 | 213,870 |
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',
}
if context.parent_id is not None:
headers[PARENT_ID_HEADER] = context.parent_id
return headers | 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',
}
if context.parent_id is not None:
headers[PARENT_ID_HEADER] = context.parent_id
return headers | [
"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 | 213,871 |
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:
sampled = '0'
params = [c.trace_id, c.span_id, sampled] # type: List[str]
if c.parent_id is not None:
params.append(c.parent_id)
h = DELIMITER.join(params)
headers = {SINGLE_HEADER: h}
return headers | 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:
sampled = '0'
params = [c.trace_id, c.span_id, sampled] # type: List[str]
if c.parent_id is not None:
params.append(c.parent_id)
h = DELIMITER.join(params)
headers = {SINGLE_HEADER: h}
return headers | [
"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 | 213,872 |
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 regular dict
# instead dict with case insensitive keys
headers = {k.lower(): v for k, v in headers.items()}
required = (TRACE_ID_HEADER.lower(), SPAN_ID_HEADER.lower())
has_b3 = all(h in headers for h in required)
has_b3_single = SINGLE_HEADER in headers
if not(has_b3_single or has_b3):
return None
if has_b3:
debug = parse_debug_header(headers)
sampled = debug if debug else parse_sampled_header(headers)
context = TraceContext(
trace_id=headers[TRACE_ID_HEADER.lower()],
parent_id=headers.get(PARENT_ID_HEADER.lower()),
span_id=headers[SPAN_ID_HEADER.lower()],
sampled=sampled,
debug=debug,
shared=False,
)
return context
return _parse_single_header(headers) | 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 regular dict
# instead dict with case insensitive keys
headers = {k.lower(): v for k, v in headers.items()}
required = (TRACE_ID_HEADER.lower(), SPAN_ID_HEADER.lower())
has_b3 = all(h in headers for h in required)
has_b3_single = SINGLE_HEADER in headers
if not(has_b3_single or has_b3):
return None
if has_b3:
debug = parse_debug_header(headers)
sampled = debug if debug else parse_sampled_header(headers)
context = TraceContext(
trace_id=headers[TRACE_ID_HEADER.lower()],
parent_id=headers.get(PARENT_ID_HEADER.lower()),
span_id=headers[SPAN_ID_HEADER.lower()],
sampled=sampled,
debug=debug,
shared=False,
)
return context
return _parse_single_header(headers) | [
"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 | 213,873 |
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 not in keys or v is not None # type: ignore
def full_filter(k: str, v: Any) -> bool:
return v is not None
f = limited_filter if keys is not None else full_filter
return {k: v for k, v in data.items() if f(k, v)} | 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 not in keys or v is not None # type: ignore
def full_filter(k: str, v: Any) -> bool:
return v is not None
f = limited_filter if keys is not None else full_filter
return {k: v for k, v in data.items() if f(k, v)} | [
"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 | 213,874 |
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['aR']
else:
return C['aS'] | 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['aR']
else:
return C['aS'] | [
"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 | 213,875 |
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 spectrum values to SA.
"""
mean = (self._compute_term_1_2(C, mag) +
self._compute_term_3(C, dists.rhypo) +
self._compute_site_term(C, vs30) +
self._compute_faulting_style_term(C, rake))
# convert from cm/s**2 to g for SA and from m/s**2 to g for PGA (PGV
# is already in cm/s) and also convert from base 10 to base e.
if imt.name == "PGA":
mean = np.log((10 ** mean) / g)
elif imt.name == "SA":
mean = np.log((10 ** mean) * ((2 * np.pi / imt.period) ** 2) *
1e-2 / g)
else:
mean = np.log(10 ** mean)
return mean | 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 spectrum values to SA.
"""
mean = (self._compute_term_1_2(C, mag) +
self._compute_term_3(C, dists.rhypo) +
self._compute_site_term(C, vs30) +
self._compute_faulting_style_term(C, rake))
# convert from cm/s**2 to g for SA and from m/s**2 to g for PGA (PGV
# is already in cm/s) and also convert from base 10 to base e.
if imt.name == "PGA":
mean = np.log((10 ** mean) / g)
elif imt.name == "SA":
mean = np.log((10 ** mean) * ((2 * np.pi / imt.period) ** 2) *
1e-2 / g)
else:
mean = np.log(10 ** mean)
return mean | [
"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 | 213,876 |
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
intensity model. A ground motion field represents a possible 'realization'
of the ground shaking due to an earthquake rupture.
.. note::
This calculator is using random numbers. In order to reproduce the
same results numpy random numbers generator needs to be seeded, see
http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.seed.html
:param openquake.hazardlib.source.rupture.Rupture rupture:
Rupture to calculate ground motion fields radiated from.
:param openquake.hazardlib.site.SiteCollection sites:
Sites of interest to calculate GMFs.
:param imts:
List of intensity measure type objects (see
:mod:`openquake.hazardlib.imt`).
:param gsim:
Ground-shaking intensity model, instance of subclass of either
:class:`~openquake.hazardlib.gsim.base.GMPE` or
:class:`~openquake.hazardlib.gsim.base.IPE`.
:param truncation_level:
Float, number of standard deviations for truncation of the intensity
distribution, or ``None``.
:param realizations:
Integer number of GMF realizations to compute.
:param correlation_model:
Instance of correlation model object. See
:mod:`openquake.hazardlib.correlation`. Can be ``None``, in which case
non-correlated ground motion fields are calculated. Correlation model
is not used if ``truncation_level`` is zero.
:param int seed:
The seed used in the numpy random number generator
:returns:
Dictionary mapping intensity measure type objects (same
as in parameter ``imts``) to 2d numpy arrays of floats,
representing different realizations of ground shaking intensity
for all sites in the collection. First dimension represents
sites and second one is for realizations.
"""
cmaker = ContextMaker(rupture.tectonic_region_type, [gsim])
gc = GmfComputer(rupture, sites, [str(imt) for imt in imts],
cmaker, truncation_level, correlation_model)
res, _sig, _eps = gc.compute(gsim, realizations, seed)
return {imt: res[imti] for imti, imt in enumerate(gc.imts)} | 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
intensity model. A ground motion field represents a possible 'realization'
of the ground shaking due to an earthquake rupture.
.. note::
This calculator is using random numbers. In order to reproduce the
same results numpy random numbers generator needs to be seeded, see
http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.seed.html
:param openquake.hazardlib.source.rupture.Rupture rupture:
Rupture to calculate ground motion fields radiated from.
:param openquake.hazardlib.site.SiteCollection sites:
Sites of interest to calculate GMFs.
:param imts:
List of intensity measure type objects (see
:mod:`openquake.hazardlib.imt`).
:param gsim:
Ground-shaking intensity model, instance of subclass of either
:class:`~openquake.hazardlib.gsim.base.GMPE` or
:class:`~openquake.hazardlib.gsim.base.IPE`.
:param truncation_level:
Float, number of standard deviations for truncation of the intensity
distribution, or ``None``.
:param realizations:
Integer number of GMF realizations to compute.
:param correlation_model:
Instance of correlation model object. See
:mod:`openquake.hazardlib.correlation`. Can be ``None``, in which case
non-correlated ground motion fields are calculated. Correlation model
is not used if ``truncation_level`` is zero.
:param int seed:
The seed used in the numpy random number generator
:returns:
Dictionary mapping intensity measure type objects (same
as in parameter ``imts``) to 2d numpy arrays of floats,
representing different realizations of ground shaking intensity
for all sites in the collection. First dimension represents
sites and second one is for realizations.
"""
cmaker = ContextMaker(rupture.tectonic_region_type, [gsim])
gc = GmfComputer(rupture, sites, [str(imt) for imt in imts],
cmaker, truncation_level, correlation_model)
res, _sig, _eps = gc.compute(gsim, realizations, seed)
return {imt: res[imti] for imti, imt in enumerate(gc.imts)} | [
"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 calculator is using random numbers. In order to reproduce the
same results numpy random numbers generator needs to be seeded, see
http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.seed.html
:param openquake.hazardlib.source.rupture.Rupture rupture:
Rupture to calculate ground motion fields radiated from.
:param openquake.hazardlib.site.SiteCollection sites:
Sites of interest to calculate GMFs.
:param imts:
List of intensity measure type objects (see
:mod:`openquake.hazardlib.imt`).
:param gsim:
Ground-shaking intensity model, instance of subclass of either
:class:`~openquake.hazardlib.gsim.base.GMPE` or
:class:`~openquake.hazardlib.gsim.base.IPE`.
:param truncation_level:
Float, number of standard deviations for truncation of the intensity
distribution, or ``None``.
:param realizations:
Integer number of GMF realizations to compute.
:param correlation_model:
Instance of correlation model object. See
:mod:`openquake.hazardlib.correlation`. Can be ``None``, in which case
non-correlated ground motion fields are calculated. Correlation model
is not used if ``truncation_level`` is zero.
:param int seed:
The seed used in the numpy random number generator
:returns:
Dictionary mapping intensity measure type objects (same
as in parameter ``imts``) to 2d numpy arrays of floats,
representing different realizations of ground shaking intensity
for all sites in the collection. First dimension represents
sites and second one is for realizations. | [
"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 | 213,877 |
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)
_, archive = archive.rsplit('/', 1)
with open(archive, 'wb') as f:
f.write(resp.content)
if not os.path.exists(archive):
sys.exit('%s does not exist' % archive)
t0 = time.time()
oqdata = os.path.abspath(oqdata)
assert archive.endswith('.zip'), archive
os.mkdir(oqdata)
zipfile.ZipFile(archive).extractall(oqdata)
dbpath = os.path.join(oqdata, 'db.sqlite3')
db = Db(sqlite3.connect, dbpath, isolation_level=None,
detect_types=sqlite3.PARSE_DECLTYPES)
n = 0
for fname in os.listdir(oqdata):
mo = re.match('calc_(\d+)\.hdf5', fname)
if mo:
job_id = int(mo.group(1))
fullname = os.path.join(oqdata, fname)[:-5] # strip .hdf5
db("UPDATE job SET user_name=?x, ds_calc_dir=?x WHERE id=?x",
getpass.getuser(), fullname, job_id)
safeprint('Restoring ' + fname)
n += 1
dt = time.time() - t0
safeprint('Extracted %d calculations into %s in %d seconds'
% (n, oqdata, dt)) | 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)
_, archive = archive.rsplit('/', 1)
with open(archive, 'wb') as f:
f.write(resp.content)
if not os.path.exists(archive):
sys.exit('%s does not exist' % archive)
t0 = time.time()
oqdata = os.path.abspath(oqdata)
assert archive.endswith('.zip'), archive
os.mkdir(oqdata)
zipfile.ZipFile(archive).extractall(oqdata)
dbpath = os.path.join(oqdata, 'db.sqlite3')
db = Db(sqlite3.connect, dbpath, isolation_level=None,
detect_types=sqlite3.PARSE_DECLTYPES)
n = 0
for fname in os.listdir(oqdata):
mo = re.match('calc_(\d+)\.hdf5', fname)
if mo:
job_id = int(mo.group(1))
fullname = os.path.join(oqdata, fname)[:-5] # strip .hdf5
db("UPDATE job SET user_name=?x, ds_calc_dir=?x WHERE id=?x",
getpass.getuser(), fullname, job_id)
safeprint('Restoring ' + fname)
n += 1
dt = time.time() - t0
safeprint('Extracted %d calculations into %s in %d seconds'
% (n, oqdata, dt)) | [
"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 | 213,878 |
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 extension along fault trace) of the rupture,
in km.
:param cell_area:
2d numpy array representing area of mesh cells in squared km.
:param cell_length:
2d numpy array of the shape as ``cell_area`` representing cells'
length in km.
:returns:
A list of slice objects. Number of items in the list is equal to number
of possible locations of the requested rupture on the fault surface.
Each slice can be used to get a portion of the whole fault surface mesh
that would represent the location of the rupture.
"""
nrows, ncols = cell_length.shape
if rupture_area >= numpy.sum(cell_area):
# requested rupture area exceeds the total surface area.
# return the single slice that doesn't cut anything out.
return [slice(None)]
rupture_slices = []
dead_ends = set()
for row in range(nrows):
for col in range(ncols):
if col in dead_ends:
continue
# find the lengths of all possible subsurfaces containing
# only the current row and from the current column till
# the last one.
lengths_acc = numpy.add.accumulate(cell_length[row, col:])
# find the "best match" number of columns, the one that gives
# the least difference between actual and requested rupture
# length (note that we only consider top row here, mainly
# for simplicity: it's not yet clear how many rows will we
# end up with).
rup_cols = numpy.argmin(numpy.abs(lengths_acc - rupture_length))
last_col = rup_cols + col + 1
if last_col == ncols and lengths_acc[rup_cols] < rupture_length:
# rupture doesn't fit along length (the requested rupture
# length is greater than the length of the part of current
# row that starts from the current column).
if col != 0:
# if we are not in the first column, it means that we
# hit the right border, so we need to go to the next
# row.
break
# now try to find the optimum (the one providing the closest
# to requested area) number of rows.
areas_acc = numpy.sum(cell_area[row:, col:last_col], axis=1)
areas_acc = numpy.add.accumulate(areas_acc, axis=0)
rup_rows = numpy.argmin(numpy.abs(areas_acc - rupture_area))
last_row = rup_rows + row + 1
if last_row == nrows and areas_acc[rup_rows] < rupture_area:
# rupture doesn't fit along width.
# we can try to extend it along length but only if we are
# at the first row
if row == 0:
if last_col == ncols:
# there is no place to extend, exiting
return rupture_slices
else:
# try to extend along length
areas_acc = numpy.sum(cell_area[:, col:], axis=0)
areas_acc = numpy.add.accumulate(areas_acc, axis=0)
rup_cols = numpy.argmin(
numpy.abs(areas_acc - rupture_area))
last_col = rup_cols + col + 1
if last_col == ncols \
and areas_acc[rup_cols] < rupture_area:
# still doesn't fit, return
return rupture_slices
else:
# row is not the first and the required area exceeds
# available area starting from target row and column.
# mark the column as "dead end" so we don't create
# one more rupture from the same column on all
# subsequent rows.
dead_ends.add(col)
# here we add 1 to last row and column numbers because we want
# to return slices for cutting the mesh of vertices, not the cell
# data (like cell_area or cell_length).
rupture_slices.append((slice(row, last_row + 1),
slice(col, last_col + 1)))
return rupture_slices | 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 extension along fault trace) of the rupture,
in km.
:param cell_area:
2d numpy array representing area of mesh cells in squared km.
:param cell_length:
2d numpy array of the shape as ``cell_area`` representing cells'
length in km.
:returns:
A list of slice objects. Number of items in the list is equal to number
of possible locations of the requested rupture on the fault surface.
Each slice can be used to get a portion of the whole fault surface mesh
that would represent the location of the rupture.
"""
nrows, ncols = cell_length.shape
if rupture_area >= numpy.sum(cell_area):
# requested rupture area exceeds the total surface area.
# return the single slice that doesn't cut anything out.
return [slice(None)]
rupture_slices = []
dead_ends = set()
for row in range(nrows):
for col in range(ncols):
if col in dead_ends:
continue
# find the lengths of all possible subsurfaces containing
# only the current row and from the current column till
# the last one.
lengths_acc = numpy.add.accumulate(cell_length[row, col:])
# find the "best match" number of columns, the one that gives
# the least difference between actual and requested rupture
# length (note that we only consider top row here, mainly
# for simplicity: it's not yet clear how many rows will we
# end up with).
rup_cols = numpy.argmin(numpy.abs(lengths_acc - rupture_length))
last_col = rup_cols + col + 1
if last_col == ncols and lengths_acc[rup_cols] < rupture_length:
# rupture doesn't fit along length (the requested rupture
# length is greater than the length of the part of current
# row that starts from the current column).
if col != 0:
# if we are not in the first column, it means that we
# hit the right border, so we need to go to the next
# row.
break
# now try to find the optimum (the one providing the closest
# to requested area) number of rows.
areas_acc = numpy.sum(cell_area[row:, col:last_col], axis=1)
areas_acc = numpy.add.accumulate(areas_acc, axis=0)
rup_rows = numpy.argmin(numpy.abs(areas_acc - rupture_area))
last_row = rup_rows + row + 1
if last_row == nrows and areas_acc[rup_rows] < rupture_area:
# rupture doesn't fit along width.
# we can try to extend it along length but only if we are
# at the first row
if row == 0:
if last_col == ncols:
# there is no place to extend, exiting
return rupture_slices
else:
# try to extend along length
areas_acc = numpy.sum(cell_area[:, col:], axis=0)
areas_acc = numpy.add.accumulate(areas_acc, axis=0)
rup_cols = numpy.argmin(
numpy.abs(areas_acc - rupture_area))
last_col = rup_cols + col + 1
if last_col == ncols \
and areas_acc[rup_cols] < rupture_area:
# still doesn't fit, return
return rupture_slices
else:
# row is not the first and the required area exceeds
# available area starting from target row and column.
# mark the column as "dead end" so we don't create
# one more rupture from the same column on all
# subsequent rows.
dead_ends.add(col)
# here we add 1 to last row and column numbers because we want
# to return slices for cutting the mesh of vertices, not the cell
# data (like cell_area or cell_length).
rupture_slices.append((slice(row, last_row + 1),
slice(col, last_col + 1)))
return rupture_slices | [
"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:
2d numpy array representing area of mesh cells in squared km.
:param cell_length:
2d numpy array of the shape as ``cell_area`` representing cells'
length in km.
:returns:
A list of slice objects. Number of items in the list is equal to number
of possible locations of the requested rupture on the fault surface.
Each slice can be used to get a portion of the whole fault surface mesh
that would represent the location of the rupture. | [
"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 | 213,879 |
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)
rjb[rjb < 0.0] = 0.0
return rjb | 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)
rjb[rjb < 0.0] = 0.0
return rjb | [
"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 | 213,880 |
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, rup.mag)
rjb[rjb < 0.1] = 0.1
p_n.append(self._get_normalised_term(np.log10(rjb),
self.CONSTANTS["logMaxR"],
self.CONSTANTS["logMinR"]))
# Magnitude
p_n.append(self._get_normalised_term(rup.mag,
self.CONSTANTS["maxMw"],
self.CONSTANTS["minMw"]))
# Vs30
p_n.append(self._get_normalised_term(np.log10(sites.vs30),
self.CONSTANTS["logMaxVs30"],
self.CONSTANTS["logMinVs30"]))
# Depth
p_n.append(self._get_normalised_term(rup.hypo_depth,
self.CONSTANTS["maxD"],
self.CONSTANTS["minD"]))
# Style of Faulting
p_n.append(self._get_normalised_term(sof,
self.CONSTANTS["maxFM"],
self.CONSTANTS["minFM"]))
return p_n | 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, rup.mag)
rjb[rjb < 0.1] = 0.1
p_n.append(self._get_normalised_term(np.log10(rjb),
self.CONSTANTS["logMaxR"],
self.CONSTANTS["logMinR"]))
# Magnitude
p_n.append(self._get_normalised_term(rup.mag,
self.CONSTANTS["maxMw"],
self.CONSTANTS["minMw"]))
# Vs30
p_n.append(self._get_normalised_term(np.log10(sites.vs30),
self.CONSTANTS["logMaxVs30"],
self.CONSTANTS["logMinVs30"]))
# Depth
p_n.append(self._get_normalised_term(rup.hypo_depth,
self.CONSTANTS["maxD"],
self.CONSTANTS["minD"]))
# Style of Faulting
p_n.append(self._get_normalised_term(sof,
self.CONSTANTS["maxFM"],
self.CONSTANTS["minFM"]))
return p_n | [
"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 | 213,881 |
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 mean, in units of sigma.
:param values:
Numpy array of values as input to a survival function for the given
distribution.
:returns:
Numpy array of survival function results in a range between 0 and 1.
>>> from scipy.stats import truncnorm
>>> truncnorm(-3, 3).sf(0.12345) == _truncnorm_sf(3, 0.12345)
True
"""
# 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
# of non-truncated distribution with that mu and sigma values.
# assume symmetric truncation, that is ``a = - truncation_level``
# and ``b = + truncation_level``.
# calculate CDF of b
phi_b = ndtr(truncation_level)
# calculate Z as ``Z = CDF(b) - CDF(a)``, here we assume that
# ``CDF(a) == CDF(- truncation_level) == 1 - CDF(b)``
z = phi_b * 2 - 1
# calculate the result of survival function of ``values``,
# and restrict it to the interval where probability is defined --
# 0..1. here we use some transformations of the original formula
# that is ``SF(x) = 1 - (CDF(x) - CDF(a)) / Z`` in order to minimize
# number of arithmetic operations and function calls:
# ``SF(x) = (Z - CDF(x) + CDF(a)) / Z``,
# ``SF(x) = (CDF(b) - CDF(a) - CDF(x) + CDF(a)) / Z``,
# ``SF(x) = (CDF(b) - CDF(x)) / Z``.
return ((phi_b - ndtr(values)) / z).clip(0.0, 1.0) | 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 mean, in units of sigma.
:param values:
Numpy array of values as input to a survival function for the given
distribution.
:returns:
Numpy array of survival function results in a range between 0 and 1.
>>> from scipy.stats import truncnorm
>>> truncnorm(-3, 3).sf(0.12345) == _truncnorm_sf(3, 0.12345)
True
"""
# 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
# of non-truncated distribution with that mu and sigma values.
# assume symmetric truncation, that is ``a = - truncation_level``
# and ``b = + truncation_level``.
# calculate CDF of b
phi_b = ndtr(truncation_level)
# calculate Z as ``Z = CDF(b) - CDF(a)``, here we assume that
# ``CDF(a) == CDF(- truncation_level) == 1 - CDF(b)``
z = phi_b * 2 - 1
# calculate the result of survival function of ``values``,
# and restrict it to the interval where probability is defined --
# 0..1. here we use some transformations of the original formula
# that is ``SF(x) = 1 - (CDF(x) - CDF(a)) / Z`` in order to minimize
# number of arithmetic operations and function calls:
# ``SF(x) = (Z - CDF(x) + CDF(a)) / Z``,
# ``SF(x) = (CDF(b) - CDF(a) - CDF(x) + CDF(a)) / Z``,
# ``SF(x) = (CDF(b) - CDF(x)) / Z``.
return ((phi_b - ndtr(values)) / z).clip(0.0, 1.0) | [
"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 array of values as input to a survival function for the given
distribution.
:returns:
Numpy array of survival function results in a range between 0 and 1.
>>> from scipy.stats import truncnorm
>>> truncnorm(-3, 3).sf(0.12345) == _truncnorm_sf(3, 0.12345)
True | [
"Survival",
"function",
"for",
"truncated",
"normal",
"distribution",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/base.py#L468-L512 | train | 213,882 |
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 | 213,883 |
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):
try:
val = getattr(self.gmpe, key)
except AttributeError:
pass
else:
setattr(self, key, val) | 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):
try:
val = getattr(self.gmpe, key)
except AttributeError:
pass
else:
setattr(self, key, val) | [
"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 | 213,884 |
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 IMT')
coeff_names = header[1:]
for row in table:
row = row.split()
imt_name = row[0].upper()
if imt_name == 'SA':
raise ValueError('specify period as float value '
'to declare SA IMT')
imt_coeffs = dict(zip(coeff_names, map(float, row[1:])))
try:
sa_period = float(imt_name)
except Exception:
if imt_name not in imt_module.registry:
raise ValueError('unknown IMT %r' % imt_name)
imt = imt_module.registry[imt_name]()
self.non_sa_coeffs[imt] = imt_coeffs
else:
if sa_damping is None:
raise TypeError('attribute "sa_damping" is required '
'for tables defining SA')
imt = imt_module.SA(sa_period, sa_damping)
self.sa_coeffs[imt] = imt_coeffs | 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 IMT')
coeff_names = header[1:]
for row in table:
row = row.split()
imt_name = row[0].upper()
if imt_name == 'SA':
raise ValueError('specify period as float value '
'to declare SA IMT')
imt_coeffs = dict(zip(coeff_names, map(float, row[1:])))
try:
sa_period = float(imt_name)
except Exception:
if imt_name not in imt_module.registry:
raise ValueError('unknown IMT %r' % imt_name)
imt = imt_module.registry[imt_name]()
self.non_sa_coeffs[imt] = imt_coeffs
else:
if sa_damping is None:
raise TypeError('attribute "sa_damping" is required '
'for tables defining SA')
imt = imt_module.SA(sa_period, sa_damping)
self.sa_coeffs[imt] = imt_coeffs | [
"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 | 213,885 |
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 | 213,886 |
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 np.log(10**0.27)
else:
return np.log(10**(0.23 + (imt.period - 0.2)/0.8 * 0.04)) | 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 np.log(10**0.27)
else:
return np.log(10**(0.23 + (imt.period - 0.2)/0.8 * 0.04)) | [
"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 | 213,887 |
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 and not has_default:
raise RuntimeError(
"Configuration not complete. %s missing" % field) | 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 and not has_default:
raise RuntimeError(
"Configuration not complete. %s missing" % field) | [
"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 | 213,888 |
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, default_value in defaults.items():
if field not in config:
config[field] = default_value | 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, default_value in defaults.items():
if field not in config:
config[field] = default_value | [
"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 | 213,889 |
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 method_name:
the method to decorate
:param bool completeness:
True if the method accepts in input an optional parameter
for the completeness table
:param fields:
a dictionary of field spec corresponding to the
keys expected to be present in the config dictionary
for the decorated method, e.g.
time_bin=numpy.float,
b_value=1E-6
"""
def class_decorator(class_obj):
original_method = getattr(class_obj, method_name)
if sys.version[0] == '2': # Python 2
original_method = original_method.im_func
def caller(fn, obj, catalogue, config=None, *args, **kwargs):
config = config or {}
self.set_defaults(config, fields)
self.check_config(config, fields)
return fn(obj, catalogue, config, *args, **kwargs)
new_method = decorator(caller, original_method)
setattr(class_obj, method_name, new_method)
instance = class_obj()
func = functools.partial(new_method, instance)
func.fields = fields
func.model = instance
func.completeness = completeness
functools.update_wrapper(func, new_method)
self[class_obj.__name__] = func
return class_obj
return class_decorator | 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 method_name:
the method to decorate
:param bool completeness:
True if the method accepts in input an optional parameter
for the completeness table
:param fields:
a dictionary of field spec corresponding to the
keys expected to be present in the config dictionary
for the decorated method, e.g.
time_bin=numpy.float,
b_value=1E-6
"""
def class_decorator(class_obj):
original_method = getattr(class_obj, method_name)
if sys.version[0] == '2': # Python 2
original_method = original_method.im_func
def caller(fn, obj, catalogue, config=None, *args, **kwargs):
config = config or {}
self.set_defaults(config, fields)
self.check_config(config, fields)
return fn(obj, catalogue, config, *args, **kwargs)
new_method = decorator(caller, original_method)
setattr(class_obj, method_name, new_method)
instance = class_obj()
func = functools.partial(new_method, instance)
func.fields = fields
func.model = instance
func.completeness = completeness
functools.update_wrapper(func, new_method)
self[class_obj.__name__] = func
return class_obj
return class_decorator | [
"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:
True if the method accepts in input an optional parameter
for the completeness table
:param fields:
a dictionary of field spec corresponding to the
keys expected to be present in the config dictionary
for the decorated method, e.g.
time_bin=numpy.float,
b_value=1E-6 | [
"Class",
"decorator",
"."
] | 8294553a0b8aba33fd96437a35065d03547d0040 | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/registry.py#L80-L120 | train | 213,890 |
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 * rup.mag + 16.05)
# Get stress-drop scaling (equation 6)
if rup.mag > C["m2"]:
stress_drop += (C["b2"] * (C["m2"] - self.CONSTANTS["mstar"]) +
(C["b3"] * (rup.mag - C["m2"])))
else:
stress_drop += (C["b2"] * (rup.mag - self.CONSTANTS["mstar"]))
stress_drop = np.exp(stress_drop)
# Get corner frequency (equation 4)
f0 = 4.9 * 1.0E6 * 3.2 * ((stress_drop / m_0) ** (1. / 3.))
return 1. / f0 | 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 * rup.mag + 16.05)
# Get stress-drop scaling (equation 6)
if rup.mag > C["m2"]:
stress_drop += (C["b2"] * (C["m2"] - self.CONSTANTS["mstar"]) +
(C["b3"] * (rup.mag - C["m2"])))
else:
stress_drop += (C["b2"] * (rup.mag - self.CONSTANTS["mstar"]))
stress_drop = np.exp(stress_drop)
# Get corner frequency (equation 4)
f0 = 4.9 * 1.0E6 * 3.2 * ((stress_drop / m_0) ** (1. / 3.))
return 1. / f0 | [
"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 | 213,891 |
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"]) +\
C["c2"] * (rrup[idx] - self.CONSTANTS["r1"])
idx = rrup > self.CONSTANTS["r2"]
f_p[idx] = C["c1"] * self.CONSTANTS["r1"] +\
C["c2"] * (self.CONSTANTS["r2"] - self.CONSTANTS["r1"]) +\
C["c3"] * (rrup[idx] - self.CONSTANTS["r2"])
return f_p | 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"]) +\
C["c2"] * (rrup[idx] - self.CONSTANTS["r1"])
idx = rrup > self.CONSTANTS["r2"]
f_p[idx] = C["c1"] * self.CONSTANTS["r1"] +\
C["c2"] * (self.CONSTANTS["r2"] - self.CONSTANTS["r1"]) +\
C["c3"] * (rrup[idx] - self.CONSTANTS["r2"])
return f_p | [
"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 | 213,892 |
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
return C["b0N"], C["b1N"]
else:
# Strike slip
return C["b0SS"], C["b1SS"] | 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
return C["b0N"], C["b1N"]
else:
# Strike slip
return C["b0SS"], C["b1SS"] | [
"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 | 213,893 |
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["dz1ref"]] = (C["c5"] *
self.CONSTANTS["dz1ref"])
idx = sites.vs30 > self.CONSTANTS["v1"]
f_s[idx] += (C["c4"] * np.log(self.CONSTANTS["v1"] / C["vref"]))
idx = np.logical_not(idx)
f_s[idx] += (C["c4"] * np.log(sites.vs30[idx] / C["vref"]))
return f_s | 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["dz1ref"]] = (C["c5"] *
self.CONSTANTS["dz1ref"])
idx = sites.vs30 > self.CONSTANTS["v1"]
f_s[idx] += (C["c4"] * np.log(self.CONSTANTS["v1"] / C["vref"]))
idx = np.logical_not(idx)
f_s[idx] += (C["c4"] * np.log(sites.vs30[idx] / C["vref"]))
return f_s | [
"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 | 213,894 |
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 ** 2)
else:
R = np.sqrt(dists.rrup ** 2 + delta ** 2)
mean = (
# 1st term
C['c1'] + C['c2'] * mag +
# 2nd term
C['c3'] * R -
# 3rd term
C['c4'] * np.log10(R) +
# 4th term
C['c5'] * hypo_depth
)
# convert from base 10 to base e
if imt == PGV():
mean = np.log(10 ** mean)
else:
# convert from cm/s**2 to g
mean = np.log((10 ** mean) * 1e-2 / g)
return mean | 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 ** 2)
else:
R = np.sqrt(dists.rrup ** 2 + delta ** 2)
mean = (
# 1st term
C['c1'] + C['c2'] * mag +
# 2nd term
C['c3'] * R -
# 3rd term
C['c4'] * np.log10(R) +
# 4th term
C['c5'] * hypo_depth
)
# convert from base 10 to base e
if imt == PGV():
mean = np.log(10 ** mean)
else:
# convert from cm/s**2 to g
mean = np.log((10 ** mean) * 1e-2 / g)
return mean | [
"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 | 213,895 |
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_stats('cumtime')
ps.print_stats(n)
stream.seek(0)
lines = list(stream)
for i, line in enumerate(lines):
if line.startswith(' ncalls'):
break
data = []
for line in lines[i + 2:]:
columns = line.split()
if len(columns) == 6:
data.append(PStatData(*columns))
rows = [(rec.ncalls, rec.cumtime, rec.path) for rec in data]
# here is an example of the expected output table:
# ====== ======= ========================================================
# ncalls cumtime path
# ====== ======= ========================================================
# 1 33.502 commands/run.py:77(_run)
# 1 33.483 calculators/base.py:110(run)
# 1 25.166 calculators/classical.py:115(execute)
# 1 25.104 baselib.parallel.py:249(apply_reduce)
# 1 25.099 calculators/classical.py:41(classical)
# 1 25.099 hazardlib/calc/hazard_curve.py:164(classical)
return views.rst_table(rows, header='ncalls cumtime path'.split()) | 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_stats('cumtime')
ps.print_stats(n)
stream.seek(0)
lines = list(stream)
for i, line in enumerate(lines):
if line.startswith(' ncalls'):
break
data = []
for line in lines[i + 2:]:
columns = line.split()
if len(columns) == 6:
data.append(PStatData(*columns))
rows = [(rec.ncalls, rec.cumtime, rec.path) for rec in data]
# here is an example of the expected output table:
# ====== ======= ========================================================
# ncalls cumtime path
# ====== ======= ========================================================
# 1 33.502 commands/run.py:77(_run)
# 1 33.483 calculators/base.py:110(run)
# 1 25.166 calculators/classical.py:115(execute)
# 1 25.104 baselib.parallel.py:249(apply_reduce)
# 1 25.099 calculators/classical.py:41(classical)
# 1 25.099 hazardlib/calc/hazard_curve.py:164(classical)
return views.rst_table(rows, header='ncalls cumtime path'.split()) | [
"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 | 213,896 |
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, **params)
hc_id = hcalc.datastore.calc_id
rcalc_id = logs.init(level=getattr(logging, loglevel.upper()))
oq = readinput.get_oqparam(job_risk, hc_id=hc_id)
rcalc = base.calculators(oq, rcalc_id)
rcalc.run(pdb=pdb, exports=exports, **params)
return rcalc | 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, **params)
hc_id = hcalc.datastore.calc_id
rcalc_id = logs.init(level=getattr(logging, loglevel.upper()))
oq = readinput.get_oqparam(job_risk, hc_id=hc_id)
rcalc = base.calculators(oq, rcalc_id)
rcalc.run(pdb=pdb, exports=exports, **params)
return rcalc | [
"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 | 213,897 |
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.split(',')))
else:
params = {}
if slowest:
prof = cProfile.Profile()
stmt = ('_run(job_ini, concurrent_tasks, pdb, loglevel, hc, '
'exports, params)')
prof.runctx(stmt, globals(), locals())
pstat = calc_path + '.pstat'
prof.dump_stats(pstat)
print('Saved profiling info in %s' % pstat)
print(get_pstats(pstat, slowest))
else:
_run(job_ini, concurrent_tasks, pdb, loglevel, hc, exports, params) | 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.split(',')))
else:
params = {}
if slowest:
prof = cProfile.Profile()
stmt = ('_run(job_ini, concurrent_tasks, pdb, loglevel, hc, '
'exports, params)')
prof.runctx(stmt, globals(), locals())
pstat = calc_path + '.pstat'
prof.dump_stats(pstat)
print('Saved profiling info in %s' % pstat)
print(get_pstats(pstat, slowest))
else:
_run(job_ini, concurrent_tasks, pdb, loglevel, hc, exports, params) | [
"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 | 213,898 |
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'):
modname, _ext = os.path.splitext(fname)
mod = importlib.import_module(
'openquake.hazardlib.scalerel.' + modname)
for cls in mod.__dict__.values():
if inspect.isclass(cls) and issubclass(cls, base_class) \
and cls != base_class \
and not inspect.isabstract(cls):
gsims[cls.__name__] = cls
return dict((k, gsims[k]) for k in sorted(gsims)) | 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'):
modname, _ext = os.path.splitext(fname)
mod = importlib.import_module(
'openquake.hazardlib.scalerel.' + modname)
for cls in mod.__dict__.values():
if inspect.isclass(cls) and issubclass(cls, base_class) \
and cls != base_class \
and not inspect.isabstract(cls):
gsims[cls.__name__] = cls
return dict((k, gsims[k]) for k in sorted(gsims)) | [
"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 | 213,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.