repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
IdentityPython/oidcendpoint | src/oidcendpoint/oidc/discovery.py | Discovery.do_response | def do_response(self, response_args=None, request=None, **kwargs):
"""
**Placeholder for the time being**
:param response_args:
:param request:
:param kwargs: request arguments
:return: Response information
"""
links = [Link(href=h, rel=OIC_ISSUER) for h... | python | def do_response(self, response_args=None, request=None, **kwargs):
"""
**Placeholder for the time being**
:param response_args:
:param request:
:param kwargs: request arguments
:return: Response information
"""
links = [Link(href=h, rel=OIC_ISSUER) for h... | [
"def",
"do_response",
"(",
"self",
",",
"response_args",
"=",
"None",
",",
"request",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"links",
"=",
"[",
"Link",
"(",
"href",
"=",
"h",
",",
"rel",
"=",
"OIC_ISSUER",
")",
"for",
"h",
"in",
"kwargs",
... | **Placeholder for the time being**
:param response_args:
:param request:
:param kwargs: request arguments
:return: Response information | [
"**",
"Placeholder",
"for",
"the",
"time",
"being",
"**"
] | train | https://github.com/IdentityPython/oidcendpoint/blob/6c1d729d51bfb6332816117fe476073df7a1d823/src/oidcendpoint/oidc/discovery.py#L17-L36 |
BeyondTheClouds/enoslib | enoslib/infra/enos_openstack/provider.py | get_session | def get_session():
"""Build the session object."""
# NOTE(msimonin): We provide only a basic support which focus
# Chameleon cloud and its rc files
if os.environ.get("OS_IDENTITY_API_VERSION") == "3":
logging.info("Creating a v3 Keystone Session")
auth = v3.Password(
auth_url... | python | def get_session():
"""Build the session object."""
# NOTE(msimonin): We provide only a basic support which focus
# Chameleon cloud and its rc files
if os.environ.get("OS_IDENTITY_API_VERSION") == "3":
logging.info("Creating a v3 Keystone Session")
auth = v3.Password(
auth_url... | [
"def",
"get_session",
"(",
")",
":",
"# NOTE(msimonin): We provide only a basic support which focus",
"# Chameleon cloud and its rc files",
"if",
"os",
".",
"environ",
".",
"get",
"(",
"\"OS_IDENTITY_API_VERSION\"",
")",
"==",
"\"3\"",
":",
"logging",
".",
"info",
"(",
... | Build the session object. | [
"Build",
"the",
"session",
"object",
"."
] | train | https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/infra/enos_openstack/provider.py#L27-L49 |
BeyondTheClouds/enoslib | enoslib/infra/enos_openstack/provider.py | check_glance | def check_glance(session, image_name):
"""Check that the base image is available.
Fails if the base image isn't added.
This means the image should be added manually.
"""
gclient = glance.Client(GLANCE_VERSION, session=session,
region_name=os.environ['OS_REGION_NAME'])
... | python | def check_glance(session, image_name):
"""Check that the base image is available.
Fails if the base image isn't added.
This means the image should be added manually.
"""
gclient = glance.Client(GLANCE_VERSION, session=session,
region_name=os.environ['OS_REGION_NAME'])
... | [
"def",
"check_glance",
"(",
"session",
",",
"image_name",
")",
":",
"gclient",
"=",
"glance",
".",
"Client",
"(",
"GLANCE_VERSION",
",",
"session",
"=",
"session",
",",
"region_name",
"=",
"os",
".",
"environ",
"[",
"'OS_REGION_NAME'",
"]",
")",
"images",
... | Check that the base image is available.
Fails if the base image isn't added.
This means the image should be added manually. | [
"Check",
"that",
"the",
"base",
"image",
"is",
"available",
"."
] | train | https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/infra/enos_openstack/provider.py#L52-L69 |
BeyondTheClouds/enoslib | enoslib/infra/enos_openstack/provider.py | check_flavors | def check_flavors(session):
"""Build the flavors mapping
returns the mappings id <-> flavor
"""
nclient = nova.Client(NOVA_VERSION, session=session,
region_name=os.environ['OS_REGION_NAME'])
flavors = nclient.flavors.list()
to_id = dict(list(map(lambda n: [n.name, n.id... | python | def check_flavors(session):
"""Build the flavors mapping
returns the mappings id <-> flavor
"""
nclient = nova.Client(NOVA_VERSION, session=session,
region_name=os.environ['OS_REGION_NAME'])
flavors = nclient.flavors.list()
to_id = dict(list(map(lambda n: [n.name, n.id... | [
"def",
"check_flavors",
"(",
"session",
")",
":",
"nclient",
"=",
"nova",
".",
"Client",
"(",
"NOVA_VERSION",
",",
"session",
"=",
"session",
",",
"region_name",
"=",
"os",
".",
"environ",
"[",
"'OS_REGION_NAME'",
"]",
")",
"flavors",
"=",
"nclient",
".",
... | Build the flavors mapping
returns the mappings id <-> flavor | [
"Build",
"the",
"flavors",
"mapping"
] | train | https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/infra/enos_openstack/provider.py#L72-L82 |
BeyondTheClouds/enoslib | enoslib/infra/enos_openstack/provider.py | check_network | def check_network(session, configure_network, network, subnet,
dns_nameservers=None, allocation_pool=None):
"""Check the network status for the deployment.
If needed, it creates a dedicated :
* private network /subnet
* router between this network and the external network
... | python | def check_network(session, configure_network, network, subnet,
dns_nameservers=None, allocation_pool=None):
"""Check the network status for the deployment.
If needed, it creates a dedicated :
* private network /subnet
* router between this network and the external network
... | [
"def",
"check_network",
"(",
"session",
",",
"configure_network",
",",
"network",
",",
"subnet",
",",
"dns_nameservers",
"=",
"None",
",",
"allocation_pool",
"=",
"None",
")",
":",
"nclient",
"=",
"neutron",
".",
"Client",
"(",
"'2'",
",",
"session",
"=",
... | Check the network status for the deployment.
If needed, it creates a dedicated :
* private network /subnet
* router between this network and the external network | [
"Check",
"the",
"network",
"status",
"for",
"the",
"deployment",
"."
] | train | https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/infra/enos_openstack/provider.py#L85-L183 |
BeyondTheClouds/enoslib | enoslib/infra/enos_openstack/provider.py | wait_for_servers | def wait_for_servers(session, servers):
"""Wait for the servers to be ready.
Note(msimonin): we don't garantee the SSH connection to be ready.
"""
nclient = nova.Client(NOVA_VERSION, session=session,
region_name=os.environ['OS_REGION_NAME'])
while True:
deployed = ... | python | def wait_for_servers(session, servers):
"""Wait for the servers to be ready.
Note(msimonin): we don't garantee the SSH connection to be ready.
"""
nclient = nova.Client(NOVA_VERSION, session=session,
region_name=os.environ['OS_REGION_NAME'])
while True:
deployed = ... | [
"def",
"wait_for_servers",
"(",
"session",
",",
"servers",
")",
":",
"nclient",
"=",
"nova",
".",
"Client",
"(",
"NOVA_VERSION",
",",
"session",
"=",
"session",
",",
"region_name",
"=",
"os",
".",
"environ",
"[",
"'OS_REGION_NAME'",
"]",
")",
"while",
"Tru... | Wait for the servers to be ready.
Note(msimonin): we don't garantee the SSH connection to be ready. | [
"Wait",
"for",
"the",
"servers",
"to",
"be",
"ready",
"."
] | train | https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/infra/enos_openstack/provider.py#L208-L230 |
BeyondTheClouds/enoslib | enoslib/infra/enos_openstack/provider.py | check_servers | def check_servers(session, machines, extra_prefix="",
force_deploy=False, key_name=None, image_id=None,
flavors='m1.medium', network=None, ext_net=None,
scheduler_hints=None):
"""Checks the servers status for the deployment.
If needed, it creates new server... | python | def check_servers(session, machines, extra_prefix="",
force_deploy=False, key_name=None, image_id=None,
flavors='m1.medium', network=None, ext_net=None,
scheduler_hints=None):
"""Checks the servers status for the deployment.
If needed, it creates new server... | [
"def",
"check_servers",
"(",
"session",
",",
"machines",
",",
"extra_prefix",
"=",
"\"\"",
",",
"force_deploy",
"=",
"False",
",",
"key_name",
"=",
"None",
",",
"image_id",
"=",
"None",
",",
"flavors",
"=",
"'m1.medium'",
",",
"network",
"=",
"None",
",",
... | Checks the servers status for the deployment.
If needed, it creates new servers and add a floating ip to one of them.
This server can be used as a gateway to the others. | [
"Checks",
"the",
"servers",
"status",
"for",
"the",
"deployment",
"."
] | train | https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/infra/enos_openstack/provider.py#L238-L297 |
BeyondTheClouds/enoslib | enoslib/infra/enos_openstack/provider.py | is_in_current_deployment | def is_in_current_deployment(server, extra_prefix=""):
"""Check if an existing server in the system take part to
the current deployment
"""
return re.match(r"^%s" % '-'.join([DEFAULT_PREFIX, extra_prefix]),
server.name) is not None | python | def is_in_current_deployment(server, extra_prefix=""):
"""Check if an existing server in the system take part to
the current deployment
"""
return re.match(r"^%s" % '-'.join([DEFAULT_PREFIX, extra_prefix]),
server.name) is not None | [
"def",
"is_in_current_deployment",
"(",
"server",
",",
"extra_prefix",
"=",
"\"\"",
")",
":",
"return",
"re",
".",
"match",
"(",
"r\"^%s\"",
"%",
"'-'",
".",
"join",
"(",
"[",
"DEFAULT_PREFIX",
",",
"extra_prefix",
"]",
")",
",",
"server",
".",
"name",
"... | Check if an existing server in the system take part to
the current deployment | [
"Check",
"if",
"an",
"existing",
"server",
"in",
"the",
"system",
"take",
"part",
"to",
"the",
"current",
"deployment"
] | train | https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/infra/enos_openstack/provider.py#L321-L326 |
BeyondTheClouds/enoslib | enoslib/infra/enos_openstack/provider.py | allow_address_pairs | def allow_address_pairs(session, network, subnet):
"""Allow several interfaces to be added and accessed from the other machines.
This is particularly useful when working with virtual ips.
"""
nclient = neutron.Client('2', session=session,
region_name=os.environ['OS_REGION_N... | python | def allow_address_pairs(session, network, subnet):
"""Allow several interfaces to be added and accessed from the other machines.
This is particularly useful when working with virtual ips.
"""
nclient = neutron.Client('2', session=session,
region_name=os.environ['OS_REGION_N... | [
"def",
"allow_address_pairs",
"(",
"session",
",",
"network",
",",
"subnet",
")",
":",
"nclient",
"=",
"neutron",
".",
"Client",
"(",
"'2'",
",",
"session",
"=",
"session",
",",
"region_name",
"=",
"os",
".",
"environ",
"[",
"'OS_REGION_NAME'",
"]",
")",
... | Allow several interfaces to be added and accessed from the other machines.
This is particularly useful when working with virtual ips. | [
"Allow",
"several",
"interfaces",
"to",
"be",
"added",
"and",
"accessed",
"from",
"the",
"other",
"machines",
"."
] | train | https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/infra/enos_openstack/provider.py#L329-L356 |
BeyondTheClouds/enoslib | enoslib/infra/enos_openstack/provider.py | check_environment | def check_environment(provider_conf):
"""Check all ressources needed by Enos."""
session = get_session()
image_id = check_glance(session, provider_conf.image)
flavor_to_id, id_to_flavor = check_flavors(session)
ext_net, network, subnet = check_network(
session,
provider_conf.configur... | python | def check_environment(provider_conf):
"""Check all ressources needed by Enos."""
session = get_session()
image_id = check_glance(session, provider_conf.image)
flavor_to_id, id_to_flavor = check_flavors(session)
ext_net, network, subnet = check_network(
session,
provider_conf.configur... | [
"def",
"check_environment",
"(",
"provider_conf",
")",
":",
"session",
"=",
"get_session",
"(",
")",
"image_id",
"=",
"check_glance",
"(",
"session",
",",
"provider_conf",
".",
"image",
")",
"flavor_to_id",
",",
"id_to_flavor",
"=",
"check_flavors",
"(",
"sessio... | Check all ressources needed by Enos. | [
"Check",
"all",
"ressources",
"needed",
"by",
"Enos",
"."
] | train | https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/infra/enos_openstack/provider.py#L359-L380 |
IdentityPython/oidcendpoint | src/oidcendpoint/userinfo.py | claims_match | def claims_match(value, claimspec):
"""
Implements matching according to section 5.5.1 of
http://openid.net/specs/openid-connect-core-1_0.html
The lack of value is not checked here.
Also the text doesn't prohibit having both 'value' and 'values'.
:param value: single value
:param claimspec:... | python | def claims_match(value, claimspec):
"""
Implements matching according to section 5.5.1 of
http://openid.net/specs/openid-connect-core-1_0.html
The lack of value is not checked here.
Also the text doesn't prohibit having both 'value' and 'values'.
:param value: single value
:param claimspec:... | [
"def",
"claims_match",
"(",
"value",
",",
"claimspec",
")",
":",
"if",
"claimspec",
"is",
"None",
":",
"# match anything",
"return",
"True",
"matched",
"=",
"False",
"for",
"key",
",",
"val",
"in",
"claimspec",
".",
"items",
"(",
")",
":",
"if",
"key",
... | Implements matching according to section 5.5.1 of
http://openid.net/specs/openid-connect-core-1_0.html
The lack of value is not checked here.
Also the text doesn't prohibit having both 'value' and 'values'.
:param value: single value
:param claimspec: None or dictionary with 'essential', 'value' or... | [
"Implements",
"matching",
"according",
"to",
"section",
"5",
".",
"5",
".",
"1",
"of",
"http",
":",
"//",
"openid",
".",
"net",
"/",
"specs",
"/",
"openid",
"-",
"connect",
"-",
"core",
"-",
"1_0",
".",
"html",
"The",
"lack",
"of",
"value",
"is",
"... | train | https://github.com/IdentityPython/oidcendpoint/blob/6c1d729d51bfb6332816117fe476073df7a1d823/src/oidcendpoint/userinfo.py#L57-L91 |
IdentityPython/oidcendpoint | src/oidcendpoint/userinfo.py | collect_user_info | def collect_user_info(endpoint_context, session, userinfo_claims=None):
"""
Collect information about a user.
This can happen in two cases, either when constructing an IdToken or
when returning user info through the UserInfo endpoint
:param session: Session information
:param userinfo_claims: u... | python | def collect_user_info(endpoint_context, session, userinfo_claims=None):
"""
Collect information about a user.
This can happen in two cases, either when constructing an IdToken or
when returning user info through the UserInfo endpoint
:param session: Session information
:param userinfo_claims: u... | [
"def",
"collect_user_info",
"(",
"endpoint_context",
",",
"session",
",",
"userinfo_claims",
"=",
"None",
")",
":",
"authn_req",
"=",
"session",
"[",
"'authn_req'",
"]",
"if",
"userinfo_claims",
"is",
"None",
":",
"uic",
"=",
"scope2claims",
"(",
"authn_req",
... | Collect information about a user.
This can happen in two cases, either when constructing an IdToken or
when returning user info through the UserInfo endpoint
:param session: Session information
:param userinfo_claims: user info claims
:return: User info | [
"Collect",
"information",
"about",
"a",
"user",
".",
"This",
"can",
"happen",
"in",
"two",
"cases",
"either",
"when",
"constructing",
"an",
"IdToken",
"or",
"when",
"returning",
"user",
"info",
"through",
"the",
"UserInfo",
"endpoint"
] | train | https://github.com/IdentityPython/oidcendpoint/blob/6c1d729d51bfb6332816117fe476073df7a1d823/src/oidcendpoint/userinfo.py#L105-L161 |
IdentityPython/oidcendpoint | src/oidcendpoint/userinfo.py | userinfo_in_id_token_claims | def userinfo_in_id_token_claims(endpoint_context, session, def_itc=None):
"""
Collect user info claims that are to be placed in the id token.
:param endpoint_context: Endpoint context
:param session: Session information
:param def_itc: Default ID Token claims
:return: User information or None
... | python | def userinfo_in_id_token_claims(endpoint_context, session, def_itc=None):
"""
Collect user info claims that are to be placed in the id token.
:param endpoint_context: Endpoint context
:param session: Session information
:param def_itc: Default ID Token claims
:return: User information or None
... | [
"def",
"userinfo_in_id_token_claims",
"(",
"endpoint_context",
",",
"session",
",",
"def_itc",
"=",
"None",
")",
":",
"if",
"def_itc",
":",
"itc",
"=",
"def_itc",
"else",
":",
"itc",
"=",
"{",
"}",
"itc",
".",
"update",
"(",
"id_token_claims",
"(",
"sessio... | Collect user info claims that are to be placed in the id token.
:param endpoint_context: Endpoint context
:param session: Session information
:param def_itc: Default ID Token claims
:return: User information or None | [
"Collect",
"user",
"info",
"claims",
"that",
"are",
"to",
"be",
"placed",
"in",
"the",
"id",
"token",
"."
] | train | https://github.com/IdentityPython/oidcendpoint/blob/6c1d729d51bfb6332816117fe476073df7a1d823/src/oidcendpoint/userinfo.py#L164-L188 |
thombashi/tabledata | tabledata/_core.py | TableData.value_matrix | def value_matrix(self):
"""Converted rows of tabular data.
Returns:
|list| or |tuple|: Table rows.
"""
if self.__value_matrix:
return self.__value_matrix
self.__value_matrix = [
[value_dp.data for value_dp in value_dp_list] for value_dp_list... | python | def value_matrix(self):
"""Converted rows of tabular data.
Returns:
|list| or |tuple|: Table rows.
"""
if self.__value_matrix:
return self.__value_matrix
self.__value_matrix = [
[value_dp.data for value_dp in value_dp_list] for value_dp_list... | [
"def",
"value_matrix",
"(",
"self",
")",
":",
"if",
"self",
".",
"__value_matrix",
":",
"return",
"self",
".",
"__value_matrix",
"self",
".",
"__value_matrix",
"=",
"[",
"[",
"value_dp",
".",
"data",
"for",
"value_dp",
"in",
"value_dp_list",
"]",
"for",
"v... | Converted rows of tabular data.
Returns:
|list| or |tuple|: Table rows. | [
"Converted",
"rows",
"of",
"tabular",
"data",
"."
] | train | https://github.com/thombashi/tabledata/blob/03d623be30fc62381f1b7fb2aa0e17a0e26ad473/tabledata/_core.py#L79-L93 |
thombashi/tabledata | tabledata/_core.py | TableData.value_dp_matrix | def value_dp_matrix(self):
"""
:return: DataProperty for table data.
:rtype: list
"""
if self.__value_dp_matrix is None:
self.__value_dp_matrix = self.__dp_extractor.to_dp_matrix(
to_value_matrix(self.headers, self.rows)
)
return ... | python | def value_dp_matrix(self):
"""
:return: DataProperty for table data.
:rtype: list
"""
if self.__value_dp_matrix is None:
self.__value_dp_matrix = self.__dp_extractor.to_dp_matrix(
to_value_matrix(self.headers, self.rows)
)
return ... | [
"def",
"value_dp_matrix",
"(",
"self",
")",
":",
"if",
"self",
".",
"__value_dp_matrix",
"is",
"None",
":",
"self",
".",
"__value_dp_matrix",
"=",
"self",
".",
"__dp_extractor",
".",
"to_dp_matrix",
"(",
"to_value_matrix",
"(",
"self",
".",
"headers",
",",
"... | :return: DataProperty for table data.
:rtype: list | [
":",
"return",
":",
"DataProperty",
"for",
"table",
"data",
".",
":",
"rtype",
":",
"list"
] | train | https://github.com/thombashi/tabledata/blob/03d623be30fc62381f1b7fb2aa0e17a0e26ad473/tabledata/_core.py#L126-L137 |
thombashi/tabledata | tabledata/_core.py | TableData.validate_rows | def validate_rows(self):
"""
:raises ValueError:
"""
invalid_row_idx_list = []
for row_idx, row in enumerate(self.rows):
if isinstance(row, (list, tuple)) and len(self.headers) != len(row):
invalid_row_idx_list.append(row_idx)
if isinsta... | python | def validate_rows(self):
"""
:raises ValueError:
"""
invalid_row_idx_list = []
for row_idx, row in enumerate(self.rows):
if isinstance(row, (list, tuple)) and len(self.headers) != len(row):
invalid_row_idx_list.append(row_idx)
if isinsta... | [
"def",
"validate_rows",
"(",
"self",
")",
":",
"invalid_row_idx_list",
"=",
"[",
"]",
"for",
"row_idx",
",",
"row",
"in",
"enumerate",
"(",
"self",
".",
"rows",
")",
":",
"if",
"isinstance",
"(",
"row",
",",
"(",
"list",
",",
"tuple",
")",
")",
"and"... | :raises ValueError: | [
":",
"raises",
"ValueError",
":"
] | train | https://github.com/thombashi/tabledata/blob/03d623be30fc62381f1b7fb2aa0e17a0e26ad473/tabledata/_core.py#L288-L317 |
thombashi/tabledata | tabledata/_core.py | TableData.as_dict | def as_dict(self):
"""
:return: Table data as a |dict| instance.
:rtype: dict
:Sample Code:
.. code:: python
from tabledata import TableData
TableData(
"sample",
["a", "b"],
[[1, 2]... | python | def as_dict(self):
"""
:return: Table data as a |dict| instance.
:rtype: dict
:Sample Code:
.. code:: python
from tabledata import TableData
TableData(
"sample",
["a", "b"],
[[1, 2]... | [
"def",
"as_dict",
"(",
"self",
")",
":",
"dict_body",
"=",
"[",
"]",
"for",
"row",
"in",
"self",
".",
"rows",
":",
"if",
"not",
"row",
":",
"continue",
"values",
"=",
"[",
"(",
"header",
",",
"value",
")",
"for",
"header",
",",
"value",
"in",
"zi... | :return: Table data as a |dict| instance.
:rtype: dict
:Sample Code:
.. code:: python
from tabledata import TableData
TableData(
"sample",
["a", "b"],
[[1, 2], [3.3, 4.4]]
).as_dict... | [
":",
"return",
":",
"Table",
"data",
"as",
"a",
"|dict|",
"instance",
".",
":",
"rtype",
":",
"dict"
] | train | https://github.com/thombashi/tabledata/blob/03d623be30fc62381f1b7fb2aa0e17a0e26ad473/tabledata/_core.py#L319-L355 |
thombashi/tabledata | tabledata/_core.py | TableData.as_tuple | def as_tuple(self):
"""
:return: Rows of the table.
:rtype: list of |namedtuple|
:Sample Code:
.. code:: python
from tabledata import TableData
records = TableData(
"sample",
["a", "b"],
... | python | def as_tuple(self):
"""
:return: Rows of the table.
:rtype: list of |namedtuple|
:Sample Code:
.. code:: python
from tabledata import TableData
records = TableData(
"sample",
["a", "b"],
... | [
"def",
"as_tuple",
"(",
"self",
")",
":",
"Row",
"=",
"namedtuple",
"(",
"\"Row\"",
",",
"self",
".",
"headers",
")",
"for",
"value_dp_list",
"in",
"self",
".",
"value_dp_matrix",
":",
"if",
"typepy",
".",
"is_empty_sequence",
"(",
"value_dp_list",
")",
":... | :return: Rows of the table.
:rtype: list of |namedtuple|
:Sample Code:
.. code:: python
from tabledata import TableData
records = TableData(
"sample",
["a", "b"],
[[1, 2], [3.3, 4.4]]
... | [
":",
"return",
":",
"Rows",
"of",
"the",
"table",
".",
":",
"rtype",
":",
"list",
"of",
"|namedtuple|"
] | train | https://github.com/thombashi/tabledata/blob/03d623be30fc62381f1b7fb2aa0e17a0e26ad473/tabledata/_core.py#L357-L390 |
thombashi/tabledata | tabledata/_core.py | TableData.as_dataframe | def as_dataframe(self):
"""
:return: Table data as a ``pandas.DataFrame`` instance.
:rtype: pandas.DataFrame
:Sample Code:
.. code-block:: python
from tabledata import TableData
TableData(
"sample",
["... | python | def as_dataframe(self):
"""
:return: Table data as a ``pandas.DataFrame`` instance.
:rtype: pandas.DataFrame
:Sample Code:
.. code-block:: python
from tabledata import TableData
TableData(
"sample",
["... | [
"def",
"as_dataframe",
"(",
"self",
")",
":",
"import",
"pandas",
"dataframe",
"=",
"pandas",
".",
"DataFrame",
"(",
"self",
".",
"value_matrix",
")",
"if",
"not",
"self",
".",
"is_empty_header",
"(",
")",
":",
"dataframe",
".",
"columns",
"=",
"self",
"... | :return: Table data as a ``pandas.DataFrame`` instance.
:rtype: pandas.DataFrame
:Sample Code:
.. code-block:: python
from tabledata import TableData
TableData(
"sample",
["a", "b"],
[[1, 2], [3.3,... | [
":",
"return",
":",
"Table",
"data",
"as",
"a",
"pandas",
".",
"DataFrame",
"instance",
".",
":",
"rtype",
":",
"pandas",
".",
"DataFrame"
] | train | https://github.com/thombashi/tabledata/blob/03d623be30fc62381f1b7fb2aa0e17a0e26ad473/tabledata/_core.py#L392-L425 |
thombashi/tabledata | tabledata/_core.py | TableData.from_dataframe | def from_dataframe(dataframe, table_name=""):
"""
Initialize TableData instance from a pandas.DataFrame instance.
:param pandas.DataFrame dataframe:
:param str table_name: Table name to create.
"""
return TableData(table_name, list(dataframe.columns.values), dataframe.v... | python | def from_dataframe(dataframe, table_name=""):
"""
Initialize TableData instance from a pandas.DataFrame instance.
:param pandas.DataFrame dataframe:
:param str table_name: Table name to create.
"""
return TableData(table_name, list(dataframe.columns.values), dataframe.v... | [
"def",
"from_dataframe",
"(",
"dataframe",
",",
"table_name",
"=",
"\"\"",
")",
":",
"return",
"TableData",
"(",
"table_name",
",",
"list",
"(",
"dataframe",
".",
"columns",
".",
"values",
")",
",",
"dataframe",
".",
"values",
".",
"tolist",
"(",
")",
")... | Initialize TableData instance from a pandas.DataFrame instance.
:param pandas.DataFrame dataframe:
:param str table_name: Table name to create. | [
"Initialize",
"TableData",
"instance",
"from",
"a",
"pandas",
".",
"DataFrame",
"instance",
"."
] | train | https://github.com/thombashi/tabledata/blob/03d623be30fc62381f1b7fb2aa0e17a0e26ad473/tabledata/_core.py#L475-L483 |
volafiled/python-volapi | volapi/auxo.py | call_async | def call_async(func):
"""Decorates a function to be called async on the loop thread"""
@wraps(func)
def wrapper(self, *args, **kw):
"""Wraps instance method to be called on loop thread"""
def call():
"""Calls function on loop thread"""
try:
func(self... | python | def call_async(func):
"""Decorates a function to be called async on the loop thread"""
@wraps(func)
def wrapper(self, *args, **kw):
"""Wraps instance method to be called on loop thread"""
def call():
"""Calls function on loop thread"""
try:
func(self... | [
"def",
"call_async",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"\"\"\"Wraps instance method to be called on loop thread\"\"\"",
"def",
"call",
"(",
")",
":",
"\"\"... | Decorates a function to be called async on the loop thread | [
"Decorates",
"a",
"function",
"to",
"be",
"called",
"async",
"on",
"the",
"loop",
"thread"
] | train | https://github.com/volafiled/python-volapi/blob/5f0bc03dbde703264ac6ed494e2050761f688a3e/volapi/auxo.py#L33-L51 |
volafiled/python-volapi | volapi/auxo.py | call_sync | def call_sync(func):
"""Decorates a function to be called sync on the loop thread"""
@wraps(func)
def wrapper(self, *args, **kw):
"""Wraps instance method to be called on loop thread"""
# Just return when already on the event thread
if self.thread.ident == get_ident():
... | python | def call_sync(func):
"""Decorates a function to be called sync on the loop thread"""
@wraps(func)
def wrapper(self, *args, **kw):
"""Wraps instance method to be called on loop thread"""
# Just return when already on the event thread
if self.thread.ident == get_ident():
... | [
"def",
"call_sync",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"\"\"\"Wraps instance method to be called on loop thread\"\"\"",
"# Just return when already on the event threa... | Decorates a function to be called sync on the loop thread | [
"Decorates",
"a",
"function",
"to",
"be",
"called",
"sync",
"on",
"the",
"loop",
"thread"
] | train | https://github.com/volafiled/python-volapi/blob/5f0bc03dbde703264ac6ed494e2050761f688a3e/volapi/auxo.py#L54-L85 |
volafiled/python-volapi | volapi/auxo.py | Awakener.target | def target(self):
"""Thread routine"""
while self.event.wait():
self.event.clear()
while True:
with self.lock:
if not self.count:
break
self.count -= 1
with self.condition:
... | python | def target(self):
"""Thread routine"""
while self.event.wait():
self.event.clear()
while True:
with self.lock:
if not self.count:
break
self.count -= 1
with self.condition:
... | [
"def",
"target",
"(",
"self",
")",
":",
"while",
"self",
".",
"event",
".",
"wait",
"(",
")",
":",
"self",
".",
"event",
".",
"clear",
"(",
")",
"while",
"True",
":",
"with",
"self",
".",
"lock",
":",
"if",
"not",
"self",
".",
"count",
":",
"br... | Thread routine | [
"Thread",
"routine"
] | train | https://github.com/volafiled/python-volapi/blob/5f0bc03dbde703264ac6ed494e2050761f688a3e/volapi/auxo.py#L113-L123 |
volafiled/python-volapi | volapi/auxo.py | ListenerArbitrator._loop | def _loop(self, barrier):
"""Actual thread"""
if sys.platform != "win32":
self.loop = asyncio.new_event_loop()
else:
self.loop = asyncio.ProactorEventLoop()
asyncio.set_event_loop(self.loop)
barrier.wait()
try:
self.loop.run_forever()
... | python | def _loop(self, barrier):
"""Actual thread"""
if sys.platform != "win32":
self.loop = asyncio.new_event_loop()
else:
self.loop = asyncio.ProactorEventLoop()
asyncio.set_event_loop(self.loop)
barrier.wait()
try:
self.loop.run_forever()
... | [
"def",
"_loop",
"(",
"self",
",",
"barrier",
")",
":",
"if",
"sys",
".",
"platform",
"!=",
"\"win32\"",
":",
"self",
".",
"loop",
"=",
"asyncio",
".",
"new_event_loop",
"(",
")",
"else",
":",
"self",
".",
"loop",
"=",
"asyncio",
".",
"ProactorEventLoop... | Actual thread | [
"Actual",
"thread"
] | train | https://github.com/volafiled/python-volapi/blob/5f0bc03dbde703264ac6ed494e2050761f688a3e/volapi/auxo.py#L138-L150 |
volafiled/python-volapi | volapi/auxo.py | ListenerArbitrator.create_connection | def create_connection(self, room, ws_url, agent, cookies):
"""Creates a new connection"""
urlparts = urlsplit(ws_url)
req = Request("GET", ws_url)
cookies = get_cookie_header(cookies, req)
if cookies:
headers = dict(Cookie=cookies)
else:
headers =... | python | def create_connection(self, room, ws_url, agent, cookies):
"""Creates a new connection"""
urlparts = urlsplit(ws_url)
req = Request("GET", ws_url)
cookies = get_cookie_header(cookies, req)
if cookies:
headers = dict(Cookie=cookies)
else:
headers =... | [
"def",
"create_connection",
"(",
"self",
",",
"room",
",",
"ws_url",
",",
"agent",
",",
"cookies",
")",
":",
"urlparts",
"=",
"urlsplit",
"(",
"ws_url",
")",
"req",
"=",
"Request",
"(",
"\"GET\"",
",",
"ws_url",
")",
"cookies",
"=",
"get_cookie_header",
... | Creates a new connection | [
"Creates",
"a",
"new",
"connection"
] | train | https://github.com/volafiled/python-volapi/blob/5f0bc03dbde703264ac6ed494e2050761f688a3e/volapi/auxo.py#L153-L173 |
volafiled/python-volapi | volapi/auxo.py | ListenerArbitrator.__send_message | def __send_message(self, proto, payload):
# pylint: disable=no-self-use
"""Sends a message"""
try:
if not isinstance(payload, bytes):
payload = payload.encode("utf-8")
if not proto.connected:
raise IOError("not connected")
prot... | python | def __send_message(self, proto, payload):
# pylint: disable=no-self-use
"""Sends a message"""
try:
if not isinstance(payload, bytes):
payload = payload.encode("utf-8")
if not proto.connected:
raise IOError("not connected")
prot... | [
"def",
"__send_message",
"(",
"self",
",",
"proto",
",",
"payload",
")",
":",
"# pylint: disable=no-self-use",
"try",
":",
"if",
"not",
"isinstance",
"(",
"payload",
",",
"bytes",
")",
":",
"payload",
"=",
"payload",
".",
"encode",
"(",
"\"utf-8\"",
")",
"... | Sends a message | [
"Sends",
"a",
"message"
] | train | https://github.com/volafiled/python-volapi/blob/5f0bc03dbde703264ac6ed494e2050761f688a3e/volapi/auxo.py#L175-L188 |
volafiled/python-volapi | volapi/auxo.py | ListenerArbitrator.close | def close(self, proto):
# pylint: disable=no-self-use
"""Closes a connection"""
try:
proto.sendClose()
except Exception as ex:
logger.exception("Failed to send close")
proto.reraise(ex) | python | def close(self, proto):
# pylint: disable=no-self-use
"""Closes a connection"""
try:
proto.sendClose()
except Exception as ex:
logger.exception("Failed to send close")
proto.reraise(ex) | [
"def",
"close",
"(",
"self",
",",
"proto",
")",
":",
"# pylint: disable=no-self-use",
"try",
":",
"proto",
".",
"sendClose",
"(",
")",
"except",
"Exception",
"as",
"ex",
":",
"logger",
".",
"exception",
"(",
"\"Failed to send close\"",
")",
"proto",
".",
"re... | Closes a connection | [
"Closes",
"a",
"connection"
] | train | https://github.com/volafiled/python-volapi/blob/5f0bc03dbde703264ac6ed494e2050761f688a3e/volapi/auxo.py#L199-L207 |
volafiled/python-volapi | volapi/auxo.py | Listeners.process | def process(self):
"""Process queue for these listeners. Only the items with type that
matches """
with self.lock, self.enlock:
queue = copy(self.queue)
self.queue.clear()
callbacks = copy(self.callbacks)
with self.lock:
rm_cb = False
... | python | def process(self):
"""Process queue for these listeners. Only the items with type that
matches """
with self.lock, self.enlock:
queue = copy(self.queue)
self.queue.clear()
callbacks = copy(self.callbacks)
with self.lock:
rm_cb = False
... | [
"def",
"process",
"(",
"self",
")",
":",
"with",
"self",
".",
"lock",
",",
"self",
".",
"enlock",
":",
"queue",
"=",
"copy",
"(",
"self",
".",
"queue",
")",
"self",
".",
"queue",
".",
"clear",
"(",
")",
"callbacks",
"=",
"copy",
"(",
"self",
".",... | Process queue for these listeners. Only the items with type that
matches | [
"Process",
"queue",
"for",
"these",
"listeners",
".",
"Only",
"the",
"items",
"with",
"type",
"that",
"matches"
] | train | https://github.com/volafiled/python-volapi/blob/5f0bc03dbde703264ac6ed494e2050761f688a3e/volapi/auxo.py#L228-L254 |
volafiled/python-volapi | volapi/auxo.py | Listeners.add | def add(self, callback_type, callback):
"""Add a new listener"""
with self.lock:
self.callbacks[callback_type].append(callback) | python | def add(self, callback_type, callback):
"""Add a new listener"""
with self.lock:
self.callbacks[callback_type].append(callback) | [
"def",
"add",
"(",
"self",
",",
"callback_type",
",",
"callback",
")",
":",
"with",
"self",
".",
"lock",
":",
"self",
".",
"callbacks",
"[",
"callback_type",
"]",
".",
"append",
"(",
"callback",
")"
] | Add a new listener | [
"Add",
"a",
"new",
"listener"
] | train | https://github.com/volafiled/python-volapi/blob/5f0bc03dbde703264ac6ed494e2050761f688a3e/volapi/auxo.py#L256-L260 |
volafiled/python-volapi | volapi/auxo.py | Listeners.enqueue | def enqueue(self, item_type, item):
"""Queue a new data item, make item iterable"""
with self.enlock:
self.queue[item_type].append(item) | python | def enqueue(self, item_type, item):
"""Queue a new data item, make item iterable"""
with self.enlock:
self.queue[item_type].append(item) | [
"def",
"enqueue",
"(",
"self",
",",
"item_type",
",",
"item",
")",
":",
"with",
"self",
".",
"enlock",
":",
"self",
".",
"queue",
"[",
"item_type",
"]",
".",
"append",
"(",
"item",
")"
] | Queue a new data item, make item iterable | [
"Queue",
"a",
"new",
"data",
"item",
"make",
"item",
"iterable"
] | train | https://github.com/volafiled/python-volapi/blob/5f0bc03dbde703264ac6ed494e2050761f688a3e/volapi/auxo.py#L262-L266 |
guaix-ucm/pyemir | emirdrp/processing/wavecal/slitlet2darc.py | Slitlet2dArc.extract_slitlet2d | def extract_slitlet2d(self, image_2k2k):
"""Extract slitlet 2d image from image with original EMIR dimensions.
Parameters
----------
image_2k2k : numpy array
Original image (dimensions EMIR_NAXIS1 * EMIR_NAXIS2)
Returns
-------
slitlet2d : numpy arra... | python | def extract_slitlet2d(self, image_2k2k):
"""Extract slitlet 2d image from image with original EMIR dimensions.
Parameters
----------
image_2k2k : numpy array
Original image (dimensions EMIR_NAXIS1 * EMIR_NAXIS2)
Returns
-------
slitlet2d : numpy arra... | [
"def",
"extract_slitlet2d",
"(",
"self",
",",
"image_2k2k",
")",
":",
"# protections",
"naxis2",
",",
"naxis1",
"=",
"image_2k2k",
".",
"shape",
"if",
"naxis1",
"!=",
"EMIR_NAXIS1",
":",
"raise",
"ValueError",
"(",
"'Unexpected naxis1'",
")",
"if",
"naxis2",
"... | Extract slitlet 2d image from image with original EMIR dimensions.
Parameters
----------
image_2k2k : numpy array
Original image (dimensions EMIR_NAXIS1 * EMIR_NAXIS2)
Returns
-------
slitlet2d : numpy array
Image corresponding to the slitlet reg... | [
"Extract",
"slitlet",
"2d",
"image",
"from",
"image",
"with",
"original",
"EMIR",
"dimensions",
"."
] | train | https://github.com/guaix-ucm/pyemir/blob/fef6bbabcb13f80123cafd1800a0f508a3c21702/emirdrp/processing/wavecal/slitlet2darc.py#L524-L576 |
guaix-ucm/pyemir | emirdrp/processing/wavecal/slitlet2darc.py | Slitlet2dArc.locate_unknown_arc_lines | def locate_unknown_arc_lines(self, slitlet2d,
times_sigma_threshold=15,
minimum_threshold=None,
delta_x_max=30,
delta_y_min=30,
min_dist_from_middle=15):
... | python | def locate_unknown_arc_lines(self, slitlet2d,
times_sigma_threshold=15,
minimum_threshold=None,
delta_x_max=30,
delta_y_min=30,
min_dist_from_middle=15):
... | [
"def",
"locate_unknown_arc_lines",
"(",
"self",
",",
"slitlet2d",
",",
"times_sigma_threshold",
"=",
"15",
",",
"minimum_threshold",
"=",
"None",
",",
"delta_x_max",
"=",
"30",
",",
"delta_y_min",
"=",
"30",
",",
"min_dist_from_middle",
"=",
"15",
")",
":",
"#... | Determine the location of known arc lines in slitlet.
Parameters
----------
slitlet2d : numpy array
Image containing the 2d slitlet image.
times_sigma_threshold : float
Times (robust) sigma above the median of the image to look
for arc lines.
... | [
"Determine",
"the",
"location",
"of",
"known",
"arc",
"lines",
"in",
"slitlet",
"."
] | train | https://github.com/guaix-ucm/pyemir/blob/fef6bbabcb13f80123cafd1800a0f508a3c21702/emirdrp/processing/wavecal/slitlet2darc.py#L578-L854 |
guaix-ucm/pyemir | emirdrp/processing/wavecal/slitlet2darc.py | Slitlet2dArc.xy_spectrail_arc_intersections | def xy_spectrail_arc_intersections(self, slitlet2d=None):
"""Compute intersection points of spectrum trails with arc lines.
The member list_arc_lines is updated with new keyword:keyval
values for each arc line.
Parameters
----------
slitlet2d : numpy array
S... | python | def xy_spectrail_arc_intersections(self, slitlet2d=None):
"""Compute intersection points of spectrum trails with arc lines.
The member list_arc_lines is updated with new keyword:keyval
values for each arc line.
Parameters
----------
slitlet2d : numpy array
S... | [
"def",
"xy_spectrail_arc_intersections",
"(",
"self",
",",
"slitlet2d",
"=",
"None",
")",
":",
"# protections",
"if",
"self",
".",
"list_arc_lines",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Arc lines not sought\"",
")",
"number_spectrum_trails",
"=",
"len",... | Compute intersection points of spectrum trails with arc lines.
The member list_arc_lines is updated with new keyword:keyval
values for each arc line.
Parameters
----------
slitlet2d : numpy array
Slitlet image to be displayed with the computed boundaries
... | [
"Compute",
"intersection",
"points",
"of",
"spectrum",
"trails",
"with",
"arc",
"lines",
"."
] | train | https://github.com/guaix-ucm/pyemir/blob/fef6bbabcb13f80123cafd1800a0f508a3c21702/emirdrp/processing/wavecal/slitlet2darc.py#L856-L948 |
guaix-ucm/pyemir | emirdrp/processing/wavecal/slitlet2darc.py | Slitlet2dArc.estimate_tt_to_rectify | def estimate_tt_to_rectify(self, order, slitlet2d=None):
"""Estimate the polynomial transformation to rectify the image.
Parameters
----------
order : int
Order of the polynomial transformation.
slitlet2d : numpy array
Slitlet image to be displayed with t... | python | def estimate_tt_to_rectify(self, order, slitlet2d=None):
"""Estimate the polynomial transformation to rectify the image.
Parameters
----------
order : int
Order of the polynomial transformation.
slitlet2d : numpy array
Slitlet image to be displayed with t... | [
"def",
"estimate_tt_to_rectify",
"(",
"self",
",",
"order",
",",
"slitlet2d",
"=",
"None",
")",
":",
"# protections",
"if",
"self",
".",
"x_inter_orig",
"is",
"None",
"or",
"self",
".",
"y_inter_orig",
"is",
"None",
"or",
"self",
".",
"x_inter_rect",
"is",
... | Estimate the polynomial transformation to rectify the image.
Parameters
----------
order : int
Order of the polynomial transformation.
slitlet2d : numpy array
Slitlet image to be displayed with the computed boundaries
and intersecting points overplott... | [
"Estimate",
"the",
"polynomial",
"transformation",
"to",
"rectify",
"the",
"image",
"."
] | train | https://github.com/guaix-ucm/pyemir/blob/fef6bbabcb13f80123cafd1800a0f508a3c21702/emirdrp/processing/wavecal/slitlet2darc.py#L950-L1042 |
guaix-ucm/pyemir | emirdrp/processing/wavecal/slitlet2darc.py | Slitlet2dArc.rectify | def rectify(self, slitlet2d, resampling, transformation, inverse=False):
"""Rectify slitlet using computed transformation.
Parameters
----------
slitlet2d : numpy array
Image containing the 2d slitlet image.
resampling : int
1: nearest neighbour, 2: flux ... | python | def rectify(self, slitlet2d, resampling, transformation, inverse=False):
"""Rectify slitlet using computed transformation.
Parameters
----------
slitlet2d : numpy array
Image containing the 2d slitlet image.
resampling : int
1: nearest neighbour, 2: flux ... | [
"def",
"rectify",
"(",
"self",
",",
"slitlet2d",
",",
"resampling",
",",
"transformation",
",",
"inverse",
"=",
"False",
")",
":",
"if",
"resampling",
"not",
"in",
"[",
"1",
",",
"2",
"]",
":",
"raise",
"ValueError",
"(",
"\"Unexpected resampling value=\"",
... | Rectify slitlet using computed transformation.
Parameters
----------
slitlet2d : numpy array
Image containing the 2d slitlet image.
resampling : int
1: nearest neighbour, 2: flux preserving interpolation.
transformation : int
1: initial, 2: mo... | [
"Rectify",
"slitlet",
"using",
"computed",
"transformation",
"."
] | train | https://github.com/guaix-ucm/pyemir/blob/fef6bbabcb13f80123cafd1800a0f508a3c21702/emirdrp/processing/wavecal/slitlet2darc.py#L1044-L1145 |
guaix-ucm/pyemir | emirdrp/processing/wavecal/slitlet2darc.py | Slitlet2dArc.median_spectrum_from_rectified_image | def median_spectrum_from_rectified_image(self, slitlet2d_rect,
sigma_gaussian_filtering=0,
nwinwidth_initial=5,
nwinwidth_refined=7,
times_s... | python | def median_spectrum_from_rectified_image(self, slitlet2d_rect,
sigma_gaussian_filtering=0,
nwinwidth_initial=5,
nwinwidth_refined=7,
times_s... | [
"def",
"median_spectrum_from_rectified_image",
"(",
"self",
",",
"slitlet2d_rect",
",",
"sigma_gaussian_filtering",
"=",
"0",
",",
"nwinwidth_initial",
"=",
"5",
",",
"nwinwidth_refined",
"=",
"7",
",",
"times_sigma_threshold",
"=",
"5",
",",
"minimum_threshold",
"=",... | Median spectrum and line peaks from rectified image.
In order to avoid the line ghosts, the line peaks are identified
independently in the upper and lower halves of the rectified
image. The final peaks correspond to lines that appear in both
spectra.
Parameters
--------... | [
"Median",
"spectrum",
"and",
"line",
"peaks",
"from",
"rectified",
"image",
"."
] | train | https://github.com/guaix-ucm/pyemir/blob/fef6bbabcb13f80123cafd1800a0f508a3c21702/emirdrp/processing/wavecal/slitlet2darc.py#L1147-L1347 |
guaix-ucm/pyemir | emirdrp/recipes/image/shared.py | intersection | def intersection(a, b, scale=1):
'''Intersection between two segments.'''
try:
a1, a2 = a
except TypeError:
a1 = a.start
a2 = a.stop
try:
b1, b2 = b
except TypeError:
b1 = b.start
b2 = b.stop
if a2 <= b1:
return None
if a1 >= b2:
... | python | def intersection(a, b, scale=1):
'''Intersection between two segments.'''
try:
a1, a2 = a
except TypeError:
a1 = a.start
a2 = a.stop
try:
b1, b2 = b
except TypeError:
b1 = b.start
b2 = b.stop
if a2 <= b1:
return None
if a1 >= b2:
... | [
"def",
"intersection",
"(",
"a",
",",
"b",
",",
"scale",
"=",
"1",
")",
":",
"try",
":",
"a1",
",",
"a2",
"=",
"a",
"except",
"TypeError",
":",
"a1",
"=",
"a",
".",
"start",
"a2",
"=",
"a",
".",
"stop",
"try",
":",
"b1",
",",
"b2",
"=",
"b"... | Intersection between two segments. | [
"Intersection",
"between",
"two",
"segments",
"."
] | train | https://github.com/guaix-ucm/pyemir/blob/fef6bbabcb13f80123cafd1800a0f508a3c21702/emirdrp/recipes/image/shared.py#L67-L97 |
guaix-ucm/pyemir | emirdrp/recipes/image/shared.py | clip_slices | def clip_slices(r, region, scale=1):
'''Intersect slices with a region.'''
t = []
for ch in r:
a1 = intersection(ch[0], region[0], scale=scale)
if a1 is None:
continue
a2 = intersection(ch[1], region[1], scale=scale)
if a2 is None:
continue
t.... | python | def clip_slices(r, region, scale=1):
'''Intersect slices with a region.'''
t = []
for ch in r:
a1 = intersection(ch[0], region[0], scale=scale)
if a1 is None:
continue
a2 = intersection(ch[1], region[1], scale=scale)
if a2 is None:
continue
t.... | [
"def",
"clip_slices",
"(",
"r",
",",
"region",
",",
"scale",
"=",
"1",
")",
":",
"t",
"=",
"[",
"]",
"for",
"ch",
"in",
"r",
":",
"a1",
"=",
"intersection",
"(",
"ch",
"[",
"0",
"]",
",",
"region",
"[",
"0",
"]",
",",
"scale",
"=",
"scale",
... | Intersect slices with a region. | [
"Intersect",
"slices",
"with",
"a",
"region",
"."
] | train | https://github.com/guaix-ucm/pyemir/blob/fef6bbabcb13f80123cafd1800a0f508a3c21702/emirdrp/recipes/image/shared.py#L100-L113 |
guaix-ucm/pyemir | emirdrp/recipes/image/join.py | JoinDitheredImagesRecipe.set_base_headers | def set_base_headers(self, hdr):
"""Set metadata in FITS headers."""
hdr = super(JoinDitheredImagesRecipe, self).set_base_headers(hdr)
hdr['IMGOBBL'] = 0
hdr['OBSMODE'] = 'DITHERED_IMAGE'
return hdr | python | def set_base_headers(self, hdr):
"""Set metadata in FITS headers."""
hdr = super(JoinDitheredImagesRecipe, self).set_base_headers(hdr)
hdr['IMGOBBL'] = 0
hdr['OBSMODE'] = 'DITHERED_IMAGE'
return hdr | [
"def",
"set_base_headers",
"(",
"self",
",",
"hdr",
")",
":",
"hdr",
"=",
"super",
"(",
"JoinDitheredImagesRecipe",
",",
"self",
")",
".",
"set_base_headers",
"(",
"hdr",
")",
"hdr",
"[",
"'IMGOBBL'",
"]",
"=",
"0",
"hdr",
"[",
"'OBSMODE'",
"]",
"=",
"... | Set metadata in FITS headers. | [
"Set",
"metadata",
"in",
"FITS",
"headers",
"."
] | train | https://github.com/guaix-ucm/pyemir/blob/fef6bbabcb13f80123cafd1800a0f508a3c21702/emirdrp/recipes/image/join.py#L338-L343 |
BeyondTheClouds/enoslib | enoslib/api.py | _load_defaults | def _load_defaults(inventory_path=None, roles=None, extra_vars=None, tags=None,
basedir=False):
"""Load common defaults data structures.
For factorization purpose."""
extra_vars = extra_vars or {}
tags = tags or []
loader = DataLoader()
if basedir:
loader.set_basedir... | python | def _load_defaults(inventory_path=None, roles=None, extra_vars=None, tags=None,
basedir=False):
"""Load common defaults data structures.
For factorization purpose."""
extra_vars = extra_vars or {}
tags = tags or []
loader = DataLoader()
if basedir:
loader.set_basedir... | [
"def",
"_load_defaults",
"(",
"inventory_path",
"=",
"None",
",",
"roles",
"=",
"None",
",",
"extra_vars",
"=",
"None",
",",
"tags",
"=",
"None",
",",
"basedir",
"=",
"False",
")",
":",
"extra_vars",
"=",
"extra_vars",
"or",
"{",
"}",
"tags",
"=",
"tag... | Load common defaults data structures.
For factorization purpose. | [
"Load",
"common",
"defaults",
"data",
"structures",
"."
] | train | https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/api.py#L45-L96 |
BeyondTheClouds/enoslib | enoslib/api.py | run_play | def run_play(play_source, inventory_path=None, roles=None,
extra_vars=None, on_error_continue=False):
"""Run a play.
Args:
pattern_hosts (str): pattern to describe ansible hosts to target.
see https://docs.ansible.com/ansible/latest/intro_patterns.html
play_source (dict... | python | def run_play(play_source, inventory_path=None, roles=None,
extra_vars=None, on_error_continue=False):
"""Run a play.
Args:
pattern_hosts (str): pattern to describe ansible hosts to target.
see https://docs.ansible.com/ansible/latest/intro_patterns.html
play_source (dict... | [
"def",
"run_play",
"(",
"play_source",
",",
"inventory_path",
"=",
"None",
",",
"roles",
"=",
"None",
",",
"extra_vars",
"=",
"None",
",",
"on_error_continue",
"=",
"False",
")",
":",
"# NOTE(msimonin): inventory could be infered from a host list (maybe)",
"results",
... | Run a play.
Args:
pattern_hosts (str): pattern to describe ansible hosts to target.
see https://docs.ansible.com/ansible/latest/intro_patterns.html
play_source (dict): ansible task
inventory_path (str): inventory to use
extra_vars (dict): extra_vars to use
on_err... | [
"Run",
"a",
"play",
"."
] | train | https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/api.py#L135-L202 |
BeyondTheClouds/enoslib | enoslib/api.py | run_command | def run_command(pattern_hosts, command, inventory_path=None, roles=None,
extra_vars=None,
on_error_continue=False):
"""Run a shell command on some remote hosts.
Args:
pattern_hosts (str): pattern to describe ansible hosts to target.
see https://docs.ansible.c... | python | def run_command(pattern_hosts, command, inventory_path=None, roles=None,
extra_vars=None,
on_error_continue=False):
"""Run a shell command on some remote hosts.
Args:
pattern_hosts (str): pattern to describe ansible hosts to target.
see https://docs.ansible.c... | [
"def",
"run_command",
"(",
"pattern_hosts",
",",
"command",
",",
"inventory_path",
"=",
"None",
",",
"roles",
"=",
"None",
",",
"extra_vars",
"=",
"None",
",",
"on_error_continue",
"=",
"False",
")",
":",
"def",
"filter_results",
"(",
"results",
",",
"status... | Run a shell command on some remote hosts.
Args:
pattern_hosts (str): pattern to describe ansible hosts to target.
see https://docs.ansible.com/ansible/latest/intro_patterns.html
command (str): the command to run
inventory_path (str): inventory to use
extra_vars (dict): e... | [
"Run",
"a",
"shell",
"command",
"on",
"some",
"remote",
"hosts",
"."
] | train | https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/api.py#L306-L390 |
BeyondTheClouds/enoslib | enoslib/api.py | run_ansible | def run_ansible(playbooks, inventory_path=None, roles=None, extra_vars=None,
tags=None, on_error_continue=False, basedir='.'):
"""Run Ansible.
Args:
playbooks (list): list of paths to the playbooks to run
inventory_path (str): path to the hosts file (inventory)
extra_var (dict):... | python | def run_ansible(playbooks, inventory_path=None, roles=None, extra_vars=None,
tags=None, on_error_continue=False, basedir='.'):
"""Run Ansible.
Args:
playbooks (list): list of paths to the playbooks to run
inventory_path (str): path to the hosts file (inventory)
extra_var (dict):... | [
"def",
"run_ansible",
"(",
"playbooks",
",",
"inventory_path",
"=",
"None",
",",
"roles",
"=",
"None",
",",
"extra_vars",
"=",
"None",
",",
"tags",
"=",
"None",
",",
"on_error_continue",
"=",
"False",
",",
"basedir",
"=",
"'.'",
")",
":",
"inventory",
",... | Run Ansible.
Args:
playbooks (list): list of paths to the playbooks to run
inventory_path (str): path to the hosts file (inventory)
extra_var (dict): extra vars to pass
tags (list): list of tags to run
on_error_continue(bool): Don't throw any exception in case a host is
... | [
"Run",
"Ansible",
"."
] | train | https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/api.py#L393-L456 |
BeyondTheClouds/enoslib | enoslib/api.py | discover_networks | def discover_networks(roles, networks, fake_interfaces=None,
fake_networks=None):
"""Checks the network interfaces on the nodes.
This enables to auto-discover the mapping interface name <-> network role.
Beware, this has a side effect on each Host in roles.
Args:
roles (dic... | python | def discover_networks(roles, networks, fake_interfaces=None,
fake_networks=None):
"""Checks the network interfaces on the nodes.
This enables to auto-discover the mapping interface name <-> network role.
Beware, this has a side effect on each Host in roles.
Args:
roles (dic... | [
"def",
"discover_networks",
"(",
"roles",
",",
"networks",
",",
"fake_interfaces",
"=",
"None",
",",
"fake_networks",
"=",
"None",
")",
":",
"def",
"get_devices",
"(",
"facts",
")",
":",
"\"\"\"Extract the network devices information from the facts.\"\"\"",
"devices",
... | Checks the network interfaces on the nodes.
This enables to auto-discover the mapping interface name <-> network role.
Beware, this has a side effect on each Host in roles.
Args:
roles (dict): role->hosts mapping as returned by
:py:meth:`enoslib.infra.provider.Provider.init`
ne... | [
"Checks",
"the",
"network",
"interfaces",
"on",
"the",
"nodes",
"."
] | train | https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/api.py#L459-L532 |
BeyondTheClouds/enoslib | enoslib/api.py | generate_inventory | def generate_inventory(roles, networks, inventory_path, check_networks=False,
fake_interfaces=None, fake_networks=None):
"""Generate an inventory file in the ini format.
The inventory is generated using the ``roles`` in the ``ini`` format. If
``check_network == True``, the function ... | python | def generate_inventory(roles, networks, inventory_path, check_networks=False,
fake_interfaces=None, fake_networks=None):
"""Generate an inventory file in the ini format.
The inventory is generated using the ``roles`` in the ``ini`` format. If
``check_network == True``, the function ... | [
"def",
"generate_inventory",
"(",
"roles",
",",
"networks",
",",
"inventory_path",
",",
"check_networks",
"=",
"False",
",",
"fake_interfaces",
"=",
"None",
",",
"fake_networks",
"=",
"None",
")",
":",
"with",
"open",
"(",
"inventory_path",
",",
"\"w\"",
")",
... | Generate an inventory file in the ini format.
The inventory is generated using the ``roles`` in the ``ini`` format. If
``check_network == True``, the function will try to discover which networks
interfaces are available and map them to one network of the ``networks``
parameters. Note that this auto-d... | [
"Generate",
"an",
"inventory",
"file",
"in",
"the",
"ini",
"format",
"."
] | train | https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/api.py#L535-L571 |
BeyondTheClouds/enoslib | enoslib/api.py | emulate_network | def emulate_network(network_constraints,
roles=None,
inventory_path=None,
extra_vars=None):
"""Emulate network links.
Read ``network_constraints`` and apply ``tc`` rules on all the nodes.
Constraints are applied between groups of machines. Theses ... | python | def emulate_network(network_constraints,
roles=None,
inventory_path=None,
extra_vars=None):
"""Emulate network links.
Read ``network_constraints`` and apply ``tc`` rules on all the nodes.
Constraints are applied between groups of machines. Theses ... | [
"def",
"emulate_network",
"(",
"network_constraints",
",",
"roles",
"=",
"None",
",",
"inventory_path",
"=",
"None",
",",
"extra_vars",
"=",
"None",
")",
":",
"# 1) Retrieve the list of ips for all nodes (Ansible)",
"# 2) Build all the constraints (Python)",
"# {source:src... | Emulate network links.
Read ``network_constraints`` and apply ``tc`` rules on all the nodes.
Constraints are applied between groups of machines. Theses groups are
described in the ``network_constraints`` variable and must be found in the
inventory file. The newtwork constraints support ``delay``, ``rat... | [
"Emulate",
"network",
"links",
"."
] | train | https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/api.py#L574-L717 |
BeyondTheClouds/enoslib | enoslib/api.py | validate_network | def validate_network(roles=None,
inventory_path=None,
output_dir=None,
extra_vars=None):
"""Validate the network parameters (latency, bandwidth ...)
Performs flent, ping tests to validate the constraints set by
:py:func:`emulate_network`. Repor... | python | def validate_network(roles=None,
inventory_path=None,
output_dir=None,
extra_vars=None):
"""Validate the network parameters (latency, bandwidth ...)
Performs flent, ping tests to validate the constraints set by
:py:func:`emulate_network`. Repor... | [
"def",
"validate_network",
"(",
"roles",
"=",
"None",
",",
"inventory_path",
"=",
"None",
",",
"output_dir",
"=",
"None",
",",
"extra_vars",
"=",
"None",
")",
":",
"logger",
".",
"debug",
"(",
"'Checking the constraints'",
")",
"if",
"not",
"output_dir",
":"... | Validate the network parameters (latency, bandwidth ...)
Performs flent, ping tests to validate the constraints set by
:py:func:`emulate_network`. Reports are available in the tmp directory used
by enos.
Args:
roles (dict): role->hosts mapping as returned by
:py:meth:`enoslib.infra... | [
"Validate",
"the",
"network",
"parameters",
"(",
"latency",
"bandwidth",
"...",
")"
] | train | https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/api.py#L720-L754 |
BeyondTheClouds/enoslib | enoslib/api.py | reset_network | def reset_network(roles, extra_vars=None):
"""Reset the network constraints (latency, bandwidth ...)
Remove any filter that have been applied to shape the traffic.
Args:
roles (dict): role->hosts mapping as returned by
:py:meth:`enoslib.infra.provider.Provider.init`
inventory (... | python | def reset_network(roles, extra_vars=None):
"""Reset the network constraints (latency, bandwidth ...)
Remove any filter that have been applied to shape the traffic.
Args:
roles (dict): role->hosts mapping as returned by
:py:meth:`enoslib.infra.provider.Provider.init`
inventory (... | [
"def",
"reset_network",
"(",
"roles",
",",
"extra_vars",
"=",
"None",
")",
":",
"logger",
".",
"debug",
"(",
"'Reset the constraints'",
")",
"if",
"not",
"extra_vars",
":",
"extra_vars",
"=",
"{",
"}",
"tmpdir",
"=",
"os",
".",
"path",
".",
"join",
"(",
... | Reset the network constraints (latency, bandwidth ...)
Remove any filter that have been applied to shape the traffic.
Args:
roles (dict): role->hosts mapping as returned by
:py:meth:`enoslib.infra.provider.Provider.init`
inventory (str): path to the inventory | [
"Reset",
"the",
"network",
"constraints",
"(",
"latency",
"bandwidth",
"...",
")"
] | train | https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/api.py#L757-L779 |
BeyondTheClouds/enoslib | enoslib/api.py | wait_ssh | def wait_ssh(roles, retries=100, interval=30):
"""Wait for all the machines to be ssh-reachable
Let ansible initiates a communication and retries if needed.
Args:
inventory (string): path to the inventoy file to test
retries (int): Number of time we'll be retrying an SSH connection
... | python | def wait_ssh(roles, retries=100, interval=30):
"""Wait for all the machines to be ssh-reachable
Let ansible initiates a communication and retries if needed.
Args:
inventory (string): path to the inventoy file to test
retries (int): Number of time we'll be retrying an SSH connection
... | [
"def",
"wait_ssh",
"(",
"roles",
",",
"retries",
"=",
"100",
",",
"interval",
"=",
"30",
")",
":",
"utils_playbook",
"=",
"os",
".",
"path",
".",
"join",
"(",
"ANSIBLE_DIR",
",",
"'utils.yml'",
")",
"options",
"=",
"{",
"'enos_action'",
":",
"'ping'",
... | Wait for all the machines to be ssh-reachable
Let ansible initiates a communication and retries if needed.
Args:
inventory (string): path to the inventoy file to test
retries (int): Number of time we'll be retrying an SSH connection
interval (int): Interval to wait in seconds between t... | [
"Wait",
"for",
"all",
"the",
"machines",
"to",
"be",
"ssh",
"-",
"reachable"
] | train | https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/api.py#L782-L807 |
BeyondTheClouds/enoslib | enoslib/api.py | expand_groups | def expand_groups(grp):
"""Expand group names.
Args:
grp (string): group names to expand
Returns:
list of groups
Examples:
* grp[1-3] will be expanded to [grp1, grp2, grp3]
* grp1 will be expanded to [grp1]
"""
p = re.compile(r"(?P<name>.+)\[(?P<start>\d+)-(?P... | python | def expand_groups(grp):
"""Expand group names.
Args:
grp (string): group names to expand
Returns:
list of groups
Examples:
* grp[1-3] will be expanded to [grp1, grp2, grp3]
* grp1 will be expanded to [grp1]
"""
p = re.compile(r"(?P<name>.+)\[(?P<start>\d+)-(?P... | [
"def",
"expand_groups",
"(",
"grp",
")",
":",
"p",
"=",
"re",
".",
"compile",
"(",
"r\"(?P<name>.+)\\[(?P<start>\\d+)-(?P<end>\\d+)\\]\"",
")",
"m",
"=",
"p",
".",
"match",
"(",
"grp",
")",
"if",
"m",
"is",
"not",
"None",
":",
"s",
"=",
"int",
"(",
"m"... | Expand group names.
Args:
grp (string): group names to expand
Returns:
list of groups
Examples:
* grp[1-3] will be expanded to [grp1, grp2, grp3]
* grp1 will be expanded to [grp1] | [
"Expand",
"group",
"names",
"."
] | train | https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/api.py#L810-L832 |
BeyondTheClouds/enoslib | enoslib/api.py | _expand_description | def _expand_description(desc):
"""Expand the description given the group names/patterns
e.g:
{src: grp[1-3], dst: grp[4-6] ...} will generate 9 descriptions
"""
srcs = expand_groups(desc['src'])
dsts = expand_groups(desc['dst'])
descs = []
for src in srcs:
for dst in dsts:
... | python | def _expand_description(desc):
"""Expand the description given the group names/patterns
e.g:
{src: grp[1-3], dst: grp[4-6] ...} will generate 9 descriptions
"""
srcs = expand_groups(desc['src'])
dsts = expand_groups(desc['dst'])
descs = []
for src in srcs:
for dst in dsts:
... | [
"def",
"_expand_description",
"(",
"desc",
")",
":",
"srcs",
"=",
"expand_groups",
"(",
"desc",
"[",
"'src'",
"]",
")",
"dsts",
"=",
"expand_groups",
"(",
"desc",
"[",
"'dst'",
"]",
")",
"descs",
"=",
"[",
"]",
"for",
"src",
"in",
"srcs",
":",
"for",... | Expand the description given the group names/patterns
e.g:
{src: grp[1-3], dst: grp[4-6] ...} will generate 9 descriptions | [
"Expand",
"the",
"description",
"given",
"the",
"group",
"names",
"/",
"patterns",
"e",
".",
"g",
":",
"{",
"src",
":",
"grp",
"[",
"1",
"-",
"3",
"]",
"dst",
":",
"grp",
"[",
"4",
"-",
"6",
"]",
"...",
"}",
"will",
"generate",
"9",
"descriptions... | train | https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/api.py#L886-L901 |
BeyondTheClouds/enoslib | enoslib/api.py | _generate_default_grp_constraints | def _generate_default_grp_constraints(roles, network_constraints):
"""Generate default symetric grp constraints.
"""
default_delay = network_constraints.get('default_delay')
default_rate = network_constraints.get('default_rate')
default_loss = network_constraints.get('default_loss', 0)
except_gr... | python | def _generate_default_grp_constraints(roles, network_constraints):
"""Generate default symetric grp constraints.
"""
default_delay = network_constraints.get('default_delay')
default_rate = network_constraints.get('default_rate')
default_loss = network_constraints.get('default_loss', 0)
except_gr... | [
"def",
"_generate_default_grp_constraints",
"(",
"roles",
",",
"network_constraints",
")",
":",
"default_delay",
"=",
"network_constraints",
".",
"get",
"(",
"'default_delay'",
")",
"default_rate",
"=",
"network_constraints",
".",
"get",
"(",
"'default_rate'",
")",
"d... | Generate default symetric grp constraints. | [
"Generate",
"default",
"symetric",
"grp",
"constraints",
"."
] | train | https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/api.py#L922-L943 |
BeyondTheClouds/enoslib | enoslib/api.py | _generate_actual_grp_constraints | def _generate_actual_grp_constraints(network_constraints):
"""Generate the user specified constraints
"""
if 'constraints' not in network_constraints:
return []
constraints = network_constraints['constraints']
actual = []
for desc in constraints:
descs = _expand_description(desc... | python | def _generate_actual_grp_constraints(network_constraints):
"""Generate the user specified constraints
"""
if 'constraints' not in network_constraints:
return []
constraints = network_constraints['constraints']
actual = []
for desc in constraints:
descs = _expand_description(desc... | [
"def",
"_generate_actual_grp_constraints",
"(",
"network_constraints",
")",
":",
"if",
"'constraints'",
"not",
"in",
"network_constraints",
":",
"return",
"[",
"]",
"constraints",
"=",
"network_constraints",
"[",
"'constraints'",
"]",
"actual",
"=",
"[",
"]",
"for",... | Generate the user specified constraints | [
"Generate",
"the",
"user",
"specified",
"constraints"
] | train | https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/api.py#L946-L963 |
BeyondTheClouds/enoslib | enoslib/api.py | _merge_constraints | def _merge_constraints(constraints, overrides):
"""Merge the constraints avoiding duplicates
Change constraints in place.
"""
for o in overrides:
i = 0
while i < len(constraints):
c = constraints[i]
if _same(o, c):
constraints[i].update(o)
... | python | def _merge_constraints(constraints, overrides):
"""Merge the constraints avoiding duplicates
Change constraints in place.
"""
for o in overrides:
i = 0
while i < len(constraints):
c = constraints[i]
if _same(o, c):
constraints[i].update(o)
... | [
"def",
"_merge_constraints",
"(",
"constraints",
",",
"overrides",
")",
":",
"for",
"o",
"in",
"overrides",
":",
"i",
"=",
"0",
"while",
"i",
"<",
"len",
"(",
"constraints",
")",
":",
"c",
"=",
"constraints",
"[",
"i",
"]",
"if",
"_same",
"(",
"o",
... | Merge the constraints avoiding duplicates
Change constraints in place. | [
"Merge",
"the",
"constraints",
"avoiding",
"duplicates",
"Change",
"constraints",
"in",
"place",
"."
] | train | https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/api.py#L966-L977 |
BeyondTheClouds/enoslib | enoslib/api.py | _build_grp_constraints | def _build_grp_constraints(roles, network_constraints):
"""Generate constraints at the group level,
It expands the group names and deal with symetric constraints.
"""
# generate defaults constraints
constraints = _generate_default_grp_constraints(roles,
... | python | def _build_grp_constraints(roles, network_constraints):
"""Generate constraints at the group level,
It expands the group names and deal with symetric constraints.
"""
# generate defaults constraints
constraints = _generate_default_grp_constraints(roles,
... | [
"def",
"_build_grp_constraints",
"(",
"roles",
",",
"network_constraints",
")",
":",
"# generate defaults constraints",
"constraints",
"=",
"_generate_default_grp_constraints",
"(",
"roles",
",",
"network_constraints",
")",
"# Updating the constraints if necessary",
"if",
"'con... | Generate constraints at the group level,
It expands the group names and deal with symetric constraints. | [
"Generate",
"constraints",
"at",
"the",
"group",
"level",
"It",
"expands",
"the",
"group",
"names",
"and",
"deal",
"with",
"symetric",
"constraints",
"."
] | train | https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/api.py#L980-L992 |
BeyondTheClouds/enoslib | enoslib/api.py | _build_ip_constraints | def _build_ip_constraints(roles, ips, constraints):
"""Generate the constraints at the ip/device level.
Those constraints are those used by ansible to enforce tc/netem rules.
"""
local_ips = copy.deepcopy(ips)
for constraint in constraints:
gsrc = constraint['src']
gdst = constraint[... | python | def _build_ip_constraints(roles, ips, constraints):
"""Generate the constraints at the ip/device level.
Those constraints are those used by ansible to enforce tc/netem rules.
"""
local_ips = copy.deepcopy(ips)
for constraint in constraints:
gsrc = constraint['src']
gdst = constraint[... | [
"def",
"_build_ip_constraints",
"(",
"roles",
",",
"ips",
",",
"constraints",
")",
":",
"local_ips",
"=",
"copy",
".",
"deepcopy",
"(",
"ips",
")",
"for",
"constraint",
"in",
"constraints",
":",
"gsrc",
"=",
"constraint",
"[",
"'src'",
"]",
"gdst",
"=",
... | Generate the constraints at the ip/device level.
Those constraints are those used by ansible to enforce tc/netem rules. | [
"Generate",
"the",
"constraints",
"at",
"the",
"ip",
"/",
"device",
"level",
".",
"Those",
"constraints",
"are",
"those",
"used",
"by",
"ansible",
"to",
"enforce",
"tc",
"/",
"netem",
"rules",
"."
] | train | https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/api.py#L995-L1035 |
BeyondTheClouds/enoslib | enoslib/api.py | _map_device_on_host_networks | def _map_device_on_host_networks(provider_nets, devices):
"""Decorate each networks with the corresponding nic name."""
networks = copy.deepcopy(provider_nets)
for network in networks:
for device in devices:
network.setdefault('device', None)
ip_set = IPSet([network['cidr']])... | python | def _map_device_on_host_networks(provider_nets, devices):
"""Decorate each networks with the corresponding nic name."""
networks = copy.deepcopy(provider_nets)
for network in networks:
for device in devices:
network.setdefault('device', None)
ip_set = IPSet([network['cidr']])... | [
"def",
"_map_device_on_host_networks",
"(",
"provider_nets",
",",
"devices",
")",
":",
"networks",
"=",
"copy",
".",
"deepcopy",
"(",
"provider_nets",
")",
"for",
"network",
"in",
"networks",
":",
"for",
"device",
"in",
"devices",
":",
"network",
".",
"setdefa... | Decorate each networks with the corresponding nic name. | [
"Decorate",
"each",
"networks",
"with",
"the",
"corresponding",
"nic",
"name",
"."
] | train | https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/api.py#L1038-L1056 |
BreakingBytes/simkit | examples/PVPower/pvpower/formulas/utils.py | f_daterange | def f_daterange(freq, tz='UTC', *args, **kwargs):
"""
Use ``dateutil.rrule`` to create a range of dates. The frequency must be a
string in the following list: YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY,
MINUTELY or SECONDLY.
See `dateutil rrule`_ documentation for more detail.
.. _dateutil rrule: ... | python | def f_daterange(freq, tz='UTC', *args, **kwargs):
"""
Use ``dateutil.rrule`` to create a range of dates. The frequency must be a
string in the following list: YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY,
MINUTELY or SECONDLY.
See `dateutil rrule`_ documentation for more detail.
.. _dateutil rrule: ... | [
"def",
"f_daterange",
"(",
"freq",
",",
"tz",
"=",
"'UTC'",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"tz",
"=",
"pytz",
".",
"timezone",
"(",
"tz",
")",
"freq",
"=",
"getattr",
"(",
"rrule",
",",
"freq",
".",
"upper",
"(",
")",
")",... | Use ``dateutil.rrule`` to create a range of dates. The frequency must be a
string in the following list: YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY,
MINUTELY or SECONDLY.
See `dateutil rrule`_ documentation for more detail.
.. _dateutil rrule: https://dateutil.readthedocs.org/en/latest/rrule.html
:pa... | [
"Use",
"dateutil",
".",
"rrule",
"to",
"create",
"a",
"range",
"of",
"dates",
".",
"The",
"frequency",
"must",
"be",
"a",
"string",
"in",
"the",
"following",
"list",
":",
"YEARLY",
"MONTHLY",
"WEEKLY",
"DAILY",
"HOURLY",
"MINUTELY",
"or",
"SECONDLY",
"."
] | train | https://github.com/BreakingBytes/simkit/blob/205163d879d3880b6c9ef609f1b723a58773026b/examples/PVPower/pvpower/formulas/utils.py#L14-L36 |
BreakingBytes/simkit | examples/PVPower/pvpower/formulas/utils.py | f_energy | def f_energy(ac_power, times):
"""
Calculate the total energy accumulated from AC power at the end of each
timestep between the given times.
:param ac_power: AC Power [W]
:param times: times
:type times: np.datetime64[s]
:return: energy [W*h] and energy times
"""
dt = np.diff(times)... | python | def f_energy(ac_power, times):
"""
Calculate the total energy accumulated from AC power at the end of each
timestep between the given times.
:param ac_power: AC Power [W]
:param times: times
:type times: np.datetime64[s]
:return: energy [W*h] and energy times
"""
dt = np.diff(times)... | [
"def",
"f_energy",
"(",
"ac_power",
",",
"times",
")",
":",
"dt",
"=",
"np",
".",
"diff",
"(",
"times",
")",
"# calculate timesteps",
"# convert timedeltas to quantities",
"dt",
"=",
"dt",
".",
"astype",
"(",
"'timedelta64[s]'",
")",
".",
"astype",
"(",
"'fl... | Calculate the total energy accumulated from AC power at the end of each
timestep between the given times.
:param ac_power: AC Power [W]
:param times: times
:type times: np.datetime64[s]
:return: energy [W*h] and energy times | [
"Calculate",
"the",
"total",
"energy",
"accumulated",
"from",
"AC",
"power",
"at",
"the",
"end",
"of",
"each",
"timestep",
"between",
"the",
"given",
"times",
"."
] | train | https://github.com/BreakingBytes/simkit/blob/205163d879d3880b6c9ef609f1b723a58773026b/examples/PVPower/pvpower/formulas/utils.py#L39-L54 |
BreakingBytes/simkit | examples/PVPower/pvpower/formulas/utils.py | groupby_freq | def groupby_freq(items, times, freq, wkst='SU'):
"""
Group timeseries by frequency. The frequency must be a string in the
following list: YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY or
SECONDLY. The optional weekstart must be a string in the following list:
MO, TU, WE, TH, FR, SA and SU.
:... | python | def groupby_freq(items, times, freq, wkst='SU'):
"""
Group timeseries by frequency. The frequency must be a string in the
following list: YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY or
SECONDLY. The optional weekstart must be a string in the following list:
MO, TU, WE, TH, FR, SA and SU.
:... | [
"def",
"groupby_freq",
"(",
"items",
",",
"times",
",",
"freq",
",",
"wkst",
"=",
"'SU'",
")",
":",
"timeseries",
"=",
"zip",
"(",
"times",
",",
"items",
")",
"# timeseries map of items",
"# create a key lambda to group timeseries by",
"if",
"freq",
".",
"upper"... | Group timeseries by frequency. The frequency must be a string in the
following list: YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY or
SECONDLY. The optional weekstart must be a string in the following list:
MO, TU, WE, TH, FR, SA and SU.
:param items: items in timeseries
:param times: times corr... | [
"Group",
"timeseries",
"by",
"frequency",
".",
"The",
"frequency",
"must",
"be",
"a",
"string",
"in",
"the",
"following",
"list",
":",
"YEARLY",
"MONTHLY",
"WEEKLY",
"DAILY",
"HOURLY",
"MINUTELY",
"or",
"SECONDLY",
".",
"The",
"optional",
"weekstart",
"must",
... | train | https://github.com/BreakingBytes/simkit/blob/205163d879d3880b6c9ef609f1b723a58773026b/examples/PVPower/pvpower/formulas/utils.py#L57-L86 |
BreakingBytes/simkit | examples/PVPower/pvpower/formulas/utils.py | f_rollup | def f_rollup(items, times, freq):
"""
Use :func:`groupby_freq` to rollup items
:param items: items in timeseries
:param times: times corresponding to items
:param freq: One of the ``dateutil.rrule`` frequency constants
:type freq: str
"""
rollup = [np.sum(item for __, item in ts)
... | python | def f_rollup(items, times, freq):
"""
Use :func:`groupby_freq` to rollup items
:param items: items in timeseries
:param times: times corresponding to items
:param freq: One of the ``dateutil.rrule`` frequency constants
:type freq: str
"""
rollup = [np.sum(item for __, item in ts)
... | [
"def",
"f_rollup",
"(",
"items",
",",
"times",
",",
"freq",
")",
":",
"rollup",
"=",
"[",
"np",
".",
"sum",
"(",
"item",
"for",
"__",
",",
"item",
"in",
"ts",
")",
"for",
"_",
",",
"ts",
"in",
"groupby_freq",
"(",
"items",
",",
"times",
",",
"f... | Use :func:`groupby_freq` to rollup items
:param items: items in timeseries
:param times: times corresponding to items
:param freq: One of the ``dateutil.rrule`` frequency constants
:type freq: str | [
"Use",
":",
"func",
":",
"groupby_freq",
"to",
"rollup",
"items"
] | train | https://github.com/BreakingBytes/simkit/blob/205163d879d3880b6c9ef609f1b723a58773026b/examples/PVPower/pvpower/formulas/utils.py#L89-L100 |
volafiled/python-volapi | volapi/file.py | File.fileupdate | def fileupdate(self, data):
"""Method to update extra metadata fields with dict obtained
through `fileinfo`"""
self.name = data["name"]
add = self.__additional
add["filetype"] = "other"
for filetype in ("book", "image", "video", "audio", "archive"):
if filety... | python | def fileupdate(self, data):
"""Method to update extra metadata fields with dict obtained
through `fileinfo`"""
self.name = data["name"]
add = self.__additional
add["filetype"] = "other"
for filetype in ("book", "image", "video", "audio", "archive"):
if filety... | [
"def",
"fileupdate",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"name",
"=",
"data",
"[",
"\"name\"",
"]",
"add",
"=",
"self",
".",
"__additional",
"add",
"[",
"\"filetype\"",
"]",
"=",
"\"other\"",
"for",
"filetype",
"in",
"(",
"\"book\"",
",",
... | Method to update extra metadata fields with dict obtained
through `fileinfo` | [
"Method",
"to",
"update",
"extra",
"metadata",
"fields",
"with",
"dict",
"obtained",
"through",
"fileinfo"
] | train | https://github.com/volafiled/python-volapi/blob/5f0bc03dbde703264ac6ed494e2050761f688a3e/volapi/file.py#L38-L60 |
volafiled/python-volapi | volapi/file.py | File.thumbnail | def thumbnail(self):
"""Returns the thumbnail's url for this image, audio, or video file.
Returns empty string if the file has no thumbnail"""
if self.filetype not in ("video", "image", "audio"):
raise RuntimeError("Only video, audio and image files can have thumbnails")
thu... | python | def thumbnail(self):
"""Returns the thumbnail's url for this image, audio, or video file.
Returns empty string if the file has no thumbnail"""
if self.filetype not in ("video", "image", "audio"):
raise RuntimeError("Only video, audio and image files can have thumbnails")
thu... | [
"def",
"thumbnail",
"(",
"self",
")",
":",
"if",
"self",
".",
"filetype",
"not",
"in",
"(",
"\"video\"",
",",
"\"image\"",
",",
"\"audio\"",
")",
":",
"raise",
"RuntimeError",
"(",
"\"Only video, audio and image files can have thumbnails\"",
")",
"thumb_srv",
"=",... | Returns the thumbnail's url for this image, audio, or video file.
Returns empty string if the file has no thumbnail | [
"Returns",
"the",
"thumbnail",
"s",
"url",
"for",
"this",
"image",
"audio",
"or",
"video",
"file",
".",
"Returns",
"empty",
"string",
"if",
"the",
"file",
"has",
"no",
"thumbnail"
] | train | https://github.com/volafiled/python-volapi/blob/5f0bc03dbde703264ac6ed494e2050761f688a3e/volapi/file.py#L81-L89 |
volafiled/python-volapi | volapi/file.py | File.duration | def duration(self):
"""Returns the duration in seconds of this audio or video file"""
if self.filetype not in ("video", "audio"):
raise RuntimeError("Only videos and audio have durations")
return self.info.get("length") or self.info.get("duration") | python | def duration(self):
"""Returns the duration in seconds of this audio or video file"""
if self.filetype not in ("video", "audio"):
raise RuntimeError("Only videos and audio have durations")
return self.info.get("length") or self.info.get("duration") | [
"def",
"duration",
"(",
"self",
")",
":",
"if",
"self",
".",
"filetype",
"not",
"in",
"(",
"\"video\"",
",",
"\"audio\"",
")",
":",
"raise",
"RuntimeError",
"(",
"\"Only videos and audio have durations\"",
")",
"return",
"self",
".",
"info",
".",
"get",
"(",... | Returns the duration in seconds of this audio or video file | [
"Returns",
"the",
"duration",
"in",
"seconds",
"of",
"this",
"audio",
"or",
"video",
"file"
] | train | https://github.com/volafiled/python-volapi/blob/5f0bc03dbde703264ac6ed494e2050761f688a3e/volapi/file.py#L100-L105 |
volafiled/python-volapi | volapi/file.py | File.delete | def delete(self):
""" Remove this file """
self.room.check_owner()
self.conn.make_call("deleteFiles", [self.fid]) | python | def delete(self):
""" Remove this file """
self.room.check_owner()
self.conn.make_call("deleteFiles", [self.fid]) | [
"def",
"delete",
"(",
"self",
")",
":",
"self",
".",
"room",
".",
"check_owner",
"(",
")",
"self",
".",
"conn",
".",
"make_call",
"(",
"\"deleteFiles\"",
",",
"[",
"self",
".",
"fid",
"]",
")"
] | Remove this file | [
"Remove",
"this",
"file"
] | train | https://github.com/volafiled/python-volapi/blob/5f0bc03dbde703264ac6ed494e2050761f688a3e/volapi/file.py#L151-L154 |
volafiled/python-volapi | volapi/file.py | File.timeout | def timeout(self, duration=3600):
""" Timeout the uploader of this file """
self.room.check_owner()
self.conn.make_call("timeoutFile", self.fid, duration) | python | def timeout(self, duration=3600):
""" Timeout the uploader of this file """
self.room.check_owner()
self.conn.make_call("timeoutFile", self.fid, duration) | [
"def",
"timeout",
"(",
"self",
",",
"duration",
"=",
"3600",
")",
":",
"self",
".",
"room",
".",
"check_owner",
"(",
")",
"self",
".",
"conn",
".",
"make_call",
"(",
"\"timeoutFile\"",
",",
"self",
".",
"fid",
",",
"duration",
")"
] | Timeout the uploader of this file | [
"Timeout",
"the",
"uploader",
"of",
"this",
"file"
] | train | https://github.com/volafiled/python-volapi/blob/5f0bc03dbde703264ac6ed494e2050761f688a3e/volapi/file.py#L156-L159 |
Scout24/succubus | src/main/python/succubus/daemonize.py | Daemon.set_gid | def set_gid(self):
"""Change the group of the running process"""
if self.group:
gid = getgrnam(self.group).gr_gid
try:
os.setgid(gid)
except Exception:
message = ("Unable to switch ownership to {0}:{1}. " +
"D... | python | def set_gid(self):
"""Change the group of the running process"""
if self.group:
gid = getgrnam(self.group).gr_gid
try:
os.setgid(gid)
except Exception:
message = ("Unable to switch ownership to {0}:{1}. " +
"D... | [
"def",
"set_gid",
"(",
"self",
")",
":",
"if",
"self",
".",
"group",
":",
"gid",
"=",
"getgrnam",
"(",
"self",
".",
"group",
")",
".",
"gr_gid",
"try",
":",
"os",
".",
"setgid",
"(",
"gid",
")",
"except",
"Exception",
":",
"message",
"=",
"(",
"\... | Change the group of the running process | [
"Change",
"the",
"group",
"of",
"the",
"running",
"process"
] | train | https://github.com/Scout24/succubus/blob/465d6ef978be165b1b652736935b7cf0ee5ebe9e/src/main/python/succubus/daemonize.py#L46-L56 |
Scout24/succubus | src/main/python/succubus/daemonize.py | Daemon.set_uid | def set_uid(self):
"""Change the user of the running process"""
if self.user:
uid = getpwnam(self.user).pw_uid
try:
os.setuid(uid)
except Exception:
message = ('Unable to switch ownership to {0}:{1}. ' +
'Did ... | python | def set_uid(self):
"""Change the user of the running process"""
if self.user:
uid = getpwnam(self.user).pw_uid
try:
os.setuid(uid)
except Exception:
message = ('Unable to switch ownership to {0}:{1}. ' +
'Did ... | [
"def",
"set_uid",
"(",
"self",
")",
":",
"if",
"self",
".",
"user",
":",
"uid",
"=",
"getpwnam",
"(",
"self",
".",
"user",
")",
".",
"pw_uid",
"try",
":",
"os",
".",
"setuid",
"(",
"uid",
")",
"except",
"Exception",
":",
"message",
"=",
"(",
"'Un... | Change the user of the running process | [
"Change",
"the",
"user",
"of",
"the",
"running",
"process"
] | train | https://github.com/Scout24/succubus/blob/465d6ef978be165b1b652736935b7cf0ee5ebe9e/src/main/python/succubus/daemonize.py#L58-L68 |
Scout24/succubus | src/main/python/succubus/daemonize.py | Daemon.setup_logging | def setup_logging(self):
"""Set up self.logger
This function is called after load_configuration() and after changing
to new user/group IDs (if configured). Logging to syslog using the
root logger is configured by default, you can override this method if
you want something else.
... | python | def setup_logging(self):
"""Set up self.logger
This function is called after load_configuration() and after changing
to new user/group IDs (if configured). Logging to syslog using the
root logger is configured by default, you can override this method if
you want something else.
... | [
"def",
"setup_logging",
"(",
"self",
")",
":",
"self",
".",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"'/dev/log'",
")",
":",
"handler",
"=",
"SysLogHandler",
"(",
"'/dev/log'",
")",
"else",
":",... | Set up self.logger
This function is called after load_configuration() and after changing
to new user/group IDs (if configured). Logging to syslog using the
root logger is configured by default, you can override this method if
you want something else. | [
"Set",
"up",
"self",
".",
"logger"
] | train | https://github.com/Scout24/succubus/blob/465d6ef978be165b1b652736935b7cf0ee5ebe9e/src/main/python/succubus/daemonize.py#L91-L105 |
Scout24/succubus | src/main/python/succubus/daemonize.py | Daemon.daemonize | def daemonize(self):
"""
Do the UNIX double-fork magic, see Stevens' "Advanced
Programming in the UNIX Environment" for details (ISBN 0201563177)
http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16
"""
try:
pid = os.fork()
if pid > 0:
... | python | def daemonize(self):
"""
Do the UNIX double-fork magic, see Stevens' "Advanced
Programming in the UNIX Environment" for details (ISBN 0201563177)
http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16
"""
try:
pid = os.fork()
if pid > 0:
... | [
"def",
"daemonize",
"(",
"self",
")",
":",
"try",
":",
"pid",
"=",
"os",
".",
"fork",
"(",
")",
"if",
"pid",
">",
"0",
":",
"sys",
".",
"exit",
"(",
"0",
")",
"except",
"OSError",
"as",
"e",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"'for... | Do the UNIX double-fork magic, see Stevens' "Advanced
Programming in the UNIX Environment" for details (ISBN 0201563177)
http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16 | [
"Do",
"the",
"UNIX",
"double",
"-",
"fork",
"magic",
"see",
"Stevens",
"Advanced",
"Programming",
"in",
"the",
"UNIX",
"Environment",
"for",
"details",
"(",
"ISBN",
"0201563177",
")",
"http",
":",
"//",
"www",
".",
"erlenstar",
".",
"demon",
".",
"co",
"... | train | https://github.com/Scout24/succubus/blob/465d6ef978be165b1b652736935b7cf0ee5ebe9e/src/main/python/succubus/daemonize.py#L123-L165 |
Scout24/succubus | src/main/python/succubus/daemonize.py | Daemon.start | def start(self):
"""Start the daemon"""
if self._already_running():
message = 'pid file %s already exists. Daemon already running?\n'
sys.stderr.write(message % self.pid_file)
return 0
self.set_gid()
self.set_uid()
# Create log files (if config... | python | def start(self):
"""Start the daemon"""
if self._already_running():
message = 'pid file %s already exists. Daemon already running?\n'
sys.stderr.write(message % self.pid_file)
return 0
self.set_gid()
self.set_uid()
# Create log files (if config... | [
"def",
"start",
"(",
"self",
")",
":",
"if",
"self",
".",
"_already_running",
"(",
")",
":",
"message",
"=",
"'pid file %s already exists. Daemon already running?\\n'",
"sys",
".",
"stderr",
".",
"write",
"(",
"message",
"%",
"self",
".",
"pid_file",
")",
"ret... | Start the daemon | [
"Start",
"the",
"daemon"
] | train | https://github.com/Scout24/succubus/blob/465d6ef978be165b1b652736935b7cf0ee5ebe9e/src/main/python/succubus/daemonize.py#L181-L200 |
Scout24/succubus | src/main/python/succubus/daemonize.py | Daemon.stop | def stop(self):
"""Stop the daemon"""
if self._already_running():
return self.reliable_kill()
else:
# FIXME: misleading error message
message = 'Daemon not running, nothing to do.\n'
sys.stderr.write(message)
return 0 | python | def stop(self):
"""Stop the daemon"""
if self._already_running():
return self.reliable_kill()
else:
# FIXME: misleading error message
message = 'Daemon not running, nothing to do.\n'
sys.stderr.write(message)
return 0 | [
"def",
"stop",
"(",
"self",
")",
":",
"if",
"self",
".",
"_already_running",
"(",
")",
":",
"return",
"self",
".",
"reliable_kill",
"(",
")",
"else",
":",
"# FIXME: misleading error message",
"message",
"=",
"'Daemon not running, nothing to do.\\n'",
"sys",
".",
... | Stop the daemon | [
"Stop",
"the",
"daemon"
] | train | https://github.com/Scout24/succubus/blob/465d6ef978be165b1b652736935b7cf0ee5ebe9e/src/main/python/succubus/daemonize.py#L223-L231 |
Scout24/succubus | src/main/python/succubus/daemonize.py | Daemon.status | def status(self):
"""Determine the status of the daemon"""
my_name = os.path.basename(sys.argv[0])
if self._already_running():
message = "{0} (pid {1}) is running...\n".format(my_name, self.pid)
sys.stdout.write(message)
return 0
sys.stdout.write("{0}... | python | def status(self):
"""Determine the status of the daemon"""
my_name = os.path.basename(sys.argv[0])
if self._already_running():
message = "{0} (pid {1}) is running...\n".format(my_name, self.pid)
sys.stdout.write(message)
return 0
sys.stdout.write("{0}... | [
"def",
"status",
"(",
"self",
")",
":",
"my_name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"sys",
".",
"argv",
"[",
"0",
"]",
")",
"if",
"self",
".",
"_already_running",
"(",
")",
":",
"message",
"=",
"\"{0} (pid {1}) is running...\\n\"",
".",
"... | Determine the status of the daemon | [
"Determine",
"the",
"status",
"of",
"the",
"daemon"
] | train | https://github.com/Scout24/succubus/blob/465d6ef978be165b1b652736935b7cf0ee5ebe9e/src/main/python/succubus/daemonize.py#L242-L250 |
nigma/django-easy-pdf | easy_pdf/rendering.py | fetch_resources | def fetch_resources(uri, rel):
"""
Retrieves embeddable resource from given ``uri``.
For now only local resources (images, fonts) are supported.
:param str uri: path or url to image or font resource
:returns: path to local resource file.
:rtype: str
:raises: :exc:`~easy_pdf.exceptions.Unsu... | python | def fetch_resources(uri, rel):
"""
Retrieves embeddable resource from given ``uri``.
For now only local resources (images, fonts) are supported.
:param str uri: path or url to image or font resource
:returns: path to local resource file.
:rtype: str
:raises: :exc:`~easy_pdf.exceptions.Unsu... | [
"def",
"fetch_resources",
"(",
"uri",
",",
"rel",
")",
":",
"if",
"settings",
".",
"STATIC_URL",
"and",
"uri",
".",
"startswith",
"(",
"settings",
".",
"STATIC_URL",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"settings",
".",
"STATIC_R... | Retrieves embeddable resource from given ``uri``.
For now only local resources (images, fonts) are supported.
:param str uri: path or url to image or font resource
:returns: path to local resource file.
:rtype: str
:raises: :exc:`~easy_pdf.exceptions.UnsupportedMediaPathException` | [
"Retrieves",
"embeddable",
"resource",
"from",
"given",
"uri",
"."
] | train | https://github.com/nigma/django-easy-pdf/blob/327605b91a445b453d8969b341ef74b12ab00a83/easy_pdf/rendering.py#L23-L48 |
nigma/django-easy-pdf | easy_pdf/rendering.py | html_to_pdf | def html_to_pdf(content, encoding="utf-8",
link_callback=fetch_resources, **kwargs):
"""
Converts html ``content`` into PDF document.
:param unicode content: html content
:returns: PDF content
:rtype: :class:`bytes`
:raises: :exc:`~easy_pdf.exceptions.PDFRenderingError`
"""
... | python | def html_to_pdf(content, encoding="utf-8",
link_callback=fetch_resources, **kwargs):
"""
Converts html ``content`` into PDF document.
:param unicode content: html content
:returns: PDF content
:rtype: :class:`bytes`
:raises: :exc:`~easy_pdf.exceptions.PDFRenderingError`
"""
... | [
"def",
"html_to_pdf",
"(",
"content",
",",
"encoding",
"=",
"\"utf-8\"",
",",
"link_callback",
"=",
"fetch_resources",
",",
"*",
"*",
"kwargs",
")",
":",
"src",
"=",
"BytesIO",
"(",
"content",
".",
"encode",
"(",
"encoding",
")",
")",
"dest",
"=",
"Bytes... | Converts html ``content`` into PDF document.
:param unicode content: html content
:returns: PDF content
:rtype: :class:`bytes`
:raises: :exc:`~easy_pdf.exceptions.PDFRenderingError` | [
"Converts",
"html",
"content",
"into",
"PDF",
"document",
"."
] | train | https://github.com/nigma/django-easy-pdf/blob/327605b91a445b453d8969b341ef74b12ab00a83/easy_pdf/rendering.py#L51-L78 |
nigma/django-easy-pdf | easy_pdf/rendering.py | make_response | def make_response(content, filename=None, content_type="application/pdf"):
"""
Wraps content into HTTP response.
If ``filename`` is specified then ``Content-Disposition: attachment``
header is added to the response.
Default ``Content-Type`` is ``application/pdf``.
:param bytes content: respon... | python | def make_response(content, filename=None, content_type="application/pdf"):
"""
Wraps content into HTTP response.
If ``filename`` is specified then ``Content-Disposition: attachment``
header is added to the response.
Default ``Content-Type`` is ``application/pdf``.
:param bytes content: respon... | [
"def",
"make_response",
"(",
"content",
",",
"filename",
"=",
"None",
",",
"content_type",
"=",
"\"application/pdf\"",
")",
":",
"response",
"=",
"HttpResponse",
"(",
"content",
",",
"content_type",
"=",
"content_type",
")",
"if",
"filename",
"is",
"not",
"Non... | Wraps content into HTTP response.
If ``filename`` is specified then ``Content-Disposition: attachment``
header is added to the response.
Default ``Content-Type`` is ``application/pdf``.
:param bytes content: response content
:param str filename: optional filename for file download
:param str ... | [
"Wraps",
"content",
"into",
"HTTP",
"response",
"."
] | train | https://github.com/nigma/django-easy-pdf/blob/327605b91a445b453d8969b341ef74b12ab00a83/easy_pdf/rendering.py#L102-L119 |
nigma/django-easy-pdf | easy_pdf/rendering.py | render_to_pdf | def render_to_pdf(template, context, using=None, request=None, encoding="utf-8", **kwargs):
"""
Create PDF document from Django html template.
:param str template: Path to Django template
:param dict context: Template context
:param using: Optional Django template engine
:param request: Django ... | python | def render_to_pdf(template, context, using=None, request=None, encoding="utf-8", **kwargs):
"""
Create PDF document from Django html template.
:param str template: Path to Django template
:param dict context: Template context
:param using: Optional Django template engine
:param request: Django ... | [
"def",
"render_to_pdf",
"(",
"template",
",",
"context",
",",
"using",
"=",
"None",
",",
"request",
"=",
"None",
",",
"encoding",
"=",
"\"utf-8\"",
",",
"*",
"*",
"kwargs",
")",
":",
"content",
"=",
"loader",
".",
"render_to_string",
"(",
"template",
","... | Create PDF document from Django html template.
:param str template: Path to Django template
:param dict context: Template context
:param using: Optional Django template engine
:param request: Django HTTP request
:type request: :class:`django.http.HttpRequest`
:returns: rendered PDF
:rtype:... | [
"Create",
"PDF",
"document",
"from",
"Django",
"html",
"template",
"."
] | train | https://github.com/nigma/django-easy-pdf/blob/327605b91a445b453d8969b341ef74b12ab00a83/easy_pdf/rendering.py#L122-L138 |
nigma/django-easy-pdf | easy_pdf/rendering.py | render_to_pdf_response | def render_to_pdf_response(request, template, context, using=None, filename=None,
encoding="utf-8", **kwargs):
"""
Renders a PDF response using given ``request``, ``template`` and ``context``.
If ``filename`` param is specified then the response ``Content-Disposition``
header... | python | def render_to_pdf_response(request, template, context, using=None, filename=None,
encoding="utf-8", **kwargs):
"""
Renders a PDF response using given ``request``, ``template`` and ``context``.
If ``filename`` param is specified then the response ``Content-Disposition``
header... | [
"def",
"render_to_pdf_response",
"(",
"request",
",",
"template",
",",
"context",
",",
"using",
"=",
"None",
",",
"filename",
"=",
"None",
",",
"encoding",
"=",
"\"utf-8\"",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"pdf",
"=",
"render_to_pdf",
"(",... | Renders a PDF response using given ``request``, ``template`` and ``context``.
If ``filename`` param is specified then the response ``Content-Disposition``
header will be set to ``attachment`` making the browser display
a "Save as.." dialog.
:param request: Django HTTP request
:type request: :class... | [
"Renders",
"a",
"PDF",
"response",
"using",
"given",
"request",
"template",
"and",
"context",
"."
] | train | https://github.com/nigma/django-easy-pdf/blob/327605b91a445b453d8969b341ef74b12ab00a83/easy_pdf/rendering.py#L141-L162 |
nigma/django-easy-pdf | easy_pdf/views.py | PDFTemplateResponseMixin.get_pdf_response | def get_pdf_response(self, context, **response_kwargs):
"""
Renders PDF document and prepares response.
:returns: Django HTTP response
:rtype: :class:`django.http.HttpResponse`
"""
return render_to_pdf_response(
request=self.request,
template=self... | python | def get_pdf_response(self, context, **response_kwargs):
"""
Renders PDF document and prepares response.
:returns: Django HTTP response
:rtype: :class:`django.http.HttpResponse`
"""
return render_to_pdf_response(
request=self.request,
template=self... | [
"def",
"get_pdf_response",
"(",
"self",
",",
"context",
",",
"*",
"*",
"response_kwargs",
")",
":",
"return",
"render_to_pdf_response",
"(",
"request",
"=",
"self",
".",
"request",
",",
"template",
"=",
"self",
".",
"get_template_names",
"(",
")",
",",
"cont... | Renders PDF document and prepares response.
:returns: Django HTTP response
:rtype: :class:`django.http.HttpResponse` | [
"Renders",
"PDF",
"document",
"and",
"prepares",
"response",
"."
] | train | https://github.com/nigma/django-easy-pdf/blob/327605b91a445b453d8969b341ef74b12ab00a83/easy_pdf/views.py#L47-L61 |
lk-geimfari/expynent | expynent/compiled.py | compile_patterns_in_dictionary | def compile_patterns_in_dictionary(dictionary):
"""
Replace all strings in dictionary with compiled
version of themselves and return dictionary.
"""
for key, value in dictionary.items():
if isinstance(value, str):
dictionary[key] = re.compile(value)
elif isinstance(value,... | python | def compile_patterns_in_dictionary(dictionary):
"""
Replace all strings in dictionary with compiled
version of themselves and return dictionary.
"""
for key, value in dictionary.items():
if isinstance(value, str):
dictionary[key] = re.compile(value)
elif isinstance(value,... | [
"def",
"compile_patterns_in_dictionary",
"(",
"dictionary",
")",
":",
"for",
"key",
",",
"value",
"in",
"dictionary",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"dictionary",
"[",
"key",
"]",
"=",
"re",
".",
"c... | Replace all strings in dictionary with compiled
version of themselves and return dictionary. | [
"Replace",
"all",
"strings",
"in",
"dictionary",
"with",
"compiled",
"version",
"of",
"themselves",
"and",
"return",
"dictionary",
"."
] | train | https://github.com/lk-geimfari/expynent/blob/85a1f6e681f669238202becb934381dd9a2313f4/expynent/compiled.py#L10-L20 |
facelessuser/pyspelling | pyspelling/filters/context.py | ContextFilter.validate_options | def validate_options(self, k, v):
"""Validate options."""
super().validate_options(k, v)
if k == 'delimiters':
for d in v:
if not isinstance(d, (dict, OrderedDict)):
raise ValueError("{}: 'delimters' entries must be of dict type.".format(self.__cl... | python | def validate_options(self, k, v):
"""Validate options."""
super().validate_options(k, v)
if k == 'delimiters':
for d in v:
if not isinstance(d, (dict, OrderedDict)):
raise ValueError("{}: 'delimters' entries must be of dict type.".format(self.__cl... | [
"def",
"validate_options",
"(",
"self",
",",
"k",
",",
"v",
")",
":",
"super",
"(",
")",
".",
"validate_options",
"(",
"k",
",",
"v",
")",
"if",
"k",
"==",
"'delimiters'",
":",
"for",
"d",
"in",
"v",
":",
"if",
"not",
"isinstance",
"(",
"d",
",",... | Validate options. | [
"Validate",
"options",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/context.py#L30-L46 |
facelessuser/pyspelling | pyspelling/filters/context.py | ContextFilter.setup | def setup(self):
"""Setup."""
self.context_visible_first = self.config['context_visible_first']
self.delimiters = []
self.escapes = None
self.line_endings = self.config['normalize_line_endings']
escapes = []
for delimiter in self.config['delimiters']:
... | python | def setup(self):
"""Setup."""
self.context_visible_first = self.config['context_visible_first']
self.delimiters = []
self.escapes = None
self.line_endings = self.config['normalize_line_endings']
escapes = []
for delimiter in self.config['delimiters']:
... | [
"def",
"setup",
"(",
"self",
")",
":",
"self",
".",
"context_visible_first",
"=",
"self",
".",
"config",
"[",
"'context_visible_first'",
"]",
"self",
".",
"delimiters",
"=",
"[",
"]",
"self",
".",
"escapes",
"=",
"None",
"self",
".",
"line_endings",
"=",
... | Setup. | [
"Setup",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/context.py#L48-L76 |
facelessuser/pyspelling | pyspelling/filters/context.py | ContextFilter.filter | def filter(self, source_file, encoding): # noqa A001
"""Parse file."""
with codecs.open(source_file, 'r', encoding=encoding) as f:
text = f.read()
return [filters.SourceText(self._filter(text), source_file, encoding, 'context')] | python | def filter(self, source_file, encoding): # noqa A001
"""Parse file."""
with codecs.open(source_file, 'r', encoding=encoding) as f:
text = f.read()
return [filters.SourceText(self._filter(text), source_file, encoding, 'context')] | [
"def",
"filter",
"(",
"self",
",",
"source_file",
",",
"encoding",
")",
":",
"# noqa A001",
"with",
"codecs",
".",
"open",
"(",
"source_file",
",",
"'r'",
",",
"encoding",
"=",
"encoding",
")",
"as",
"f",
":",
"text",
"=",
"f",
".",
"read",
"(",
")",... | Parse file. | [
"Parse",
"file",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/context.py#L78-L84 |
facelessuser/pyspelling | pyspelling/filters/context.py | ContextFilter.sfilter | def sfilter(self, source):
"""Filter."""
return [filters.SourceText(self._filter(source.text), source.context, source.encoding, 'context')] | python | def sfilter(self, source):
"""Filter."""
return [filters.SourceText(self._filter(source.text), source.context, source.encoding, 'context')] | [
"def",
"sfilter",
"(",
"self",
",",
"source",
")",
":",
"return",
"[",
"filters",
".",
"SourceText",
"(",
"self",
".",
"_filter",
"(",
"source",
".",
"text",
")",
",",
"source",
".",
"context",
",",
"source",
".",
"encoding",
",",
"'context'",
")",
"... | Filter. | [
"Filter",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/context.py#L86-L89 |
facelessuser/pyspelling | pyspelling/filters/context.py | ContextFilter._filter | def _filter(self, text):
"""Context delimiter filter."""
if self.line_endings:
text = self.norm_nl(text)
new_text = []
index = 0
last = 0
end = len(text)
while index < end:
m = self.escapes.match(text, pos=index) if self.escapes else None... | python | def _filter(self, text):
"""Context delimiter filter."""
if self.line_endings:
text = self.norm_nl(text)
new_text = []
index = 0
last = 0
end = len(text)
while index < end:
m = self.escapes.match(text, pos=index) if self.escapes else None... | [
"def",
"_filter",
"(",
"self",
",",
"text",
")",
":",
"if",
"self",
".",
"line_endings",
":",
"text",
"=",
"self",
".",
"norm_nl",
"(",
"text",
")",
"new_text",
"=",
"[",
"]",
"index",
"=",
"0",
"last",
"=",
"0",
"end",
"=",
"len",
"(",
"text",
... | Context delimiter filter. | [
"Context",
"delimiter",
"filter",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/context.py#L91-L124 |
horazont/aioopenssl | aioopenssl/__init__.py | create_starttls_connection | def create_starttls_connection(
loop,
protocol_factory,
host=None,
port=None,
*,
sock=None,
ssl_context_factory=None,
use_starttls=False,
local_addr=None,
**kwargs):
"""
Create a connection which can later be upgraded to use TLS.
... | python | def create_starttls_connection(
loop,
protocol_factory,
host=None,
port=None,
*,
sock=None,
ssl_context_factory=None,
use_starttls=False,
local_addr=None,
**kwargs):
"""
Create a connection which can later be upgraded to use TLS.
... | [
"def",
"create_starttls_connection",
"(",
"loop",
",",
"protocol_factory",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"*",
",",
"sock",
"=",
"None",
",",
"ssl_context_factory",
"=",
"None",
",",
"use_starttls",
"=",
"False",
",",
"local_addr",
... | Create a connection which can later be upgraded to use TLS.
.. versionchanged:: 0.4
The `local_addr` argument was added.
:param loop: The event loop to use.
:type loop: :class:`asyncio.BaseEventLoop`
:param protocol_factory: Factory for the protocol for the connection
:param host: The hos... | [
"Create",
"a",
"connection",
"which",
"can",
"later",
"be",
"upgraded",
"to",
"use",
"TLS",
"."
] | train | https://github.com/horazont/aioopenssl/blob/95cb39b5904d6a9702afcef6704181c850371081/aioopenssl/__init__.py#L726-L849 |
horazont/aioopenssl | aioopenssl/__init__.py | STARTTLSTransport._call_connection_lost_and_clean_up | def _call_connection_lost_and_clean_up(self, exc):
"""
Clean up all resources and call the protocols connection lost method.
"""
self._state = _State.CLOSED
try:
self._protocol.connection_lost(exc)
finally:
self._rawsock.close()
if sel... | python | def _call_connection_lost_and_clean_up(self, exc):
"""
Clean up all resources and call the protocols connection lost method.
"""
self._state = _State.CLOSED
try:
self._protocol.connection_lost(exc)
finally:
self._rawsock.close()
if sel... | [
"def",
"_call_connection_lost_and_clean_up",
"(",
"self",
",",
"exc",
")",
":",
"self",
".",
"_state",
"=",
"_State",
".",
"CLOSED",
"try",
":",
"self",
".",
"_protocol",
".",
"connection_lost",
"(",
"exc",
")",
"finally",
":",
"self",
".",
"_rawsock",
"."... | Clean up all resources and call the protocols connection lost method. | [
"Clean",
"up",
"all",
"resources",
"and",
"call",
"the",
"protocols",
"connection",
"lost",
"method",
"."
] | train | https://github.com/horazont/aioopenssl/blob/95cb39b5904d6a9702afcef6704181c850371081/aioopenssl/__init__.py#L271-L286 |
horazont/aioopenssl | aioopenssl/__init__.py | STARTTLSTransport.abort | def abort(self):
"""
Immediately close the stream, without sending remaining buffers or
performing a proper shutdown.
"""
if self._state == _State.CLOSED:
self._invalid_state("abort() called")
return
self._force_close(None) | python | def abort(self):
"""
Immediately close the stream, without sending remaining buffers or
performing a proper shutdown.
"""
if self._state == _State.CLOSED:
self._invalid_state("abort() called")
return
self._force_close(None) | [
"def",
"abort",
"(",
"self",
")",
":",
"if",
"self",
".",
"_state",
"==",
"_State",
".",
"CLOSED",
":",
"self",
".",
"_invalid_state",
"(",
"\"abort() called\"",
")",
"return",
"self",
".",
"_force_close",
"(",
"None",
")"
] | Immediately close the stream, without sending remaining buffers or
performing a proper shutdown. | [
"Immediately",
"close",
"the",
"stream",
"without",
"sending",
"remaining",
"buffers",
"or",
"performing",
"a",
"proper",
"shutdown",
"."
] | train | https://github.com/horazont/aioopenssl/blob/95cb39b5904d6a9702afcef6704181c850371081/aioopenssl/__init__.py#L576-L585 |
horazont/aioopenssl | aioopenssl/__init__.py | STARTTLSTransport.close | def close(self):
"""
Close the stream. This performs a proper stream shutdown, except if the
stream is currently performing a TLS handshake. In that case, calling
:meth:`close` is equivalent to calling :meth:`abort`.
Otherwise, the transport waits until all buffers are transmitt... | python | def close(self):
"""
Close the stream. This performs a proper stream shutdown, except if the
stream is currently performing a TLS handshake. In that case, calling
:meth:`close` is equivalent to calling :meth:`abort`.
Otherwise, the transport waits until all buffers are transmitt... | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"_state",
"==",
"_State",
".",
"CLOSED",
":",
"self",
".",
"_invalid_state",
"(",
"\"close() called\"",
")",
"return",
"if",
"self",
".",
"_state",
"==",
"_State",
".",
"TLS_HANDSHAKING",
":",
"# ... | Close the stream. This performs a proper stream shutdown, except if the
stream is currently performing a TLS handshake. In that case, calling
:meth:`close` is equivalent to calling :meth:`abort`.
Otherwise, the transport waits until all buffers are transmitted. | [
"Close",
"the",
"stream",
".",
"This",
"performs",
"a",
"proper",
"stream",
"shutdown",
"except",
"if",
"the",
"stream",
"is",
"currently",
"performing",
"a",
"TLS",
"handshake",
".",
"In",
"that",
"case",
"calling",
":",
"meth",
":",
"close",
"is",
"equiv... | train | https://github.com/horazont/aioopenssl/blob/95cb39b5904d6a9702afcef6704181c850371081/aioopenssl/__init__.py#L601-L628 |
horazont/aioopenssl | aioopenssl/__init__.py | STARTTLSTransport.starttls | def starttls(self, ssl_context=None,
post_handshake_callback=None):
"""
Start a TLS stream on top of the socket. This is an invalid operation
if the stream is not in RAW_OPEN state.
If `ssl_context` is set, it overrides the `ssl_context` passed to the
constructo... | python | def starttls(self, ssl_context=None,
post_handshake_callback=None):
"""
Start a TLS stream on top of the socket. This is an invalid operation
if the stream is not in RAW_OPEN state.
If `ssl_context` is set, it overrides the `ssl_context` passed to the
constructo... | [
"def",
"starttls",
"(",
"self",
",",
"ssl_context",
"=",
"None",
",",
"post_handshake_callback",
"=",
"None",
")",
":",
"if",
"self",
".",
"_state",
"!=",
"_State",
".",
"RAW_OPEN",
"or",
"self",
".",
"_closing",
":",
"raise",
"self",
".",
"_invalid_state"... | Start a TLS stream on top of the socket. This is an invalid operation
if the stream is not in RAW_OPEN state.
If `ssl_context` is set, it overrides the `ssl_context` passed to the
constructor. If `post_handshake_callback` is set, it overrides the
`post_handshake_callback` passed to the ... | [
"Start",
"a",
"TLS",
"stream",
"on",
"top",
"of",
"the",
"socket",
".",
"This",
"is",
"an",
"invalid",
"operation",
"if",
"the",
"stream",
"is",
"not",
"in",
"RAW_OPEN",
"state",
"."
] | train | https://github.com/horazont/aioopenssl/blob/95cb39b5904d6a9702afcef6704181c850371081/aioopenssl/__init__.py#L649-L685 |
horazont/aioopenssl | aioopenssl/__init__.py | STARTTLSTransport.write | def write(self, data):
"""
Write data to the transport. This is an invalid operation if the stream
is not writable, that is, if it is closed. During TLS negotiation, the
data is buffered.
"""
if not isinstance(data, (bytes, bytearray, memoryview)):
raise TypeE... | python | def write(self, data):
"""
Write data to the transport. This is an invalid operation if the stream
is not writable, that is, if it is closed. During TLS negotiation, the
data is buffered.
"""
if not isinstance(data, (bytes, bytearray, memoryview)):
raise TypeE... | [
"def",
"write",
"(",
"self",
",",
"data",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"(",
"bytes",
",",
"bytearray",
",",
"memoryview",
")",
")",
":",
"raise",
"TypeError",
"(",
"'data argument must be byte-ish (%r)'",
",",
"type",
"(",
"data",... | Write data to the transport. This is an invalid operation if the stream
is not writable, that is, if it is closed. During TLS negotiation, the
data is buffered. | [
"Write",
"data",
"to",
"the",
"transport",
".",
"This",
"is",
"an",
"invalid",
"operation",
"if",
"the",
"stream",
"is",
"not",
"writable",
"that",
"is",
"if",
"it",
"is",
"closed",
".",
"During",
"TLS",
"negotiation",
"the",
"data",
"is",
"buffered",
".... | train | https://github.com/horazont/aioopenssl/blob/95cb39b5904d6a9702afcef6704181c850371081/aioopenssl/__init__.py#L687-L706 |
BBVA/data-refinery | datarefinery/FieldOperations.py | explode | def explode(prefix: str):
"""
given an array of objects de-normalized into fields
"""
def _app(i, e=None):
if i is not None:
return {k: v for (k, v) in iter_fields(i)}, None
return i, e
def iter_fields(event_field: Union[dict, list]):
if type(event_field) is dict... | python | def explode(prefix: str):
"""
given an array of objects de-normalized into fields
"""
def _app(i, e=None):
if i is not None:
return {k: v for (k, v) in iter_fields(i)}, None
return i, e
def iter_fields(event_field: Union[dict, list]):
if type(event_field) is dict... | [
"def",
"explode",
"(",
"prefix",
":",
"str",
")",
":",
"def",
"_app",
"(",
"i",
",",
"e",
"=",
"None",
")",
":",
"if",
"i",
"is",
"not",
"None",
":",
"return",
"{",
"k",
":",
"v",
"for",
"(",
"k",
",",
"v",
")",
"in",
"iter_fields",
"(",
"i... | given an array of objects de-normalized into fields | [
"given",
"an",
"array",
"of",
"objects",
"de",
"-",
"normalized",
"into",
"fields"
] | train | https://github.com/BBVA/data-refinery/blob/4ff19186ac570269f64a245ad6297cf882c70aa4/datarefinery/FieldOperations.py#L186-L207 |
facelessuser/pyspelling | pyspelling/filters/xml.py | XmlFilter._has_xml_encode | def _has_xml_encode(self, content):
"""Check XML encoding."""
encode = None
m = RE_XML_START.match(content)
if m:
if m.group(1):
m2 = RE_XML_ENCODE.match(m.group(1))
if m2:
enc = m2.group(2).decode('ascii')
... | python | def _has_xml_encode(self, content):
"""Check XML encoding."""
encode = None
m = RE_XML_START.match(content)
if m:
if m.group(1):
m2 = RE_XML_ENCODE.match(m.group(1))
if m2:
enc = m2.group(2).decode('ascii')
... | [
"def",
"_has_xml_encode",
"(",
"self",
",",
"content",
")",
":",
"encode",
"=",
"None",
"m",
"=",
"RE_XML_START",
".",
"match",
"(",
"content",
")",
"if",
"m",
":",
"if",
"m",
".",
"group",
"(",
"1",
")",
":",
"m2",
"=",
"RE_XML_ENCODE",
".",
"matc... | Check XML encoding. | [
"Check",
"XML",
"encoding",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/xml.py#L71-L116 |
facelessuser/pyspelling | pyspelling/filters/xml.py | XmlFilter.is_break_tag | def is_break_tag(self, el):
"""Check if tag is an element we should break on."""
name = el.name
return name in self.break_tags or name in self.user_break_tags | python | def is_break_tag(self, el):
"""Check if tag is an element we should break on."""
name = el.name
return name in self.break_tags or name in self.user_break_tags | [
"def",
"is_break_tag",
"(",
"self",
",",
"el",
")",
":",
"name",
"=",
"el",
".",
"name",
"return",
"name",
"in",
"self",
".",
"break_tags",
"or",
"name",
"in",
"self",
".",
"user_break_tags"
] | Check if tag is an element we should break on. | [
"Check",
"if",
"tag",
"is",
"an",
"element",
"we",
"should",
"break",
"on",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/xml.py#L123-L127 |
facelessuser/pyspelling | pyspelling/filters/xml.py | XmlFilter.store_blocks | def store_blocks(self, el, blocks, text, force_root):
"""Store the text as desired."""
if force_root or el.parent is None or self.is_break_tag(el):
content = ''.join(text)
if content:
blocks.append((content, self.construct_selector(el)))
text = []
... | python | def store_blocks(self, el, blocks, text, force_root):
"""Store the text as desired."""
if force_root or el.parent is None or self.is_break_tag(el):
content = ''.join(text)
if content:
blocks.append((content, self.construct_selector(el)))
text = []
... | [
"def",
"store_blocks",
"(",
"self",
",",
"el",
",",
"blocks",
",",
"text",
",",
"force_root",
")",
":",
"if",
"force_root",
"or",
"el",
".",
"parent",
"is",
"None",
"or",
"self",
".",
"is_break_tag",
"(",
"el",
")",
":",
"content",
"=",
"''",
".",
... | Store the text as desired. | [
"Store",
"the",
"text",
"as",
"desired",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/xml.py#L129-L137 |
facelessuser/pyspelling | pyspelling/filters/xml.py | XmlFilter.construct_selector | def construct_selector(self, el, attr=''):
"""Construct an selector for context."""
selector = deque()
ancestor = el
while ancestor and ancestor.parent:
if ancestor is not el:
selector.appendleft(ancestor.name)
else:
tag = ancesto... | python | def construct_selector(self, el, attr=''):
"""Construct an selector for context."""
selector = deque()
ancestor = el
while ancestor and ancestor.parent:
if ancestor is not el:
selector.appendleft(ancestor.name)
else:
tag = ancesto... | [
"def",
"construct_selector",
"(",
"self",
",",
"el",
",",
"attr",
"=",
"''",
")",
":",
"selector",
"=",
"deque",
"(",
")",
"ancestor",
"=",
"el",
"while",
"ancestor",
"and",
"ancestor",
".",
"parent",
":",
"if",
"ancestor",
"is",
"not",
"el",
":",
"s... | Construct an selector for context. | [
"Construct",
"an",
"selector",
"for",
"context",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/xml.py#L139-L159 |
facelessuser/pyspelling | pyspelling/filters/xml.py | XmlFilter.to_text | def to_text(self, tree, force_root=False):
"""
Extract text from tags.
Skip any selectors specified and include attributes if specified.
Ignored tags will not have their attributes scanned either.
"""
self.extract_tag_metadata(tree)
text = []
attributes... | python | def to_text(self, tree, force_root=False):
"""
Extract text from tags.
Skip any selectors specified and include attributes if specified.
Ignored tags will not have their attributes scanned either.
"""
self.extract_tag_metadata(tree)
text = []
attributes... | [
"def",
"to_text",
"(",
"self",
",",
"tree",
",",
"force_root",
"=",
"False",
")",
":",
"self",
".",
"extract_tag_metadata",
"(",
"tree",
")",
"text",
"=",
"[",
"]",
"attributes",
"=",
"[",
"]",
"comments",
"=",
"[",
"]",
"blocks",
"=",
"[",
"]",
"i... | Extract text from tags.
Skip any selectors specified and include attributes if specified.
Ignored tags will not have their attributes scanned either. | [
"Extract",
"text",
"from",
"tags",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/xml.py#L167-L226 |
facelessuser/pyspelling | pyspelling/filters/xml.py | XmlFilter._filter | def _filter(self, text, context, encoding):
"""Filter the source text."""
content = []
blocks, attributes, comments = self.to_text(bs4.BeautifulSoup(text, self.parser))
if self.comments:
for c, desc in comments:
content.append(filters.SourceText(c, context + ... | python | def _filter(self, text, context, encoding):
"""Filter the source text."""
content = []
blocks, attributes, comments = self.to_text(bs4.BeautifulSoup(text, self.parser))
if self.comments:
for c, desc in comments:
content.append(filters.SourceText(c, context + ... | [
"def",
"_filter",
"(",
"self",
",",
"text",
",",
"context",
",",
"encoding",
")",
":",
"content",
"=",
"[",
"]",
"blocks",
",",
"attributes",
",",
"comments",
"=",
"self",
".",
"to_text",
"(",
"bs4",
".",
"BeautifulSoup",
"(",
"text",
",",
"self",
".... | Filter the source text. | [
"Filter",
"the",
"source",
"text",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/xml.py#L228-L241 |
facelessuser/pyspelling | pyspelling/filters/xml.py | XmlFilter.sfilter | def sfilter(self, source):
"""Filter."""
return self._filter(source.text, source.context, source.encoding) | python | def sfilter(self, source):
"""Filter."""
return self._filter(source.text, source.context, source.encoding) | [
"def",
"sfilter",
"(",
"self",
",",
"source",
")",
":",
"return",
"self",
".",
"_filter",
"(",
"source",
".",
"text",
",",
"source",
".",
"context",
",",
"source",
".",
"encoding",
")"
] | Filter. | [
"Filter",
"."
] | train | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/xml.py#L250-L253 |
JMSwag/dsdev-utils | dsdev_utils/helpers.py | lazy_import | def lazy_import(func):
"""Decorator for declaring a lazy import.
This decorator turns a function into an object that will act as a lazy
importer. Whenever the object's attributes are accessed, the function
is called and its return value used in place of the object. So you
can declare lazy imports... | python | def lazy_import(func):
"""Decorator for declaring a lazy import.
This decorator turns a function into an object that will act as a lazy
importer. Whenever the object's attributes are accessed, the function
is called and its return value used in place of the object. So you
can declare lazy imports... | [
"def",
"lazy_import",
"(",
"func",
")",
":",
"try",
":",
"f",
"=",
"sys",
".",
"_getframe",
"(",
"1",
")",
"except",
"Exception",
":",
"# pragma: no cover",
"namespace",
"=",
"None",
"else",
":",
"namespace",
"=",
"f",
".",
"f_locals",
"return",
"_LazyIm... | Decorator for declaring a lazy import.
This decorator turns a function into an object that will act as a lazy
importer. Whenever the object's attributes are accessed, the function
is called and its return value used in place of the object. So you
can declare lazy imports like this:
@lazy_imp... | [
"Decorator",
"for",
"declaring",
"a",
"lazy",
"import",
"."
] | train | https://github.com/JMSwag/dsdev-utils/blob/5adbf9b3fd9fff92d1dd714423b08e26a5038e14/dsdev_utils/helpers.py#L64-L90 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.