repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
metakermit/django-spa | spa/storage.py | PatchedManifestStaticFilesStorage.url_converter | def url_converter(self, *args, **kwargs):
"""
Return the custom URL converter for the given file name.
"""
upstream_converter = super(PatchedManifestStaticFilesStorage, self).url_converter(*args, **kwargs)
def converter(matchobj):
try:
upstream_conver... | python | def url_converter(self, *args, **kwargs):
"""
Return the custom URL converter for the given file name.
"""
upstream_converter = super(PatchedManifestStaticFilesStorage, self).url_converter(*args, **kwargs)
def converter(matchobj):
try:
upstream_conver... | [
"def",
"url_converter",
"(",
"self",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"upstream_converter",
"=",
"super",
"(",
"PatchedManifestStaticFilesStorage",
",",
"self",
")",
".",
"url_converter",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
"def",
"... | Return the custom URL converter for the given file name. | [
"Return",
"the",
"custom",
"URL",
"converter",
"for",
"the",
"given",
"file",
"name",
"."
] | dbdfa6d06c1077fade729db25b3b137d44299db6 | https://github.com/metakermit/django-spa/blob/dbdfa6d06c1077fade729db25b3b137d44299db6/spa/storage.py#L12-L27 | train |
TriOptima/tri.table | lib/tri/table/__init__.py | order_by_on_list | def order_by_on_list(objects, order_field, is_desc=False):
"""
Utility function to sort objects django-style even for non-query set collections
:param objects: list of objects to sort
:param order_field: field name, follows django conventions, so "foo__bar" means `foo.bar`, can be a callable.
:para... | python | def order_by_on_list(objects, order_field, is_desc=False):
"""
Utility function to sort objects django-style even for non-query set collections
:param objects: list of objects to sort
:param order_field: field name, follows django conventions, so "foo__bar" means `foo.bar`, can be a callable.
:para... | [
"def",
"order_by_on_list",
"(",
"objects",
",",
"order_field",
",",
"is_desc",
"=",
"False",
")",
":",
"if",
"callable",
"(",
"order_field",
")",
":",
"objects",
".",
"sort",
"(",
"key",
"=",
"order_field",
",",
"reverse",
"=",
"is_desc",
")",
"return",
... | Utility function to sort objects django-style even for non-query set collections
:param objects: list of objects to sort
:param order_field: field name, follows django conventions, so "foo__bar" means `foo.bar`, can be a callable.
:param is_desc: reverse the sorting
:return: | [
"Utility",
"function",
"to",
"sort",
"objects",
"django",
"-",
"style",
"even",
"for",
"non",
"-",
"query",
"set",
"collections"
] | fc38c02098a80a3fb336ac4cf502954d74e31484 | https://github.com/TriOptima/tri.table/blob/fc38c02098a80a3fb336ac4cf502954d74e31484/lib/tri/table/__init__.py#L153-L172 | train |
TriOptima/tri.table | lib/tri/table/__init__.py | render_table | def render_table(request,
table,
links=None,
context=None,
template='tri_table/list.html',
blank_on_empty=False,
paginate_by=40, # pragma: no mutate
page=None,
paginator=None,
... | python | def render_table(request,
table,
links=None,
context=None,
template='tri_table/list.html',
blank_on_empty=False,
paginate_by=40, # pragma: no mutate
page=None,
paginator=None,
... | [
"def",
"render_table",
"(",
"request",
",",
"table",
",",
"links",
"=",
"None",
",",
"context",
"=",
"None",
",",
"template",
"=",
"'tri_table/list.html'",
",",
"blank_on_empty",
"=",
"False",
",",
"paginate_by",
"=",
"40",
",",
"page",
"=",
"None",
",",
... | Render a table. This automatically handles pagination, sorting, filtering and bulk operations.
:param request: the request object. This is set on the table object so that it is available for lambda expressions.
:param table: an instance of Table
:param links: a list of instances of Link
:param context:... | [
"Render",
"a",
"table",
".",
"This",
"automatically",
"handles",
"pagination",
"sorting",
"filtering",
"and",
"bulk",
"operations",
"."
] | fc38c02098a80a3fb336ac4cf502954d74e31484 | https://github.com/TriOptima/tri.table/blob/fc38c02098a80a3fb336ac4cf502954d74e31484/lib/tri/table/__init__.py#L1595-L1671 | train |
infobloxopen/infoblox-client | infoblox_client/utils.py | generate_duid | def generate_duid(mac):
"""DUID is consisted of 10 hex numbers.
0x00 + mac with last 3 hex + mac with 6 hex
"""
valid = mac and isinstance(mac, six.string_types)
if not valid:
raise ValueError("Invalid argument was passed")
return "00:" + mac[9:] + ":" + mac | python | def generate_duid(mac):
"""DUID is consisted of 10 hex numbers.
0x00 + mac with last 3 hex + mac with 6 hex
"""
valid = mac and isinstance(mac, six.string_types)
if not valid:
raise ValueError("Invalid argument was passed")
return "00:" + mac[9:] + ":" + mac | [
"def",
"generate_duid",
"(",
"mac",
")",
":",
"valid",
"=",
"mac",
"and",
"isinstance",
"(",
"mac",
",",
"six",
".",
"string_types",
")",
"if",
"not",
"valid",
":",
"raise",
"ValueError",
"(",
"\"Invalid argument was passed\"",
")",
"return",
"\"00:\"",
"+",... | DUID is consisted of 10 hex numbers.
0x00 + mac with last 3 hex + mac with 6 hex | [
"DUID",
"is",
"consisted",
"of",
"10",
"hex",
"numbers",
"."
] | edeec62db1935784c728731b2ae7cf0fcc9bf84d | https://github.com/infobloxopen/infoblox-client/blob/edeec62db1935784c728731b2ae7cf0fcc9bf84d/infoblox_client/utils.py#L41-L49 | train |
infobloxopen/infoblox-client | infoblox_client/utils.py | try_value_to_bool | def try_value_to_bool(value, strict_mode=True):
"""Tries to convert value into boolean.
strict_mode is True:
- Only string representation of str(True) and str(False)
are converted into booleans;
- Otherwise unchanged incoming value is returned;
strict_mode is False:
- Anything that looks... | python | def try_value_to_bool(value, strict_mode=True):
"""Tries to convert value into boolean.
strict_mode is True:
- Only string representation of str(True) and str(False)
are converted into booleans;
- Otherwise unchanged incoming value is returned;
strict_mode is False:
- Anything that looks... | [
"def",
"try_value_to_bool",
"(",
"value",
",",
"strict_mode",
"=",
"True",
")",
":",
"if",
"strict_mode",
":",
"true_list",
"=",
"(",
"'True'",
",",
")",
"false_list",
"=",
"(",
"'False'",
",",
")",
"val",
"=",
"value",
"else",
":",
"true_list",
"=",
"... | Tries to convert value into boolean.
strict_mode is True:
- Only string representation of str(True) and str(False)
are converted into booleans;
- Otherwise unchanged incoming value is returned;
strict_mode is False:
- Anything that looks like True or False is converted into booleans.
Val... | [
"Tries",
"to",
"convert",
"value",
"into",
"boolean",
"."
] | edeec62db1935784c728731b2ae7cf0fcc9bf84d | https://github.com/infobloxopen/infoblox-client/blob/edeec62db1935784c728731b2ae7cf0fcc9bf84d/infoblox_client/utils.py#L85-L114 | train |
infobloxopen/infoblox-client | infoblox_client/object_manager.py | InfobloxObjectManager.create_network | def create_network(self, net_view_name, cidr, nameservers=None,
members=None, gateway_ip=None, dhcp_trel_ip=None,
network_extattrs=None):
"""Create NIOS Network and prepare DHCP options.
Some DHCP options are valid for IPv4 only, so just skip processing
... | python | def create_network(self, net_view_name, cidr, nameservers=None,
members=None, gateway_ip=None, dhcp_trel_ip=None,
network_extattrs=None):
"""Create NIOS Network and prepare DHCP options.
Some DHCP options are valid for IPv4 only, so just skip processing
... | [
"def",
"create_network",
"(",
"self",
",",
"net_view_name",
",",
"cidr",
",",
"nameservers",
"=",
"None",
",",
"members",
"=",
"None",
",",
"gateway_ip",
"=",
"None",
",",
"dhcp_trel_ip",
"=",
"None",
",",
"network_extattrs",
"=",
"None",
")",
":",
"ipv4",... | Create NIOS Network and prepare DHCP options.
Some DHCP options are valid for IPv4 only, so just skip processing
them for IPv6 case.
:param net_view_name: network view name
:param cidr: network to allocate, example '172.23.23.0/24'
:param nameservers: list of name servers hosts... | [
"Create",
"NIOS",
"Network",
"and",
"prepare",
"DHCP",
"options",
"."
] | edeec62db1935784c728731b2ae7cf0fcc9bf84d | https://github.com/infobloxopen/infoblox-client/blob/edeec62db1935784c728731b2ae7cf0fcc9bf84d/infoblox_client/object_manager.py#L58-L96 | train |
infobloxopen/infoblox-client | infoblox_client/object_manager.py | InfobloxObjectManager.create_ip_range | def create_ip_range(self, network_view, start_ip, end_ip, network,
disable, range_extattrs):
"""Creates IPRange or fails if already exists."""
return obj.IPRange.create(self.connector,
network_view=network_view,
... | python | def create_ip_range(self, network_view, start_ip, end_ip, network,
disable, range_extattrs):
"""Creates IPRange or fails if already exists."""
return obj.IPRange.create(self.connector,
network_view=network_view,
... | [
"def",
"create_ip_range",
"(",
"self",
",",
"network_view",
",",
"start_ip",
",",
"end_ip",
",",
"network",
",",
"disable",
",",
"range_extattrs",
")",
":",
"return",
"obj",
".",
"IPRange",
".",
"create",
"(",
"self",
".",
"connector",
",",
"network_view",
... | Creates IPRange or fails if already exists. | [
"Creates",
"IPRange",
"or",
"fails",
"if",
"already",
"exists",
"."
] | edeec62db1935784c728731b2ae7cf0fcc9bf84d | https://github.com/infobloxopen/infoblox-client/blob/edeec62db1935784c728731b2ae7cf0fcc9bf84d/infoblox_client/object_manager.py#L103-L113 | train |
infobloxopen/infoblox-client | infoblox_client/connector.py | Connector._parse_options | def _parse_options(self, options):
"""Copy needed options to self"""
attributes = ('host', 'wapi_version', 'username', 'password',
'ssl_verify', 'http_request_timeout', 'max_retries',
'http_pool_connections', 'http_pool_maxsize',
'silent_... | python | def _parse_options(self, options):
"""Copy needed options to self"""
attributes = ('host', 'wapi_version', 'username', 'password',
'ssl_verify', 'http_request_timeout', 'max_retries',
'http_pool_connections', 'http_pool_maxsize',
'silent_... | [
"def",
"_parse_options",
"(",
"self",
",",
"options",
")",
":",
"attributes",
"=",
"(",
"'host'",
",",
"'wapi_version'",
",",
"'username'",
",",
"'password'",
",",
"'ssl_verify'",
",",
"'http_request_timeout'",
",",
"'max_retries'",
",",
"'http_pool_connections'",
... | Copy needed options to self | [
"Copy",
"needed",
"options",
"to",
"self"
] | edeec62db1935784c728731b2ae7cf0fcc9bf84d | https://github.com/infobloxopen/infoblox-client/blob/edeec62db1935784c728731b2ae7cf0fcc9bf84d/infoblox_client/connector.py#L89-L115 | train |
infobloxopen/infoblox-client | infoblox_client/connector.py | Connector._parse_reply | def _parse_reply(request):
"""Tries to parse reply from NIOS.
Raises exception with content if reply is not in json format
"""
try:
return jsonutils.loads(request.content)
except ValueError:
raise ib_ex.InfobloxConnectionError(reason=request.content) | python | def _parse_reply(request):
"""Tries to parse reply from NIOS.
Raises exception with content if reply is not in json format
"""
try:
return jsonutils.loads(request.content)
except ValueError:
raise ib_ex.InfobloxConnectionError(reason=request.content) | [
"def",
"_parse_reply",
"(",
"request",
")",
":",
"try",
":",
"return",
"jsonutils",
".",
"loads",
"(",
"request",
".",
"content",
")",
"except",
"ValueError",
":",
"raise",
"ib_ex",
".",
"InfobloxConnectionError",
"(",
"reason",
"=",
"request",
".",
"content... | Tries to parse reply from NIOS.
Raises exception with content if reply is not in json format | [
"Tries",
"to",
"parse",
"reply",
"from",
"NIOS",
"."
] | edeec62db1935784c728731b2ae7cf0fcc9bf84d | https://github.com/infobloxopen/infoblox-client/blob/edeec62db1935784c728731b2ae7cf0fcc9bf84d/infoblox_client/connector.py#L212-L220 | train |
infobloxopen/infoblox-client | infoblox_client/connector.py | Connector.get_object | def get_object(self, obj_type, payload=None, return_fields=None,
extattrs=None, force_proxy=False, max_results=None,
paging=False):
"""Retrieve a list of Infoblox objects of type 'obj_type'
Some get requests like 'ipv4address' should be always
proxied to GM... | python | def get_object(self, obj_type, payload=None, return_fields=None,
extattrs=None, force_proxy=False, max_results=None,
paging=False):
"""Retrieve a list of Infoblox objects of type 'obj_type'
Some get requests like 'ipv4address' should be always
proxied to GM... | [
"def",
"get_object",
"(",
"self",
",",
"obj_type",
",",
"payload",
"=",
"None",
",",
"return_fields",
"=",
"None",
",",
"extattrs",
"=",
"None",
",",
"force_proxy",
"=",
"False",
",",
"max_results",
"=",
"None",
",",
"paging",
"=",
"False",
")",
":",
"... | Retrieve a list of Infoblox objects of type 'obj_type'
Some get requests like 'ipv4address' should be always
proxied to GM on Hellfire
If request is cloud and proxy is not forced yet,
then plan to do 2 request:
- the first one is not proxied to GM
- the second is proxied... | [
"Retrieve",
"a",
"list",
"of",
"Infoblox",
"objects",
"of",
"type",
"obj_type"
] | edeec62db1935784c728731b2ae7cf0fcc9bf84d | https://github.com/infobloxopen/infoblox-client/blob/edeec62db1935784c728731b2ae7cf0fcc9bf84d/infoblox_client/connector.py#L231-L293 | train |
infobloxopen/infoblox-client | infoblox_client/connector.py | Connector.create_object | def create_object(self, obj_type, payload, return_fields=None):
"""Create an Infoblox object of type 'obj_type'
Args:
obj_type (str): Infoblox object type,
e.g. 'network', 'range', etc.
payload (dict): Payload with data to send
... | python | def create_object(self, obj_type, payload, return_fields=None):
"""Create an Infoblox object of type 'obj_type'
Args:
obj_type (str): Infoblox object type,
e.g. 'network', 'range', etc.
payload (dict): Payload with data to send
... | [
"def",
"create_object",
"(",
"self",
",",
"obj_type",
",",
"payload",
",",
"return_fields",
"=",
"None",
")",
":",
"self",
".",
"_validate_obj_type_or_die",
"(",
"obj_type",
")",
"query_params",
"=",
"self",
".",
"_build_query_params",
"(",
"return_fields",
"=",... | Create an Infoblox object of type 'obj_type'
Args:
obj_type (str): Infoblox object type,
e.g. 'network', 'range', etc.
payload (dict): Payload with data to send
return_fields (list): List of fields to be returned
Returns... | [
"Create",
"an",
"Infoblox",
"object",
"of",
"type",
"obj_type"
] | edeec62db1935784c728731b2ae7cf0fcc9bf84d | https://github.com/infobloxopen/infoblox-client/blob/edeec62db1935784c728731b2ae7cf0fcc9bf84d/infoblox_client/connector.py#L345-L387 | train |
infobloxopen/infoblox-client | infoblox_client/connector.py | Connector.update_object | def update_object(self, ref, payload, return_fields=None):
"""Update an Infoblox object
Args:
ref (str): Infoblox object reference
payload (dict): Payload with data to send
Returns:
The object reference of the updated object
Raises:
I... | python | def update_object(self, ref, payload, return_fields=None):
"""Update an Infoblox object
Args:
ref (str): Infoblox object reference
payload (dict): Payload with data to send
Returns:
The object reference of the updated object
Raises:
I... | [
"def",
"update_object",
"(",
"self",
",",
"ref",
",",
"payload",
",",
"return_fields",
"=",
"None",
")",
":",
"query_params",
"=",
"self",
".",
"_build_query_params",
"(",
"return_fields",
"=",
"return_fields",
")",
"opts",
"=",
"self",
".",
"_get_request_opti... | Update an Infoblox object
Args:
ref (str): Infoblox object reference
payload (dict): Payload with data to send
Returns:
The object reference of the updated object
Raises:
InfobloxException | [
"Update",
"an",
"Infoblox",
"object"
] | edeec62db1935784c728731b2ae7cf0fcc9bf84d | https://github.com/infobloxopen/infoblox-client/blob/edeec62db1935784c728731b2ae7cf0fcc9bf84d/infoblox_client/connector.py#L424-L453 | train |
infobloxopen/infoblox-client | infoblox_client/connector.py | Connector.delete_object | def delete_object(self, ref, delete_arguments=None):
"""Remove an Infoblox object
Args:
ref (str): Object reference
delete_arguments (dict): Extra delete arguments
Returns:
The object reference of the removed object
Raises:
I... | python | def delete_object(self, ref, delete_arguments=None):
"""Remove an Infoblox object
Args:
ref (str): Object reference
delete_arguments (dict): Extra delete arguments
Returns:
The object reference of the removed object
Raises:
I... | [
"def",
"delete_object",
"(",
"self",
",",
"ref",
",",
"delete_arguments",
"=",
"None",
")",
":",
"opts",
"=",
"self",
".",
"_get_request_options",
"(",
")",
"if",
"not",
"isinstance",
"(",
"delete_arguments",
",",
"dict",
")",
":",
"delete_arguments",
"=",
... | Remove an Infoblox object
Args:
ref (str): Object reference
delete_arguments (dict): Extra delete arguments
Returns:
The object reference of the removed object
Raises:
InfobloxException | [
"Remove",
"an",
"Infoblox",
"object"
] | edeec62db1935784c728731b2ae7cf0fcc9bf84d | https://github.com/infobloxopen/infoblox-client/blob/edeec62db1935784c728731b2ae7cf0fcc9bf84d/infoblox_client/connector.py#L456-L485 | train |
infobloxopen/infoblox-client | infoblox_client/objects.py | BaseObject._remap_fields | def _remap_fields(cls, kwargs):
"""Map fields from kwargs into dict acceptable by NIOS"""
mapped = {}
for key in kwargs:
if key in cls._remap:
mapped[cls._remap[key]] = kwargs[key]
else:
mapped[key] = kwargs[key]
return mapped | python | def _remap_fields(cls, kwargs):
"""Map fields from kwargs into dict acceptable by NIOS"""
mapped = {}
for key in kwargs:
if key in cls._remap:
mapped[cls._remap[key]] = kwargs[key]
else:
mapped[key] = kwargs[key]
return mapped | [
"def",
"_remap_fields",
"(",
"cls",
",",
"kwargs",
")",
":",
"mapped",
"=",
"{",
"}",
"for",
"key",
"in",
"kwargs",
":",
"if",
"key",
"in",
"cls",
".",
"_remap",
":",
"mapped",
"[",
"cls",
".",
"_remap",
"[",
"key",
"]",
"]",
"=",
"kwargs",
"[",
... | Map fields from kwargs into dict acceptable by NIOS | [
"Map",
"fields",
"from",
"kwargs",
"into",
"dict",
"acceptable",
"by",
"NIOS"
] | edeec62db1935784c728731b2ae7cf0fcc9bf84d | https://github.com/infobloxopen/infoblox-client/blob/edeec62db1935784c728731b2ae7cf0fcc9bf84d/infoblox_client/objects.py#L87-L95 | train |
infobloxopen/infoblox-client | infoblox_client/objects.py | EA.from_dict | def from_dict(cls, eas_from_nios):
"""Converts extensible attributes from the NIOS reply."""
if not eas_from_nios:
return
return cls({name: cls._process_value(ib_utils.try_value_to_bool,
eas_from_nios[name]['value'])
fo... | python | def from_dict(cls, eas_from_nios):
"""Converts extensible attributes from the NIOS reply."""
if not eas_from_nios:
return
return cls({name: cls._process_value(ib_utils.try_value_to_bool,
eas_from_nios[name]['value'])
fo... | [
"def",
"from_dict",
"(",
"cls",
",",
"eas_from_nios",
")",
":",
"if",
"not",
"eas_from_nios",
":",
"return",
"return",
"cls",
"(",
"{",
"name",
":",
"cls",
".",
"_process_value",
"(",
"ib_utils",
".",
"try_value_to_bool",
",",
"eas_from_nios",
"[",
"name",
... | Converts extensible attributes from the NIOS reply. | [
"Converts",
"extensible",
"attributes",
"from",
"the",
"NIOS",
"reply",
"."
] | edeec62db1935784c728731b2ae7cf0fcc9bf84d | https://github.com/infobloxopen/infoblox-client/blob/edeec62db1935784c728731b2ae7cf0fcc9bf84d/infoblox_client/objects.py#L141-L147 | train |
infobloxopen/infoblox-client | infoblox_client/objects.py | EA.to_dict | def to_dict(self):
"""Converts extensible attributes into the format suitable for NIOS."""
return {name: {'value': self._process_value(str, value)}
for name, value in self._ea_dict.items()
if not (value is None or value == "" or value == [])} | python | def to_dict(self):
"""Converts extensible attributes into the format suitable for NIOS."""
return {name: {'value': self._process_value(str, value)}
for name, value in self._ea_dict.items()
if not (value is None or value == "" or value == [])} | [
"def",
"to_dict",
"(",
"self",
")",
":",
"return",
"{",
"name",
":",
"{",
"'value'",
":",
"self",
".",
"_process_value",
"(",
"str",
",",
"value",
")",
"}",
"for",
"name",
",",
"value",
"in",
"self",
".",
"_ea_dict",
".",
"items",
"(",
")",
"if",
... | Converts extensible attributes into the format suitable for NIOS. | [
"Converts",
"extensible",
"attributes",
"into",
"the",
"format",
"suitable",
"for",
"NIOS",
"."
] | edeec62db1935784c728731b2ae7cf0fcc9bf84d | https://github.com/infobloxopen/infoblox-client/blob/edeec62db1935784c728731b2ae7cf0fcc9bf84d/infoblox_client/objects.py#L149-L153 | train |
infobloxopen/infoblox-client | infoblox_client/objects.py | EA._process_value | def _process_value(func, value):
"""Applies processing method for value or each element in it.
:param func: method to be called with value
:param value: value to process
:return: if 'value' is list/tupe, returns iterable with func results,
else func result is returned
... | python | def _process_value(func, value):
"""Applies processing method for value or each element in it.
:param func: method to be called with value
:param value: value to process
:return: if 'value' is list/tupe, returns iterable with func results,
else func result is returned
... | [
"def",
"_process_value",
"(",
"func",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"return",
"[",
"func",
"(",
"item",
")",
"for",
"item",
"in",
"value",
"]",
"return",
"func",
"(",
"value... | Applies processing method for value or each element in it.
:param func: method to be called with value
:param value: value to process
:return: if 'value' is list/tupe, returns iterable with func results,
else func result is returned | [
"Applies",
"processing",
"method",
"for",
"value",
"or",
"each",
"element",
"in",
"it",
"."
] | edeec62db1935784c728731b2ae7cf0fcc9bf84d | https://github.com/infobloxopen/infoblox-client/blob/edeec62db1935784c728731b2ae7cf0fcc9bf84d/infoblox_client/objects.py#L156-L166 | train |
infobloxopen/infoblox-client | infoblox_client/objects.py | InfobloxObject.from_dict | def from_dict(cls, connector, ip_dict):
"""Build dict fields as SubObjects if needed.
Checks if lambda for building object from dict exists.
_global_field_processing and _custom_field_processing rules
are checked.
"""
mapping = cls._global_field_processing.copy()
... | python | def from_dict(cls, connector, ip_dict):
"""Build dict fields as SubObjects if needed.
Checks if lambda for building object from dict exists.
_global_field_processing and _custom_field_processing rules
are checked.
"""
mapping = cls._global_field_processing.copy()
... | [
"def",
"from_dict",
"(",
"cls",
",",
"connector",
",",
"ip_dict",
")",
":",
"mapping",
"=",
"cls",
".",
"_global_field_processing",
".",
"copy",
"(",
")",
"mapping",
".",
"update",
"(",
"cls",
".",
"_custom_field_processing",
")",
"for",
"field",
"in",
"ma... | Build dict fields as SubObjects if needed.
Checks if lambda for building object from dict exists.
_global_field_processing and _custom_field_processing rules
are checked. | [
"Build",
"dict",
"fields",
"as",
"SubObjects",
"if",
"needed",
"."
] | edeec62db1935784c728731b2ae7cf0fcc9bf84d | https://github.com/infobloxopen/infoblox-client/blob/edeec62db1935784c728731b2ae7cf0fcc9bf84d/infoblox_client/objects.py#L243-L256 | train |
infobloxopen/infoblox-client | infoblox_client/objects.py | InfobloxObject.field_to_dict | def field_to_dict(self, field):
"""Read field value and converts to dict if possible"""
value = getattr(self, field)
if isinstance(value, (list, tuple)):
return [self.value_to_dict(val) for val in value]
return self.value_to_dict(value) | python | def field_to_dict(self, field):
"""Read field value and converts to dict if possible"""
value = getattr(self, field)
if isinstance(value, (list, tuple)):
return [self.value_to_dict(val) for val in value]
return self.value_to_dict(value) | [
"def",
"field_to_dict",
"(",
"self",
",",
"field",
")",
":",
"value",
"=",
"getattr",
"(",
"self",
",",
"field",
")",
"if",
"isinstance",
"(",
"value",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"return",
"[",
"self",
".",
"value_to_dict",
"(",
... | Read field value and converts to dict if possible | [
"Read",
"field",
"value",
"and",
"converts",
"to",
"dict",
"if",
"possible"
] | edeec62db1935784c728731b2ae7cf0fcc9bf84d | https://github.com/infobloxopen/infoblox-client/blob/edeec62db1935784c728731b2ae7cf0fcc9bf84d/infoblox_client/objects.py#L262-L267 | train |
infobloxopen/infoblox-client | infoblox_client/objects.py | InfobloxObject.to_dict | def to_dict(self, search_fields=None):
"""Builds dict without None object fields"""
fields = self._fields
if search_fields == 'update':
fields = self._search_for_update_fields
elif search_fields == 'all':
fields = self._all_searchable_fields
elif search_fi... | python | def to_dict(self, search_fields=None):
"""Builds dict without None object fields"""
fields = self._fields
if search_fields == 'update':
fields = self._search_for_update_fields
elif search_fields == 'all':
fields = self._all_searchable_fields
elif search_fi... | [
"def",
"to_dict",
"(",
"self",
",",
"search_fields",
"=",
"None",
")",
":",
"fields",
"=",
"self",
".",
"_fields",
"if",
"search_fields",
"==",
"'update'",
":",
"fields",
"=",
"self",
".",
"_search_for_update_fields",
"elif",
"search_fields",
"==",
"'all'",
... | Builds dict without None object fields | [
"Builds",
"dict",
"without",
"None",
"object",
"fields"
] | edeec62db1935784c728731b2ae7cf0fcc9bf84d | https://github.com/infobloxopen/infoblox-client/blob/edeec62db1935784c728731b2ae7cf0fcc9bf84d/infoblox_client/objects.py#L269-L284 | train |
infobloxopen/infoblox-client | infoblox_client/objects.py | InfobloxObject.fetch | def fetch(self, only_ref=False):
"""Fetch object from NIOS by _ref or searchfields
Update existent object with fields returned from NIOS
Return True on successful object fetch
"""
if self.ref:
reply = self.connector.get_object(
self.ref, return_fields... | python | def fetch(self, only_ref=False):
"""Fetch object from NIOS by _ref or searchfields
Update existent object with fields returned from NIOS
Return True on successful object fetch
"""
if self.ref:
reply = self.connector.get_object(
self.ref, return_fields... | [
"def",
"fetch",
"(",
"self",
",",
"only_ref",
"=",
"False",
")",
":",
"if",
"self",
".",
"ref",
":",
"reply",
"=",
"self",
".",
"connector",
".",
"get_object",
"(",
"self",
".",
"ref",
",",
"return_fields",
"=",
"self",
".",
"return_fields",
")",
"if... | Fetch object from NIOS by _ref or searchfields
Update existent object with fields returned from NIOS
Return True on successful object fetch | [
"Fetch",
"object",
"from",
"NIOS",
"by",
"_ref",
"or",
"searchfields"
] | edeec62db1935784c728731b2ae7cf0fcc9bf84d | https://github.com/infobloxopen/infoblox-client/blob/edeec62db1935784c728731b2ae7cf0fcc9bf84d/infoblox_client/objects.py#L378-L399 | train |
infobloxopen/infoblox-client | infoblox_client/objects.py | HostRecord._ip_setter | def _ip_setter(self, ipaddr_name, ipaddrs_name, ips):
"""Setter for ip fields
Accept as input string or list of IP instances.
String case:
only ipvXaddr is going to be filled, that is enough to perform
host record search using ip
List of IP instances case:
... | python | def _ip_setter(self, ipaddr_name, ipaddrs_name, ips):
"""Setter for ip fields
Accept as input string or list of IP instances.
String case:
only ipvXaddr is going to be filled, that is enough to perform
host record search using ip
List of IP instances case:
... | [
"def",
"_ip_setter",
"(",
"self",
",",
"ipaddr_name",
",",
"ipaddrs_name",
",",
"ips",
")",
":",
"if",
"isinstance",
"(",
"ips",
",",
"six",
".",
"string_types",
")",
":",
"setattr",
"(",
"self",
",",
"ipaddr_name",
",",
"ips",
")",
"elif",
"isinstance",... | Setter for ip fields
Accept as input string or list of IP instances.
String case:
only ipvXaddr is going to be filled, that is enough to perform
host record search using ip
List of IP instances case:
ipvXaddrs is going to be filled with ips content,
... | [
"Setter",
"for",
"ip",
"fields"
] | edeec62db1935784c728731b2ae7cf0fcc9bf84d | https://github.com/infobloxopen/infoblox-client/blob/edeec62db1935784c728731b2ae7cf0fcc9bf84d/infoblox_client/objects.py#L527-L554 | train |
infobloxopen/infoblox-client | infoblox_client/objects.py | FixedAddressV6.mac | def mac(self, mac):
"""Set mac and duid fields
To have common interface with FixedAddress accept mac address
and set duid as a side effect.
'mac' was added to _shadow_fields to prevent sending it out over wapi.
"""
self._mac = mac
if mac:
self.duid = ... | python | def mac(self, mac):
"""Set mac and duid fields
To have common interface with FixedAddress accept mac address
and set duid as a side effect.
'mac' was added to _shadow_fields to prevent sending it out over wapi.
"""
self._mac = mac
if mac:
self.duid = ... | [
"def",
"mac",
"(",
"self",
",",
"mac",
")",
":",
"self",
".",
"_mac",
"=",
"mac",
"if",
"mac",
":",
"self",
".",
"duid",
"=",
"ib_utils",
".",
"generate_duid",
"(",
"mac",
")",
"elif",
"not",
"hasattr",
"(",
"self",
",",
"'duid'",
")",
":",
"self... | Set mac and duid fields
To have common interface with FixedAddress accept mac address
and set duid as a side effect.
'mac' was added to _shadow_fields to prevent sending it out over wapi. | [
"Set",
"mac",
"and",
"duid",
"fields"
] | edeec62db1935784c728731b2ae7cf0fcc9bf84d | https://github.com/infobloxopen/infoblox-client/blob/edeec62db1935784c728731b2ae7cf0fcc9bf84d/infoblox_client/objects.py#L821-L832 | train |
cf-platform-eng/tile-generator | tile_generator/template.py | render_property | def render_property(property):
"""Render a property for bosh manifest, according to its type."""
# This ain't the prettiest thing, but it should get the job done.
# I don't think we have anything more elegant available at bosh-manifest-generation time.
# See https://docs.pivotal.io/partners/product-template-referen... | python | def render_property(property):
"""Render a property for bosh manifest, according to its type."""
# This ain't the prettiest thing, but it should get the job done.
# I don't think we have anything more elegant available at bosh-manifest-generation time.
# See https://docs.pivotal.io/partners/product-template-referen... | [
"def",
"render_property",
"(",
"property",
")",
":",
"if",
"'type'",
"in",
"property",
"and",
"property",
"[",
"'type'",
"]",
"in",
"PROPERTY_FIELDS",
":",
"fields",
"=",
"{",
"}",
"for",
"field",
"in",
"PROPERTY_FIELDS",
"[",
"property",
"[",
"'type'",
"]... | Render a property for bosh manifest, according to its type. | [
"Render",
"a",
"property",
"for",
"bosh",
"manifest",
"according",
"to",
"its",
"type",
"."
] | 56b602334edb38639bc7e01b1e9e68e43f9e6828 | https://github.com/cf-platform-eng/tile-generator/blob/56b602334edb38639bc7e01b1e9e68e43f9e6828/tile_generator/template.py#L152-L170 | train |
h2non/filetype.py | filetype/match.py | match | def match(obj, matchers=TYPES):
"""
Matches the given input againts the available
file type matchers.
Args:
obj: path to file, bytes or bytearray.
Returns:
Type instance if type matches. Otherwise None.
Raises:
TypeError: if obj is not a supported type.
"""
buf... | python | def match(obj, matchers=TYPES):
"""
Matches the given input againts the available
file type matchers.
Args:
obj: path to file, bytes or bytearray.
Returns:
Type instance if type matches. Otherwise None.
Raises:
TypeError: if obj is not a supported type.
"""
buf... | [
"def",
"match",
"(",
"obj",
",",
"matchers",
"=",
"TYPES",
")",
":",
"buf",
"=",
"get_bytes",
"(",
"obj",
")",
"for",
"matcher",
"in",
"matchers",
":",
"if",
"matcher",
".",
"match",
"(",
"buf",
")",
":",
"return",
"matcher",
"return",
"None"
] | Matches the given input againts the available
file type matchers.
Args:
obj: path to file, bytes or bytearray.
Returns:
Type instance if type matches. Otherwise None.
Raises:
TypeError: if obj is not a supported type. | [
"Matches",
"the",
"given",
"input",
"againts",
"the",
"available",
"file",
"type",
"matchers",
"."
] | 37e7fd1a9eed1a9eab55ac43f62da98f10970675 | https://github.com/h2non/filetype.py/blob/37e7fd1a9eed1a9eab55ac43f62da98f10970675/filetype/match.py#L14-L34 | train |
h2non/filetype.py | filetype/utils.py | signature | def signature(array):
"""
Returns the first 262 bytes of the given bytearray
as part of the file header signature.
Args:
array: bytearray to extract the header signature.
Returns:
First 262 bytes of the file content as bytearray type.
"""
length = len(array)
index = _NU... | python | def signature(array):
"""
Returns the first 262 bytes of the given bytearray
as part of the file header signature.
Args:
array: bytearray to extract the header signature.
Returns:
First 262 bytes of the file content as bytearray type.
"""
length = len(array)
index = _NU... | [
"def",
"signature",
"(",
"array",
")",
":",
"length",
"=",
"len",
"(",
"array",
")",
"index",
"=",
"_NUM_SIGNATURE_BYTES",
"if",
"length",
">",
"_NUM_SIGNATURE_BYTES",
"else",
"length",
"return",
"array",
"[",
":",
"index",
"]"
] | Returns the first 262 bytes of the given bytearray
as part of the file header signature.
Args:
array: bytearray to extract the header signature.
Returns:
First 262 bytes of the file content as bytearray type. | [
"Returns",
"the",
"first",
"262",
"bytes",
"of",
"the",
"given",
"bytearray",
"as",
"part",
"of",
"the",
"file",
"header",
"signature",
"."
] | 37e7fd1a9eed1a9eab55ac43f62da98f10970675 | https://github.com/h2non/filetype.py/blob/37e7fd1a9eed1a9eab55ac43f62da98f10970675/filetype/utils.py#L21-L35 | train |
h2non/filetype.py | filetype/utils.py | get_bytes | def get_bytes(obj):
"""
Infers the input type and reads the first 262 bytes,
returning a sliced bytearray.
Args:
obj: path to readable, file, bytes or bytearray.
Returns:
First 262 bytes of the file content as bytearray type.
Raises:
TypeError: if obj is not a supporte... | python | def get_bytes(obj):
"""
Infers the input type and reads the first 262 bytes,
returning a sliced bytearray.
Args:
obj: path to readable, file, bytes or bytearray.
Returns:
First 262 bytes of the file content as bytearray type.
Raises:
TypeError: if obj is not a supporte... | [
"def",
"get_bytes",
"(",
"obj",
")",
":",
"try",
":",
"obj",
"=",
"obj",
".",
"read",
"(",
"_NUM_SIGNATURE_BYTES",
")",
"except",
"AttributeError",
":",
"pass",
"kind",
"=",
"type",
"(",
"obj",
")",
"if",
"kind",
"is",
"bytearray",
":",
"return",
"sign... | Infers the input type and reads the first 262 bytes,
returning a sliced bytearray.
Args:
obj: path to readable, file, bytes or bytearray.
Returns:
First 262 bytes of the file content as bytearray type.
Raises:
TypeError: if obj is not a supported type. | [
"Infers",
"the",
"input",
"type",
"and",
"reads",
"the",
"first",
"262",
"bytes",
"returning",
"a",
"sliced",
"bytearray",
"."
] | 37e7fd1a9eed1a9eab55ac43f62da98f10970675 | https://github.com/h2non/filetype.py/blob/37e7fd1a9eed1a9eab55ac43f62da98f10970675/filetype/utils.py#L38-L72 | train |
h2non/filetype.py | filetype/filetype.py | get_type | def get_type(mime=None, ext=None):
"""
Returns the file type instance searching by
MIME type or file extension.
Args:
ext: file extension string. E.g: jpg, png, mp4, mp3
mime: MIME string. E.g: image/jpeg, video/mpeg
Returns:
The matched file type instance. Otherwise None.
... | python | def get_type(mime=None, ext=None):
"""
Returns the file type instance searching by
MIME type or file extension.
Args:
ext: file extension string. E.g: jpg, png, mp4, mp3
mime: MIME string. E.g: image/jpeg, video/mpeg
Returns:
The matched file type instance. Otherwise None.
... | [
"def",
"get_type",
"(",
"mime",
"=",
"None",
",",
"ext",
"=",
"None",
")",
":",
"for",
"kind",
"in",
"types",
":",
"if",
"kind",
".",
"extension",
"is",
"ext",
"or",
"kind",
".",
"mime",
"is",
"mime",
":",
"return",
"kind",
"return",
"None"
] | Returns the file type instance searching by
MIME type or file extension.
Args:
ext: file extension string. E.g: jpg, png, mp4, mp3
mime: MIME string. E.g: image/jpeg, video/mpeg
Returns:
The matched file type instance. Otherwise None. | [
"Returns",
"the",
"file",
"type",
"instance",
"searching",
"by",
"MIME",
"type",
"or",
"file",
"extension",
"."
] | 37e7fd1a9eed1a9eab55ac43f62da98f10970675 | https://github.com/h2non/filetype.py/blob/37e7fd1a9eed1a9eab55ac43f62da98f10970675/filetype/filetype.py#L67-L82 | train |
python-beaver/python-beaver | beaver/worker/tail.py | Tail.open | def open(self, encoding=None):
"""Opens the file with the appropriate call"""
try:
if IS_GZIPPED_FILE.search(self._filename):
_file = gzip.open(self._filename, 'rb')
else:
if encoding:
_file = io.open(self._filename, 'r', encodi... | python | def open(self, encoding=None):
"""Opens the file with the appropriate call"""
try:
if IS_GZIPPED_FILE.search(self._filename):
_file = gzip.open(self._filename, 'rb')
else:
if encoding:
_file = io.open(self._filename, 'r', encodi... | [
"def",
"open",
"(",
"self",
",",
"encoding",
"=",
"None",
")",
":",
"try",
":",
"if",
"IS_GZIPPED_FILE",
".",
"search",
"(",
"self",
".",
"_filename",
")",
":",
"_file",
"=",
"gzip",
".",
"open",
"(",
"self",
".",
"_filename",
",",
"'rb'",
")",
"el... | Opens the file with the appropriate call | [
"Opens",
"the",
"file",
"with",
"the",
"appropriate",
"call"
] | 93941e968016c5a962dffed9e7a9f6dc1d23236c | https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/worker/tail.py#L79-L96 | train |
python-beaver/python-beaver | beaver/worker/tail.py | Tail.close | def close(self):
"""Closes all currently open file pointers"""
if not self.active:
return
self.active = False
if self._file:
self._file.close()
self._sincedb_update_position(force_update=True)
if self._current_event:
event = '\n'.... | python | def close(self):
"""Closes all currently open file pointers"""
if not self.active:
return
self.active = False
if self._file:
self._file.close()
self._sincedb_update_position(force_update=True)
if self._current_event:
event = '\n'.... | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"active",
":",
"return",
"self",
".",
"active",
"=",
"False",
"if",
"self",
".",
"_file",
":",
"self",
".",
"_file",
".",
"close",
"(",
")",
"self",
".",
"_sincedb_update_position",
"("... | Closes all currently open file pointers | [
"Closes",
"all",
"currently",
"open",
"file",
"pointers"
] | 93941e968016c5a962dffed9e7a9f6dc1d23236c | https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/worker/tail.py#L98-L111 | train |
python-beaver/python-beaver | beaver/worker/tail.py | Tail._ensure_file_is_good | def _ensure_file_is_good(self, current_time):
"""Every N seconds, ensures that the file we are tailing is the file we expect to be tailing"""
if self._last_file_mapping_update and current_time - self._last_file_mapping_update <= self._stat_interval:
return
self._last_file_mapping_up... | python | def _ensure_file_is_good(self, current_time):
"""Every N seconds, ensures that the file we are tailing is the file we expect to be tailing"""
if self._last_file_mapping_update and current_time - self._last_file_mapping_update <= self._stat_interval:
return
self._last_file_mapping_up... | [
"def",
"_ensure_file_is_good",
"(",
"self",
",",
"current_time",
")",
":",
"if",
"self",
".",
"_last_file_mapping_update",
"and",
"current_time",
"-",
"self",
".",
"_last_file_mapping_update",
"<=",
"self",
".",
"_stat_interval",
":",
"return",
"self",
".",
"_last... | Every N seconds, ensures that the file we are tailing is the file we expect to be tailing | [
"Every",
"N",
"seconds",
"ensures",
"that",
"the",
"file",
"we",
"are",
"tailing",
"is",
"the",
"file",
"we",
"expect",
"to",
"be",
"tailing"
] | 93941e968016c5a962dffed9e7a9f6dc1d23236c | https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/worker/tail.py#L197-L232 | train |
python-beaver/python-beaver | beaver/worker/tail.py | Tail._run_pass | def _run_pass(self):
"""Read lines from a file and performs a callback against them"""
while True:
try:
data = self._file.read(4096)
except IOError, e:
if e.errno == errno.ESTALE:
self.active = False
return F... | python | def _run_pass(self):
"""Read lines from a file and performs a callback against them"""
while True:
try:
data = self._file.read(4096)
except IOError, e:
if e.errno == errno.ESTALE:
self.active = False
return F... | [
"def",
"_run_pass",
"(",
"self",
")",
":",
"while",
"True",
":",
"try",
":",
"data",
"=",
"self",
".",
"_file",
".",
"read",
"(",
"4096",
")",
"except",
"IOError",
",",
"e",
":",
"if",
"e",
".",
"errno",
"==",
"errno",
".",
"ESTALE",
":",
"self",... | Read lines from a file and performs a callback against them | [
"Read",
"lines",
"from",
"a",
"file",
"and",
"performs",
"a",
"callback",
"against",
"them"
] | 93941e968016c5a962dffed9e7a9f6dc1d23236c | https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/worker/tail.py#L234-L273 | train |
python-beaver/python-beaver | beaver/worker/tail.py | Tail._sincedb_init | def _sincedb_init(self):
"""Initializes the sincedb schema in an sqlite db"""
if not self._sincedb_path:
return
if not os.path.exists(self._sincedb_path):
self._log_debug('initializing sincedb sqlite schema')
conn = sqlite3.connect(self._sincedb_path, isolati... | python | def _sincedb_init(self):
"""Initializes the sincedb schema in an sqlite db"""
if not self._sincedb_path:
return
if not os.path.exists(self._sincedb_path):
self._log_debug('initializing sincedb sqlite schema')
conn = sqlite3.connect(self._sincedb_path, isolati... | [
"def",
"_sincedb_init",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_sincedb_path",
":",
"return",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"_sincedb_path",
")",
":",
"self",
".",
"_log_debug",
"(",
"'initializing sincedb sqli... | Initializes the sincedb schema in an sqlite db | [
"Initializes",
"the",
"sincedb",
"schema",
"in",
"an",
"sqlite",
"db"
] | 93941e968016c5a962dffed9e7a9f6dc1d23236c | https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/worker/tail.py#L381-L396 | train |
python-beaver/python-beaver | beaver/worker/tail.py | Tail._sincedb_update_position | def _sincedb_update_position(self, lines=0, force_update=False):
"""Retrieves the starting position from the sincedb sql db for a given file
Returns a boolean representing whether or not it updated the record
"""
if not self._sincedb_path:
return False
self._line_cou... | python | def _sincedb_update_position(self, lines=0, force_update=False):
"""Retrieves the starting position from the sincedb sql db for a given file
Returns a boolean representing whether or not it updated the record
"""
if not self._sincedb_path:
return False
self._line_cou... | [
"def",
"_sincedb_update_position",
"(",
"self",
",",
"lines",
"=",
"0",
",",
"force_update",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"_sincedb_path",
":",
"return",
"False",
"self",
".",
"_line_count",
"=",
"self",
".",
"_line_count",
"+",
"lines... | Retrieves the starting position from the sincedb sql db for a given file
Returns a boolean representing whether or not it updated the record | [
"Retrieves",
"the",
"starting",
"position",
"from",
"the",
"sincedb",
"sql",
"db",
"for",
"a",
"given",
"file",
"Returns",
"a",
"boolean",
"representing",
"whether",
"or",
"not",
"it",
"updated",
"the",
"record"
] | 93941e968016c5a962dffed9e7a9f6dc1d23236c | https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/worker/tail.py#L398-L441 | train |
python-beaver/python-beaver | beaver/worker/tail.py | Tail._sincedb_start_position | def _sincedb_start_position(self):
"""Retrieves the starting position from the sincedb sql db
for a given file
"""
if not self._sincedb_path:
return None
self._sincedb_init()
self._log_debug('retrieving start_position from sincedb')
conn = sqlite3.con... | python | def _sincedb_start_position(self):
"""Retrieves the starting position from the sincedb sql db
for a given file
"""
if not self._sincedb_path:
return None
self._sincedb_init()
self._log_debug('retrieving start_position from sincedb')
conn = sqlite3.con... | [
"def",
"_sincedb_start_position",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_sincedb_path",
":",
"return",
"None",
"self",
".",
"_sincedb_init",
"(",
")",
"self",
".",
"_log_debug",
"(",
"'retrieving start_position from sincedb'",
")",
"conn",
"=",
"sqli... | Retrieves the starting position from the sincedb sql db
for a given file | [
"Retrieves",
"the",
"starting",
"position",
"from",
"the",
"sincedb",
"sql",
"db",
"for",
"a",
"given",
"file"
] | 93941e968016c5a962dffed9e7a9f6dc1d23236c | https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/worker/tail.py#L443-L463 | train |
python-beaver/python-beaver | beaver/worker/tail.py | Tail._update_file | def _update_file(self, seek_to_end=True):
"""Open the file for tailing"""
try:
self.close()
self._file = self.open()
except IOError:
pass
else:
if not self._file:
return
self.active = True
try:
... | python | def _update_file(self, seek_to_end=True):
"""Open the file for tailing"""
try:
self.close()
self._file = self.open()
except IOError:
pass
else:
if not self._file:
return
self.active = True
try:
... | [
"def",
"_update_file",
"(",
"self",
",",
"seek_to_end",
"=",
"True",
")",
":",
"try",
":",
"self",
".",
"close",
"(",
")",
"self",
".",
"_file",
"=",
"self",
".",
"open",
"(",
")",
"except",
"IOError",
":",
"pass",
"else",
":",
"if",
"not",
"self",... | Open the file for tailing | [
"Open",
"the",
"file",
"for",
"tailing"
] | 93941e968016c5a962dffed9e7a9f6dc1d23236c | https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/worker/tail.py#L465-L492 | train |
python-beaver/python-beaver | beaver/worker/tail.py | Tail.tail | def tail(self, fname, encoding, window, position=None):
"""Read last N lines from file fname."""
if window <= 0:
raise ValueError('invalid window %r' % window)
encodings = ENCODINGS
if encoding:
encodings = [encoding] + ENCODINGS
for enc in encodings:
... | python | def tail(self, fname, encoding, window, position=None):
"""Read last N lines from file fname."""
if window <= 0:
raise ValueError('invalid window %r' % window)
encodings = ENCODINGS
if encoding:
encodings = [encoding] + ENCODINGS
for enc in encodings:
... | [
"def",
"tail",
"(",
"self",
",",
"fname",
",",
"encoding",
",",
"window",
",",
"position",
"=",
"None",
")",
":",
"if",
"window",
"<=",
"0",
":",
"raise",
"ValueError",
"(",
"'invalid window %r'",
"%",
"window",
")",
"encodings",
"=",
"ENCODINGS",
"if",
... | Read last N lines from file fname. | [
"Read",
"last",
"N",
"lines",
"from",
"file",
"fname",
"."
] | 93941e968016c5a962dffed9e7a9f6dc1d23236c | https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/worker/tail.py#L494-L515 | train |
python-beaver/python-beaver | beaver/transports/__init__.py | create_transport | def create_transport(beaver_config, logger):
"""Creates and returns a transport object"""
transport_str = beaver_config.get('transport')
if '.' not in transport_str:
# allow simple names like 'redis' to load a beaver built-in transport
module_path = 'beaver.transports.%s_transport' % transpo... | python | def create_transport(beaver_config, logger):
"""Creates and returns a transport object"""
transport_str = beaver_config.get('transport')
if '.' not in transport_str:
# allow simple names like 'redis' to load a beaver built-in transport
module_path = 'beaver.transports.%s_transport' % transpo... | [
"def",
"create_transport",
"(",
"beaver_config",
",",
"logger",
")",
":",
"transport_str",
"=",
"beaver_config",
".",
"get",
"(",
"'transport'",
")",
"if",
"'.'",
"not",
"in",
"transport_str",
":",
"module_path",
"=",
"'beaver.transports.%s_transport'",
"%",
"tran... | Creates and returns a transport object | [
"Creates",
"and",
"returns",
"a",
"transport",
"object"
] | 93941e968016c5a962dffed9e7a9f6dc1d23236c | https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/transports/__init__.py#L4-L22 | train |
python-beaver/python-beaver | beaver/worker/tail_manager.py | TailManager.update_files | def update_files(self):
"""Ensures all files are properly loaded.
Detects new files, file removals, file rotation, and truncation.
On non-linux platforms, it will also manually reload the file for tailing.
Note that this hack is necessary because EOF is cached on BSD systems.
"""... | python | def update_files(self):
"""Ensures all files are properly loaded.
Detects new files, file removals, file rotation, and truncation.
On non-linux platforms, it will also manually reload the file for tailing.
Note that this hack is necessary because EOF is cached on BSD systems.
"""... | [
"def",
"update_files",
"(",
"self",
")",
":",
"if",
"self",
".",
"_update_time",
"and",
"int",
"(",
"time",
".",
"time",
"(",
")",
")",
"-",
"self",
".",
"_update_time",
"<",
"self",
".",
"_discover_interval",
":",
"return",
"self",
".",
"_update_time",
... | Ensures all files are properly loaded.
Detects new files, file removals, file rotation, and truncation.
On non-linux platforms, it will also manually reload the file for tailing.
Note that this hack is necessary because EOF is cached on BSD systems. | [
"Ensures",
"all",
"files",
"are",
"properly",
"loaded",
".",
"Detects",
"new",
"files",
"file",
"removals",
"file",
"rotation",
"and",
"truncation",
".",
"On",
"non",
"-",
"linux",
"platforms",
"it",
"will",
"also",
"manually",
"reload",
"the",
"file",
"for"... | 93941e968016c5a962dffed9e7a9f6dc1d23236c | https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/worker/tail_manager.py#L85-L125 | train |
python-beaver/python-beaver | beaver/worker/tail_manager.py | TailManager.close | def close(self, signalnum=None, frame=None):
self._running = False
"""Closes all currently open Tail objects"""
self._log_debug("Closing all tail objects")
self._active = False
for fid in self._tails:
self._tails[fid].close()
for n in range(0,self._number_of_c... | python | def close(self, signalnum=None, frame=None):
self._running = False
"""Closes all currently open Tail objects"""
self._log_debug("Closing all tail objects")
self._active = False
for fid in self._tails:
self._tails[fid].close()
for n in range(0,self._number_of_c... | [
"def",
"close",
"(",
"self",
",",
"signalnum",
"=",
"None",
",",
"frame",
"=",
"None",
")",
":",
"self",
".",
"_running",
"=",
"False",
"self",
".",
"_log_debug",
"(",
"\"Closing all tail objects\"",
")",
"self",
".",
"_active",
"=",
"False",
"for",
"fid... | Closes all currently open Tail objects | [
"Closes",
"all",
"currently",
"open",
"Tail",
"objects"
] | 93941e968016c5a962dffed9e7a9f6dc1d23236c | https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/worker/tail_manager.py#L127-L138 | train |
python-beaver/python-beaver | beaver/utils.py | expand_paths | def expand_paths(path):
"""When given a path with brackets, expands it to return all permutations
of the path with expanded brackets, similar to ant.
>>> expand_paths('../{a,b}/{c,d}')
['../a/c', '../a/d', '../b/c', '../b/d']
>>> expand_paths('../{a,b}/{a,b}.py')
['../a/a.py', '.... | python | def expand_paths(path):
"""When given a path with brackets, expands it to return all permutations
of the path with expanded brackets, similar to ant.
>>> expand_paths('../{a,b}/{c,d}')
['../a/c', '../a/d', '../b/c', '../b/d']
>>> expand_paths('../{a,b}/{a,b}.py')
['../a/a.py', '.... | [
"def",
"expand_paths",
"(",
"path",
")",
":",
"pr",
"=",
"itertools",
".",
"product",
"parts",
"=",
"MAGIC_BRACKETS",
".",
"findall",
"(",
"path",
")",
"if",
"not",
"path",
":",
"return",
"if",
"not",
"parts",
":",
"return",
"[",
"path",
"]",
"permutat... | When given a path with brackets, expands it to return all permutations
of the path with expanded brackets, similar to ant.
>>> expand_paths('../{a,b}/{c,d}')
['../a/c', '../a/d', '../b/c', '../b/d']
>>> expand_paths('../{a,b}/{a,b}.py')
['../a/a.py', '../a/b.py', '../b/a.py', '../b/b... | [
"When",
"given",
"a",
"path",
"with",
"brackets",
"expands",
"it",
"to",
"return",
"all",
"permutations",
"of",
"the",
"path",
"with",
"expanded",
"brackets",
"similar",
"to",
"ant",
"."
] | 93941e968016c5a962dffed9e7a9f6dc1d23236c | https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/utils.py#L147-L171 | train |
python-beaver/python-beaver | beaver/utils.py | multiline_merge | def multiline_merge(lines, current_event, re_after, re_before):
""" Merge multi-line events based.
Some event (like Python trackback or Java stracktrace) spawn
on multiple line. This method will merge them using two
regular expression: regex_after and regex_before.
If a line match ... | python | def multiline_merge(lines, current_event, re_after, re_before):
""" Merge multi-line events based.
Some event (like Python trackback or Java stracktrace) spawn
on multiple line. This method will merge them using two
regular expression: regex_after and regex_before.
If a line match ... | [
"def",
"multiline_merge",
"(",
"lines",
",",
"current_event",
",",
"re_after",
",",
"re_before",
")",
":",
"events",
"=",
"[",
"]",
"for",
"line",
"in",
"lines",
":",
"if",
"re_before",
"and",
"re_before",
".",
"match",
"(",
"line",
")",
":",
"current_ev... | Merge multi-line events based.
Some event (like Python trackback or Java stracktrace) spawn
on multiple line. This method will merge them using two
regular expression: regex_after and regex_before.
If a line match re_after, it will be merged with next line.
If a line match re_... | [
"Merge",
"multi",
"-",
"line",
"events",
"based",
"."
] | 93941e968016c5a962dffed9e7a9f6dc1d23236c | https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/utils.py#L180-L210 | train |
python-beaver/python-beaver | beaver/ssh_tunnel.py | create_ssh_tunnel | def create_ssh_tunnel(beaver_config, logger=None):
"""Returns a BeaverSshTunnel object if the current config requires us to"""
if not beaver_config.use_ssh_tunnel():
return None
logger.info("Proxying transport using through local ssh tunnel")
return BeaverSshTunnel(beaver_config, logger=logger) | python | def create_ssh_tunnel(beaver_config, logger=None):
"""Returns a BeaverSshTunnel object if the current config requires us to"""
if not beaver_config.use_ssh_tunnel():
return None
logger.info("Proxying transport using through local ssh tunnel")
return BeaverSshTunnel(beaver_config, logger=logger) | [
"def",
"create_ssh_tunnel",
"(",
"beaver_config",
",",
"logger",
"=",
"None",
")",
":",
"if",
"not",
"beaver_config",
".",
"use_ssh_tunnel",
"(",
")",
":",
"return",
"None",
"logger",
".",
"info",
"(",
"\"Proxying transport using through local ssh tunnel\"",
")",
... | Returns a BeaverSshTunnel object if the current config requires us to | [
"Returns",
"a",
"BeaverSshTunnel",
"object",
"if",
"the",
"current",
"config",
"requires",
"us",
"to"
] | 93941e968016c5a962dffed9e7a9f6dc1d23236c | https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/ssh_tunnel.py#L10-L16 | train |
python-beaver/python-beaver | beaver/ssh_tunnel.py | BeaverSubprocess.poll | def poll(self):
"""Poll attached subprocess until it is available"""
if self._subprocess is not None:
self._subprocess.poll()
time.sleep(self._beaver_config.get('subprocess_poll_sleep')) | python | def poll(self):
"""Poll attached subprocess until it is available"""
if self._subprocess is not None:
self._subprocess.poll()
time.sleep(self._beaver_config.get('subprocess_poll_sleep')) | [
"def",
"poll",
"(",
"self",
")",
":",
"if",
"self",
".",
"_subprocess",
"is",
"not",
"None",
":",
"self",
".",
"_subprocess",
".",
"poll",
"(",
")",
"time",
".",
"sleep",
"(",
"self",
".",
"_beaver_config",
".",
"get",
"(",
"'subprocess_poll_sleep'",
"... | Poll attached subprocess until it is available | [
"Poll",
"attached",
"subprocess",
"until",
"it",
"is",
"available"
] | 93941e968016c5a962dffed9e7a9f6dc1d23236c | https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/ssh_tunnel.py#L43-L48 | train |
python-beaver/python-beaver | beaver/ssh_tunnel.py | BeaverSubprocess.close | def close(self):
"""Close child subprocess"""
if self._subprocess is not None:
os.killpg(self._subprocess.pid, signal.SIGTERM)
self._subprocess = None | python | def close(self):
"""Close child subprocess"""
if self._subprocess is not None:
os.killpg(self._subprocess.pid, signal.SIGTERM)
self._subprocess = None | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"_subprocess",
"is",
"not",
"None",
":",
"os",
".",
"killpg",
"(",
"self",
".",
"_subprocess",
".",
"pid",
",",
"signal",
".",
"SIGTERM",
")",
"self",
".",
"_subprocess",
"=",
"None"
] | Close child subprocess | [
"Close",
"child",
"subprocess"
] | 93941e968016c5a962dffed9e7a9f6dc1d23236c | https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/ssh_tunnel.py#L50-L54 | train |
python-beaver/python-beaver | beaver/unicode_dammit.py | _to_unicode | def _to_unicode(self, data, encoding, errors='strict'):
'''Given a string and its encoding, decodes the string into Unicode.
%encoding is a string recognized by encodings.aliases'''
# strip Byte Order Mark (if present)
if (len(data) >= 4) and (data[:2] == '\xfe\xff') and (data[2:4] != '\x00\x00'):
... | python | def _to_unicode(self, data, encoding, errors='strict'):
'''Given a string and its encoding, decodes the string into Unicode.
%encoding is a string recognized by encodings.aliases'''
# strip Byte Order Mark (if present)
if (len(data) >= 4) and (data[:2] == '\xfe\xff') and (data[2:4] != '\x00\x00'):
... | [
"def",
"_to_unicode",
"(",
"self",
",",
"data",
",",
"encoding",
",",
"errors",
"=",
"'strict'",
")",
":",
"if",
"(",
"len",
"(",
"data",
")",
">=",
"4",
")",
"and",
"(",
"data",
"[",
":",
"2",
"]",
"==",
"'\\xfe\\xff'",
")",
"and",
"(",
"data",
... | Given a string and its encoding, decodes the string into Unicode.
%encoding is a string recognized by encodings.aliases | [
"Given",
"a",
"string",
"and",
"its",
"encoding",
"decodes",
"the",
"string",
"into",
"Unicode",
".",
"%encoding",
"is",
"a",
"string",
"recognized",
"by",
"encodings",
".",
"aliases"
] | 93941e968016c5a962dffed9e7a9f6dc1d23236c | https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/unicode_dammit.py#L38-L59 | train |
python-beaver/python-beaver | beaver/transports/stomp_transport.py | StompTransport.reconnect | def reconnect(self):
"""Allows reconnection from when a handled
TransportException is thrown"""
try:
self.conn.close()
except Exception,e:
self.logger.warn(e)
self.createConnection()
return True | python | def reconnect(self):
"""Allows reconnection from when a handled
TransportException is thrown"""
try:
self.conn.close()
except Exception,e:
self.logger.warn(e)
self.createConnection()
return True | [
"def",
"reconnect",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"conn",
".",
"close",
"(",
")",
"except",
"Exception",
",",
"e",
":",
"self",
".",
"logger",
".",
"warn",
"(",
"e",
")",
"self",
".",
"createConnection",
"(",
")",
"return",
"True"... | Allows reconnection from when a handled
TransportException is thrown | [
"Allows",
"reconnection",
"from",
"when",
"a",
"handled",
"TransportException",
"is",
"thrown"
] | 93941e968016c5a962dffed9e7a9f6dc1d23236c | https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/transports/stomp_transport.py#L64-L74 | train |
python-beaver/python-beaver | beaver/transports/redis_transport.py | RedisTransport._check_connections | def _check_connections(self):
"""Checks if all configured redis servers are reachable"""
for server in self._servers:
if self._is_reachable(server):
server['down_until'] = 0
else:
server['down_until'] = time.time() + 5 | python | def _check_connections(self):
"""Checks if all configured redis servers are reachable"""
for server in self._servers:
if self._is_reachable(server):
server['down_until'] = 0
else:
server['down_until'] = time.time() + 5 | [
"def",
"_check_connections",
"(",
"self",
")",
":",
"for",
"server",
"in",
"self",
".",
"_servers",
":",
"if",
"self",
".",
"_is_reachable",
"(",
"server",
")",
":",
"server",
"[",
"'down_until'",
"]",
"=",
"0",
"else",
":",
"server",
"[",
"'down_until'"... | Checks if all configured redis servers are reachable | [
"Checks",
"if",
"all",
"configured",
"redis",
"servers",
"are",
"reachable"
] | 93941e968016c5a962dffed9e7a9f6dc1d23236c | https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/transports/redis_transport.py#L38-L45 | train |
python-beaver/python-beaver | beaver/transports/redis_transport.py | RedisTransport._is_reachable | def _is_reachable(self, server):
"""Checks if the given redis server is reachable"""
try:
server['redis'].ping()
return True
except UserWarning:
self._logger.warn('Cannot reach redis server: ' + server['url'])
except Exception:
self._logge... | python | def _is_reachable(self, server):
"""Checks if the given redis server is reachable"""
try:
server['redis'].ping()
return True
except UserWarning:
self._logger.warn('Cannot reach redis server: ' + server['url'])
except Exception:
self._logge... | [
"def",
"_is_reachable",
"(",
"self",
",",
"server",
")",
":",
"try",
":",
"server",
"[",
"'redis'",
"]",
".",
"ping",
"(",
")",
"return",
"True",
"except",
"UserWarning",
":",
"self",
".",
"_logger",
".",
"warn",
"(",
"'Cannot reach redis server: '",
"+",
... | Checks if the given redis server is reachable | [
"Checks",
"if",
"the",
"given",
"redis",
"server",
"is",
"reachable"
] | 93941e968016c5a962dffed9e7a9f6dc1d23236c | https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/transports/redis_transport.py#L47-L58 | train |
python-beaver/python-beaver | beaver/transports/redis_transport.py | RedisTransport.invalidate | def invalidate(self):
"""Invalidates the current transport and disconnects all redis connections"""
super(RedisTransport, self).invalidate()
for server in self._servers:
server['redis'].connection_pool.disconnect()
return False | python | def invalidate(self):
"""Invalidates the current transport and disconnects all redis connections"""
super(RedisTransport, self).invalidate()
for server in self._servers:
server['redis'].connection_pool.disconnect()
return False | [
"def",
"invalidate",
"(",
"self",
")",
":",
"super",
"(",
"RedisTransport",
",",
"self",
")",
".",
"invalidate",
"(",
")",
"for",
"server",
"in",
"self",
".",
"_servers",
":",
"server",
"[",
"'redis'",
"]",
".",
"connection_pool",
".",
"disconnect",
"(",... | Invalidates the current transport and disconnects all redis connections | [
"Invalidates",
"the",
"current",
"transport",
"and",
"disconnects",
"all",
"redis",
"connections"
] | 93941e968016c5a962dffed9e7a9f6dc1d23236c | https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/transports/redis_transport.py#L63-L69 | train |
python-beaver/python-beaver | beaver/transports/redis_transport.py | RedisTransport.callback | def callback(self, filename, lines, **kwargs):
"""Sends log lines to redis servers"""
self._logger.debug('Redis transport called')
timestamp = self.get_timestamp(**kwargs)
if kwargs.get('timestamp', False):
del kwargs['timestamp']
namespaces = self._beaver_config.g... | python | def callback(self, filename, lines, **kwargs):
"""Sends log lines to redis servers"""
self._logger.debug('Redis transport called')
timestamp = self.get_timestamp(**kwargs)
if kwargs.get('timestamp', False):
del kwargs['timestamp']
namespaces = self._beaver_config.g... | [
"def",
"callback",
"(",
"self",
",",
"filename",
",",
"lines",
",",
"**",
"kwargs",
")",
":",
"self",
".",
"_logger",
".",
"debug",
"(",
"'Redis transport called'",
")",
"timestamp",
"=",
"self",
".",
"get_timestamp",
"(",
"**",
"kwargs",
")",
"if",
"kwa... | Sends log lines to redis servers | [
"Sends",
"log",
"lines",
"to",
"redis",
"servers"
] | 93941e968016c5a962dffed9e7a9f6dc1d23236c | https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/transports/redis_transport.py#L71-L112 | train |
python-beaver/python-beaver | beaver/transports/redis_transport.py | RedisTransport._get_next_server | def _get_next_server(self):
"""Returns a valid redis server or raises a TransportException"""
current_try = 0
max_tries = len(self._servers)
while current_try < max_tries:
server_index = self._raise_server_index()
server = self._servers[server_index]
... | python | def _get_next_server(self):
"""Returns a valid redis server or raises a TransportException"""
current_try = 0
max_tries = len(self._servers)
while current_try < max_tries:
server_index = self._raise_server_index()
server = self._servers[server_index]
... | [
"def",
"_get_next_server",
"(",
"self",
")",
":",
"current_try",
"=",
"0",
"max_tries",
"=",
"len",
"(",
"self",
".",
"_servers",
")",
"while",
"current_try",
"<",
"max_tries",
":",
"server_index",
"=",
"self",
".",
"_raise_server_index",
"(",
")",
"server",... | Returns a valid redis server or raises a TransportException | [
"Returns",
"a",
"valid",
"redis",
"server",
"or",
"raises",
"a",
"TransportException"
] | 93941e968016c5a962dffed9e7a9f6dc1d23236c | https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/transports/redis_transport.py#L114-L144 | train |
python-beaver/python-beaver | beaver/transports/redis_transport.py | RedisTransport.valid | def valid(self):
"""Returns whether or not the transport can send data to any redis server"""
valid_servers = 0
for server in self._servers:
if server['down_until'] <= time.time():
valid_servers += 1
return valid_servers > 0 | python | def valid(self):
"""Returns whether or not the transport can send data to any redis server"""
valid_servers = 0
for server in self._servers:
if server['down_until'] <= time.time():
valid_servers += 1
return valid_servers > 0 | [
"def",
"valid",
"(",
"self",
")",
":",
"valid_servers",
"=",
"0",
"for",
"server",
"in",
"self",
".",
"_servers",
":",
"if",
"server",
"[",
"'down_until'",
"]",
"<=",
"time",
".",
"time",
"(",
")",
":",
"valid_servers",
"+=",
"1",
"return",
"valid_serv... | Returns whether or not the transport can send data to any redis server | [
"Returns",
"whether",
"or",
"not",
"the",
"transport",
"can",
"send",
"data",
"to",
"any",
"redis",
"server"
] | 93941e968016c5a962dffed9e7a9f6dc1d23236c | https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/transports/redis_transport.py#L154-L162 | train |
python-beaver/python-beaver | beaver/transports/base_transport.py | BaseTransport.format | def format(self, filename, line, timestamp, **kwargs):
"""Returns a formatted log line"""
line = unicode(line.encode("utf-8"), "utf-8", errors="ignore")
formatter = self._beaver_config.get_field('format', filename)
if formatter not in self._formatters:
formatter = self._defau... | python | def format(self, filename, line, timestamp, **kwargs):
"""Returns a formatted log line"""
line = unicode(line.encode("utf-8"), "utf-8", errors="ignore")
formatter = self._beaver_config.get_field('format', filename)
if formatter not in self._formatters:
formatter = self._defau... | [
"def",
"format",
"(",
"self",
",",
"filename",
",",
"line",
",",
"timestamp",
",",
"**",
"kwargs",
")",
":",
"line",
"=",
"unicode",
"(",
"line",
".",
"encode",
"(",
"\"utf-8\"",
")",
",",
"\"utf-8\"",
",",
"errors",
"=",
"\"ignore\"",
")",
"formatter"... | Returns a formatted log line | [
"Returns",
"a",
"formatted",
"log",
"line"
] | 93941e968016c5a962dffed9e7a9f6dc1d23236c | https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/transports/base_transport.py#L117-L142 | train |
python-beaver/python-beaver | beaver/transports/base_transport.py | BaseTransport.get_timestamp | def get_timestamp(self, **kwargs):
"""Retrieves the timestamp for a given set of data"""
timestamp = kwargs.get('timestamp')
if not timestamp:
now = datetime.datetime.utcnow()
timestamp = now.strftime("%Y-%m-%dT%H:%M:%S") + ".%03d" % (now.microsecond / 1000) + "Z"
... | python | def get_timestamp(self, **kwargs):
"""Retrieves the timestamp for a given set of data"""
timestamp = kwargs.get('timestamp')
if not timestamp:
now = datetime.datetime.utcnow()
timestamp = now.strftime("%Y-%m-%dT%H:%M:%S") + ".%03d" % (now.microsecond / 1000) + "Z"
... | [
"def",
"get_timestamp",
"(",
"self",
",",
"**",
"kwargs",
")",
":",
"timestamp",
"=",
"kwargs",
".",
"get",
"(",
"'timestamp'",
")",
"if",
"not",
"timestamp",
":",
"now",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"timestamp",
"=",
"now... | Retrieves the timestamp for a given set of data | [
"Retrieves",
"the",
"timestamp",
"for",
"a",
"given",
"set",
"of",
"data"
] | 93941e968016c5a962dffed9e7a9f6dc1d23236c | https://github.com/python-beaver/python-beaver/blob/93941e968016c5a962dffed9e7a9f6dc1d23236c/beaver/transports/base_transport.py#L144-L151 | train |
gqmelo/exec-wrappers | exec_wrappers/create_wrappers.py | _make_executable | def _make_executable(path):
"""Make the file at path executable."""
os.chmod(path, os.stat(path).st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH) | python | def _make_executable(path):
"""Make the file at path executable."""
os.chmod(path, os.stat(path).st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH) | [
"def",
"_make_executable",
"(",
"path",
")",
":",
"os",
".",
"chmod",
"(",
"path",
",",
"os",
".",
"stat",
"(",
"path",
")",
".",
"st_mode",
"|",
"stat",
".",
"S_IXUSR",
"|",
"stat",
".",
"S_IXGRP",
"|",
"stat",
".",
"S_IXOTH",
")"
] | Make the file at path executable. | [
"Make",
"the",
"file",
"at",
"path",
"executable",
"."
] | 0faf892a103cf03d005f1dbdc71ca52d279b4e3b | https://github.com/gqmelo/exec-wrappers/blob/0faf892a103cf03d005f1dbdc71ca52d279b4e3b/exec_wrappers/create_wrappers.py#L300-L302 | train |
cmap/cmapPy | cmapPy/pandasGEXpress/subset.py | build_parser | def build_parser():
"""Build argument parser."""
parser = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
# Required args
parser.add_argument("--in_path", "-i", required=True,
help="file p... | python | def build_parser():
"""Build argument parser."""
parser = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
# Required args
parser.add_argument("--in_path", "-i", required=True,
help="file p... | [
"def",
"build_parser",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"__doc__",
",",
"formatter_class",
"=",
"argparse",
".",
"ArgumentDefaultsHelpFormatter",
")",
"parser",
".",
"add_argument",
"(",
"\"--in_path\"",
","... | Build argument parser. | [
"Build",
"argument",
"parser",
"."
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/subset.py#L28-L49 | train |
cmap/cmapPy | cmapPy/pandasGEXpress/subset.py | _read_arg | def _read_arg(arg):
"""
If arg is a list with 1 element that corresponds to a valid file path, use
set_io.grp to read the grp file. Otherwise, check that arg is a list of strings.
Args:
arg (list or None)
Returns:
arg_out (list or None)
"""
# If arg is None, just return it... | python | def _read_arg(arg):
"""
If arg is a list with 1 element that corresponds to a valid file path, use
set_io.grp to read the grp file. Otherwise, check that arg is a list of strings.
Args:
arg (list or None)
Returns:
arg_out (list or None)
"""
# If arg is None, just return it... | [
"def",
"_read_arg",
"(",
"arg",
")",
":",
"if",
"arg",
"is",
"None",
":",
"arg_out",
"=",
"arg",
"else",
":",
"if",
"len",
"(",
"arg",
")",
"==",
"1",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"arg",
"[",
"0",
"]",
")",
":",
"arg_out",
"=... | If arg is a list with 1 element that corresponds to a valid file path, use
set_io.grp to read the grp file. Otherwise, check that arg is a list of strings.
Args:
arg (list or None)
Returns:
arg_out (list or None) | [
"If",
"arg",
"is",
"a",
"list",
"with",
"1",
"element",
"that",
"corresponds",
"to",
"a",
"valid",
"file",
"path",
"use",
"set_io",
".",
"grp",
"to",
"read",
"the",
"grp",
"file",
".",
"Otherwise",
"check",
"that",
"arg",
"is",
"a",
"list",
"of",
"st... | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/subset.py#L94-L121 | train |
cmap/cmapPy | cmapPy/set_io/gmt.py | read | def read(file_path):
""" Read a gmt file at the path specified by file_path.
Args:
file_path (string): path to gmt file
Returns:
gmt (GMT object): list of dicts, where each dict corresponds to one
line of the GMT file
"""
# Read in file
actual_file_path = os.path.e... | python | def read(file_path):
""" Read a gmt file at the path specified by file_path.
Args:
file_path (string): path to gmt file
Returns:
gmt (GMT object): list of dicts, where each dict corresponds to one
line of the GMT file
"""
# Read in file
actual_file_path = os.path.e... | [
"def",
"read",
"(",
"file_path",
")",
":",
"actual_file_path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"file_path",
")",
"with",
"open",
"(",
"actual_file_path",
",",
"'r'",
")",
"as",
"f",
":",
"lines",
"=",
"f",
".",
"readlines",
"(",
")",
... | Read a gmt file at the path specified by file_path.
Args:
file_path (string): path to gmt file
Returns:
gmt (GMT object): list of dicts, where each dict corresponds to one
line of the GMT file | [
"Read",
"a",
"gmt",
"file",
"at",
"the",
"path",
"specified",
"by",
"file_path",
"."
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/set_io/gmt.py#L24-L73 | train |
cmap/cmapPy | cmapPy/set_io/gmt.py | verify_gmt_integrity | def verify_gmt_integrity(gmt):
""" Make sure that set ids are unique.
Args:
gmt (GMT object): list of dicts
Returns:
None
"""
# Verify that set ids are unique
set_ids = [d[SET_IDENTIFIER_FIELD] for d in gmt]
assert len(set(set_ids)) == len(set_ids), (
"Set identif... | python | def verify_gmt_integrity(gmt):
""" Make sure that set ids are unique.
Args:
gmt (GMT object): list of dicts
Returns:
None
"""
# Verify that set ids are unique
set_ids = [d[SET_IDENTIFIER_FIELD] for d in gmt]
assert len(set(set_ids)) == len(set_ids), (
"Set identif... | [
"def",
"verify_gmt_integrity",
"(",
"gmt",
")",
":",
"set_ids",
"=",
"[",
"d",
"[",
"SET_IDENTIFIER_FIELD",
"]",
"for",
"d",
"in",
"gmt",
"]",
"assert",
"len",
"(",
"set",
"(",
"set_ids",
")",
")",
"==",
"len",
"(",
"set_ids",
")",
",",
"(",
"\"Set i... | Make sure that set ids are unique.
Args:
gmt (GMT object): list of dicts
Returns:
None | [
"Make",
"sure",
"that",
"set",
"ids",
"are",
"unique",
"."
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/set_io/gmt.py#L76-L90 | train |
cmap/cmapPy | cmapPy/set_io/gmt.py | write | def write(gmt, out_path):
""" Write a GMT to a text file.
Args:
gmt (GMT object): list of dicts
out_path (string): output path
Returns:
None
"""
with open(out_path, 'w') as f:
for _, each_dict in enumerate(gmt):
f.write(each_dict[SET_IDENTIFIER_FIELD] +... | python | def write(gmt, out_path):
""" Write a GMT to a text file.
Args:
gmt (GMT object): list of dicts
out_path (string): output path
Returns:
None
"""
with open(out_path, 'w') as f:
for _, each_dict in enumerate(gmt):
f.write(each_dict[SET_IDENTIFIER_FIELD] +... | [
"def",
"write",
"(",
"gmt",
",",
"out_path",
")",
":",
"with",
"open",
"(",
"out_path",
",",
"'w'",
")",
"as",
"f",
":",
"for",
"_",
",",
"each_dict",
"in",
"enumerate",
"(",
"gmt",
")",
":",
"f",
".",
"write",
"(",
"each_dict",
"[",
"SET_IDENTIFIE... | Write a GMT to a text file.
Args:
gmt (GMT object): list of dicts
out_path (string): output path
Returns:
None | [
"Write",
"a",
"GMT",
"to",
"a",
"text",
"file",
"."
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/set_io/gmt.py#L93-L109 | train |
cmap/cmapPy | cmapPy/pandasGEXpress/parse_gctx.py | parse | def parse(gctx_file_path, convert_neg_666=True, rid=None, cid=None,
ridx=None, cidx=None, row_meta_only=False, col_meta_only=False, make_multiindex=False):
"""
Primary method of script. Reads in path to a gctx file and parses into GCToo object.
Input:
Mandatory:
- gctx_file_path (... | python | def parse(gctx_file_path, convert_neg_666=True, rid=None, cid=None,
ridx=None, cidx=None, row_meta_only=False, col_meta_only=False, make_multiindex=False):
"""
Primary method of script. Reads in path to a gctx file and parses into GCToo object.
Input:
Mandatory:
- gctx_file_path (... | [
"def",
"parse",
"(",
"gctx_file_path",
",",
"convert_neg_666",
"=",
"True",
",",
"rid",
"=",
"None",
",",
"cid",
"=",
"None",
",",
"ridx",
"=",
"None",
",",
"cidx",
"=",
"None",
",",
"row_meta_only",
"=",
"False",
",",
"col_meta_only",
"=",
"False",
",... | Primary method of script. Reads in path to a gctx file and parses into GCToo object.
Input:
Mandatory:
- gctx_file_path (str): full path to gctx file you want to parse.
Optional:
- convert_neg_666 (bool): whether to convert -666 values to numpy.nan or not
(see Note belo... | [
"Primary",
"method",
"of",
"script",
".",
"Reads",
"in",
"path",
"to",
"a",
"gctx",
"file",
"and",
"parses",
"into",
"GCToo",
"object",
"."
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/parse_gctx.py#L23-L126 | train |
cmap/cmapPy | cmapPy/pandasGEXpress/parse_gctx.py | check_id_idx_exclusivity | def check_id_idx_exclusivity(id, idx):
"""
Makes sure user didn't provide both ids and idx values to subset by.
Input:
- id (list or None): if not None, a list of string id names
- idx (list or None): if not None, a list of integer id indexes
Output:
- a tuple: first element is... | python | def check_id_idx_exclusivity(id, idx):
"""
Makes sure user didn't provide both ids and idx values to subset by.
Input:
- id (list or None): if not None, a list of string id names
- idx (list or None): if not None, a list of integer id indexes
Output:
- a tuple: first element is... | [
"def",
"check_id_idx_exclusivity",
"(",
"id",
",",
"idx",
")",
":",
"if",
"(",
"id",
"is",
"not",
"None",
"and",
"idx",
"is",
"not",
"None",
")",
":",
"msg",
"=",
"(",
"\"'id' and 'idx' fields can't both not be None,\"",
"+",
"\" please specify subset in only one ... | Makes sure user didn't provide both ids and idx values to subset by.
Input:
- id (list or None): if not None, a list of string id names
- idx (list or None): if not None, a list of integer id indexes
Output:
- a tuple: first element is subset type, second is subset content | [
"Makes",
"sure",
"user",
"didn",
"t",
"provide",
"both",
"ids",
"and",
"idx",
"values",
"to",
"subset",
"by",
"."
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/parse_gctx.py#L151-L172 | train |
cmap/cmapPy | cmapPy/pandasGEXpress/parse_gctx.py | parse_data_df | def parse_data_df(data_dset, ridx, cidx, row_meta, col_meta):
"""
Parses in data_df from hdf5, subsetting if specified.
Input:
-data_dset (h5py dset): HDF5 dataset from which to read data_df
-ridx (list): list of indexes to subset from data_df
(may be all of them if no subsettin... | python | def parse_data_df(data_dset, ridx, cidx, row_meta, col_meta):
"""
Parses in data_df from hdf5, subsetting if specified.
Input:
-data_dset (h5py dset): HDF5 dataset from which to read data_df
-ridx (list): list of indexes to subset from data_df
(may be all of them if no subsettin... | [
"def",
"parse_data_df",
"(",
"data_dset",
",",
"ridx",
",",
"cidx",
",",
"row_meta",
",",
"col_meta",
")",
":",
"if",
"len",
"(",
"ridx",
")",
"==",
"len",
"(",
"row_meta",
".",
"index",
")",
"and",
"len",
"(",
"cidx",
")",
"==",
"len",
"(",
"col_m... | Parses in data_df from hdf5, subsetting if specified.
Input:
-data_dset (h5py dset): HDF5 dataset from which to read data_df
-ridx (list): list of indexes to subset from data_df
(may be all of them if no subsetting)
-cidx (list): list of indexes to subset from data_df
... | [
"Parses",
"in",
"data_df",
"from",
"hdf5",
"subsetting",
"if",
"specified",
"."
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/parse_gctx.py#L320-L345 | train |
cmap/cmapPy | cmapPy/pandasGEXpress/parse_gctx.py | get_column_metadata | def get_column_metadata(gctx_file_path, convert_neg_666=True):
"""
Opens .gctx file and returns only column metadata
Input:
Mandatory:
- gctx_file_path (str): full path to gctx file you want to parse.
Optional:
- convert_neg_666 (bool): whether to convert -666 values to num... | python | def get_column_metadata(gctx_file_path, convert_neg_666=True):
"""
Opens .gctx file and returns only column metadata
Input:
Mandatory:
- gctx_file_path (str): full path to gctx file you want to parse.
Optional:
- convert_neg_666 (bool): whether to convert -666 values to num... | [
"def",
"get_column_metadata",
"(",
"gctx_file_path",
",",
"convert_neg_666",
"=",
"True",
")",
":",
"full_path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"gctx_file_path",
")",
"gctx_file",
"=",
"h5py",
".",
"File",
"(",
"full_path",
",",
"\"r\"",
")"... | Opens .gctx file and returns only column metadata
Input:
Mandatory:
- gctx_file_path (str): full path to gctx file you want to parse.
Optional:
- convert_neg_666 (bool): whether to convert -666 values to num
Output:
- col_meta (pandas DataFrame): a DataFrame of all col... | [
"Opens",
".",
"gctx",
"file",
"and",
"returns",
"only",
"column",
"metadata"
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/parse_gctx.py#L348-L368 | train |
cmap/cmapPy | cmapPy/pandasGEXpress/parse_gctx.py | get_row_metadata | def get_row_metadata(gctx_file_path, convert_neg_666=True):
"""
Opens .gctx file and returns only row metadata
Input:
Mandatory:
- gctx_file_path (str): full path to gctx file you want to parse.
Optional:
- convert_neg_666 (bool): whether to convert -666 values to num
... | python | def get_row_metadata(gctx_file_path, convert_neg_666=True):
"""
Opens .gctx file and returns only row metadata
Input:
Mandatory:
- gctx_file_path (str): full path to gctx file you want to parse.
Optional:
- convert_neg_666 (bool): whether to convert -666 values to num
... | [
"def",
"get_row_metadata",
"(",
"gctx_file_path",
",",
"convert_neg_666",
"=",
"True",
")",
":",
"full_path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"gctx_file_path",
")",
"gctx_file",
"=",
"h5py",
".",
"File",
"(",
"full_path",
",",
"\"r\"",
")",
... | Opens .gctx file and returns only row metadata
Input:
Mandatory:
- gctx_file_path (str): full path to gctx file you want to parse.
Optional:
- convert_neg_666 (bool): whether to convert -666 values to num
Output:
- row_meta (pandas DataFrame): a DataFrame of all row me... | [
"Opens",
".",
"gctx",
"file",
"and",
"returns",
"only",
"row",
"metadata"
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/parse_gctx.py#L371-L391 | train |
cmap/cmapPy | cmapPy/pandasGEXpress/GCToo.py | multi_index_df_to_component_dfs | def multi_index_df_to_component_dfs(multi_index_df, rid="rid", cid="cid"):
""" Convert a multi-index df into 3 component dfs. """
# Id level of the multiindex will become the index
rids = list(multi_index_df.index.get_level_values(rid))
cids = list(multi_index_df.columns.get_level_values(cid))
# I... | python | def multi_index_df_to_component_dfs(multi_index_df, rid="rid", cid="cid"):
""" Convert a multi-index df into 3 component dfs. """
# Id level of the multiindex will become the index
rids = list(multi_index_df.index.get_level_values(rid))
cids = list(multi_index_df.columns.get_level_values(cid))
# I... | [
"def",
"multi_index_df_to_component_dfs",
"(",
"multi_index_df",
",",
"rid",
"=",
"\"rid\"",
",",
"cid",
"=",
"\"cid\"",
")",
":",
"rids",
"=",
"list",
"(",
"multi_index_df",
".",
"index",
".",
"get_level_values",
"(",
"rid",
")",
")",
"cids",
"=",
"list",
... | Convert a multi-index df into 3 component dfs. | [
"Convert",
"a",
"multi",
"-",
"index",
"df",
"into",
"3",
"component",
"dfs",
"."
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/GCToo.py#L222-L284 | train |
cmap/cmapPy | cmapPy/pandasGEXpress/GCToo.py | GCToo.check_df | def check_df(self, df):
"""
Verifies that df is a pandas DataFrame instance and
that its index and column values are unique.
"""
if isinstance(df, pd.DataFrame):
if not df.index.is_unique:
repeats = df.index[df.index.duplicated()].values
... | python | def check_df(self, df):
"""
Verifies that df is a pandas DataFrame instance and
that its index and column values are unique.
"""
if isinstance(df, pd.DataFrame):
if not df.index.is_unique:
repeats = df.index[df.index.duplicated()].values
... | [
"def",
"check_df",
"(",
"self",
",",
"df",
")",
":",
"if",
"isinstance",
"(",
"df",
",",
"pd",
".",
"DataFrame",
")",
":",
"if",
"not",
"df",
".",
"index",
".",
"is_unique",
":",
"repeats",
"=",
"df",
".",
"index",
"[",
"df",
".",
"index",
".",
... | Verifies that df is a pandas DataFrame instance and
that its index and column values are unique. | [
"Verifies",
"that",
"df",
"is",
"a",
"pandas",
"DataFrame",
"instance",
"and",
"that",
"its",
"index",
"and",
"column",
"values",
"are",
"unique",
"."
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/GCToo.py#L125-L145 | train |
cmap/cmapPy | cmapPy/clue_api_client/gene_queries.py | are_genes_in_api | def are_genes_in_api(my_clue_api_client, gene_symbols):
"""determine if genes are present in the API
Args:
my_clue_api_client:
gene_symbols: collection of gene symbols to query the API with
Returns: set of the found gene symbols
"""
if len(gene_symbols) > 0:
query_gene_sym... | python | def are_genes_in_api(my_clue_api_client, gene_symbols):
"""determine if genes are present in the API
Args:
my_clue_api_client:
gene_symbols: collection of gene symbols to query the API with
Returns: set of the found gene symbols
"""
if len(gene_symbols) > 0:
query_gene_sym... | [
"def",
"are_genes_in_api",
"(",
"my_clue_api_client",
",",
"gene_symbols",
")",
":",
"if",
"len",
"(",
"gene_symbols",
")",
">",
"0",
":",
"query_gene_symbols",
"=",
"gene_symbols",
"if",
"type",
"(",
"gene_symbols",
")",
"is",
"list",
"else",
"list",
"(",
"... | determine if genes are present in the API
Args:
my_clue_api_client:
gene_symbols: collection of gene symbols to query the API with
Returns: set of the found gene symbols | [
"determine",
"if",
"genes",
"are",
"present",
"in",
"the",
"API"
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/clue_api_client/gene_queries.py#L13-L34 | train |
cmap/cmapPy | cmapPy/pandasGEXpress/write_gct.py | write | def write(gctoo, out_fname, data_null="NaN", metadata_null="-666", filler_null="-666", data_float_format="%.4f"):
"""Write a gctoo object to a gct file.
Args:
gctoo (gctoo object)
out_fname (string): filename for output gct file
data_null (string): how to represent missing values in the... | python | def write(gctoo, out_fname, data_null="NaN", metadata_null="-666", filler_null="-666", data_float_format="%.4f"):
"""Write a gctoo object to a gct file.
Args:
gctoo (gctoo object)
out_fname (string): filename for output gct file
data_null (string): how to represent missing values in the... | [
"def",
"write",
"(",
"gctoo",
",",
"out_fname",
",",
"data_null",
"=",
"\"NaN\"",
",",
"metadata_null",
"=",
"\"-666\"",
",",
"filler_null",
"=",
"\"-666\"",
",",
"data_float_format",
"=",
"\"%.4f\"",
")",
":",
"if",
"not",
"out_fname",
".",
"endswith",
"(",... | Write a gctoo object to a gct file.
Args:
gctoo (gctoo object)
out_fname (string): filename for output gct file
data_null (string): how to represent missing values in the data (default = "NaN")
metadata_null (string): how to represent missing values in the metadata (default = "-666"... | [
"Write",
"a",
"gctoo",
"object",
"to",
"a",
"gct",
"file",
"."
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/write_gct.py#L16-L51 | train |
cmap/cmapPy | cmapPy/pandasGEXpress/write_gct.py | write_version_and_dims | def write_version_and_dims(version, dims, f):
"""Write first two lines of gct file.
Args:
version (string): 1.3 by default
dims (list of strings): length = 4
f (file handle): handle of output file
Returns:
nothing
"""
f.write(("#" + version + "\n"))
f.write((dims... | python | def write_version_and_dims(version, dims, f):
"""Write first two lines of gct file.
Args:
version (string): 1.3 by default
dims (list of strings): length = 4
f (file handle): handle of output file
Returns:
nothing
"""
f.write(("#" + version + "\n"))
f.write((dims... | [
"def",
"write_version_and_dims",
"(",
"version",
",",
"dims",
",",
"f",
")",
":",
"f",
".",
"write",
"(",
"(",
"\"#\"",
"+",
"version",
"+",
"\"\\n\"",
")",
")",
"f",
".",
"write",
"(",
"(",
"dims",
"[",
"0",
"]",
"+",
"\"\\t\"",
"+",
"dims",
"["... | Write first two lines of gct file.
Args:
version (string): 1.3 by default
dims (list of strings): length = 4
f (file handle): handle of output file
Returns:
nothing | [
"Write",
"first",
"two",
"lines",
"of",
"gct",
"file",
"."
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/write_gct.py#L54-L65 | train |
cmap/cmapPy | cmapPy/pandasGEXpress/write_gct.py | append_dims_and_file_extension | def append_dims_and_file_extension(fname, data_df):
"""Append dimensions and file extension to output filename.
N.B. Dimensions are cols x rows.
Args:
fname (string): output filename
data_df (pandas df)
Returns:
out_fname (string): output filename with matrix dims and .gct appen... | python | def append_dims_and_file_extension(fname, data_df):
"""Append dimensions and file extension to output filename.
N.B. Dimensions are cols x rows.
Args:
fname (string): output filename
data_df (pandas df)
Returns:
out_fname (string): output filename with matrix dims and .gct appen... | [
"def",
"append_dims_and_file_extension",
"(",
"fname",
",",
"data_df",
")",
":",
"if",
"not",
"fname",
".",
"endswith",
"(",
"\".gct\"",
")",
":",
"out_fname",
"=",
"'{0}_n{1}x{2}.gct'",
".",
"format",
"(",
"fname",
",",
"data_df",
".",
"shape",
"[",
"1",
... | Append dimensions and file extension to output filename.
N.B. Dimensions are cols x rows.
Args:
fname (string): output filename
data_df (pandas df)
Returns:
out_fname (string): output filename with matrix dims and .gct appended | [
"Append",
"dimensions",
"and",
"file",
"extension",
"to",
"output",
"filename",
".",
"N",
".",
"B",
".",
"Dimensions",
"are",
"cols",
"x",
"rows",
"."
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/write_gct.py#L142-L161 | train |
cmap/cmapPy | cmapPy/math/robust_zscore.py | robust_zscore | def robust_zscore(mat, ctrl_mat=None, min_mad=0.1):
''' Robustly z-score a pandas df along the rows.
Args:
mat (pandas df): Matrix of data that z-scoring will be applied to
ctrl_mat (pandas df): Optional matrix from which to compute medians and MADs
(e.g. vehicle control)
min_mad (float): M... | python | def robust_zscore(mat, ctrl_mat=None, min_mad=0.1):
''' Robustly z-score a pandas df along the rows.
Args:
mat (pandas df): Matrix of data that z-scoring will be applied to
ctrl_mat (pandas df): Optional matrix from which to compute medians and MADs
(e.g. vehicle control)
min_mad (float): M... | [
"def",
"robust_zscore",
"(",
"mat",
",",
"ctrl_mat",
"=",
"None",
",",
"min_mad",
"=",
"0.1",
")",
":",
"if",
"ctrl_mat",
"is",
"not",
"None",
":",
"medians",
"=",
"ctrl_mat",
".",
"median",
"(",
"axis",
"=",
"1",
")",
"median_devs",
"=",
"abs",
"(",... | Robustly z-score a pandas df along the rows.
Args:
mat (pandas df): Matrix of data that z-scoring will be applied to
ctrl_mat (pandas df): Optional matrix from which to compute medians and MADs
(e.g. vehicle control)
min_mad (float): Minimum MAD to threshold to; tiny MAD values will cause
... | [
"Robustly",
"z",
"-",
"score",
"a",
"pandas",
"df",
"along",
"the",
"rows",
"."
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/math/robust_zscore.py#L24-L58 | train |
cmap/cmapPy | cmapPy/pandasGEXpress/parse.py | parse | def parse(file_path, convert_neg_666=True, rid=None, cid=None, ridx=None, cidx=None,
row_meta_only=False, col_meta_only=False, make_multiindex=False):
"""
Identifies whether file_path corresponds to a .gct or .gctx file and calls the
correct corresponding parse method.
Input:
Mandator... | python | def parse(file_path, convert_neg_666=True, rid=None, cid=None, ridx=None, cidx=None,
row_meta_only=False, col_meta_only=False, make_multiindex=False):
"""
Identifies whether file_path corresponds to a .gct or .gctx file and calls the
correct corresponding parse method.
Input:
Mandator... | [
"def",
"parse",
"(",
"file_path",
",",
"convert_neg_666",
"=",
"True",
",",
"rid",
"=",
"None",
",",
"cid",
"=",
"None",
",",
"ridx",
"=",
"None",
",",
"cidx",
"=",
"None",
",",
"row_meta_only",
"=",
"False",
",",
"col_meta_only",
"=",
"False",
",",
... | Identifies whether file_path corresponds to a .gct or .gctx file and calls the
correct corresponding parse method.
Input:
Mandatory:
- gct(x)_file_path (str): full path to gct(x) file you want to parse.
Optional:
- convert_neg_666 (bool): whether to convert -666 values to numpy... | [
"Identifies",
"whether",
"file_path",
"corresponds",
"to",
"a",
".",
"gct",
"or",
".",
"gctx",
"file",
"and",
"calls",
"the",
"correct",
"corresponding",
"parse",
"method",
"."
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/parse.py#L21-L75 | train |
cmap/cmapPy | cmapPy/math/agg_wt_avg.py | get_upper_triangle | def get_upper_triangle(correlation_matrix):
''' Extract upper triangle from a square matrix. Negative values are
set to 0.
Args:
correlation_matrix (pandas df): Correlations between all replicates
Returns:
upper_tri_df (pandas df): Upper triangle extracted from
correlation_matrix; rid ... | python | def get_upper_triangle(correlation_matrix):
''' Extract upper triangle from a square matrix. Negative values are
set to 0.
Args:
correlation_matrix (pandas df): Correlations between all replicates
Returns:
upper_tri_df (pandas df): Upper triangle extracted from
correlation_matrix; rid ... | [
"def",
"get_upper_triangle",
"(",
"correlation_matrix",
")",
":",
"upper_triangle",
"=",
"correlation_matrix",
".",
"where",
"(",
"np",
".",
"triu",
"(",
"np",
".",
"ones",
"(",
"correlation_matrix",
".",
"shape",
")",
",",
"k",
"=",
"1",
")",
".",
"astype... | Extract upper triangle from a square matrix. Negative values are
set to 0.
Args:
correlation_matrix (pandas df): Correlations between all replicates
Returns:
upper_tri_df (pandas df): Upper triangle extracted from
correlation_matrix; rid is the row index, cid is the column index,
c... | [
"Extract",
"upper",
"triangle",
"from",
"a",
"square",
"matrix",
".",
"Negative",
"values",
"are",
"set",
"to",
"0",
"."
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/math/agg_wt_avg.py#L17-L41 | train |
cmap/cmapPy | cmapPy/math/agg_wt_avg.py | calculate_weights | def calculate_weights(correlation_matrix, min_wt):
''' Calculate a weight for each profile based on its correlation to other
replicates. Negative correlations are clipped to 0, and weights are clipped
to be min_wt at the least.
Args:
correlation_matrix (pandas df): Correlations between all replicat... | python | def calculate_weights(correlation_matrix, min_wt):
''' Calculate a weight for each profile based on its correlation to other
replicates. Negative correlations are clipped to 0, and weights are clipped
to be min_wt at the least.
Args:
correlation_matrix (pandas df): Correlations between all replicat... | [
"def",
"calculate_weights",
"(",
"correlation_matrix",
",",
"min_wt",
")",
":",
"np",
".",
"fill_diagonal",
"(",
"correlation_matrix",
".",
"values",
",",
"np",
".",
"nan",
")",
"correlation_matrix",
"=",
"correlation_matrix",
".",
"clip",
"(",
"lower",
"=",
"... | Calculate a weight for each profile based on its correlation to other
replicates. Negative correlations are clipped to 0, and weights are clipped
to be min_wt at the least.
Args:
correlation_matrix (pandas df): Correlations between all replicates
min_wt (float): Minimum raw weight when calculating ... | [
"Calculate",
"a",
"weight",
"for",
"each",
"profile",
"based",
"on",
"its",
"correlation",
"to",
"other",
"replicates",
".",
"Negative",
"correlations",
"are",
"clipped",
"to",
"0",
"and",
"weights",
"are",
"clipped",
"to",
"be",
"min_wt",
"at",
"the",
"leas... | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/math/agg_wt_avg.py#L44-L72 | train |
cmap/cmapPy | cmapPy/math/agg_wt_avg.py | agg_wt_avg | def agg_wt_avg(mat, min_wt = 0.01, corr_metric='spearman'):
''' Aggregate a set of replicate profiles into a single signature using
a weighted average.
Args:
mat (pandas df): a matrix of replicate profiles, where the columns are
samples and the rows are features; columns correspond to the
... | python | def agg_wt_avg(mat, min_wt = 0.01, corr_metric='spearman'):
''' Aggregate a set of replicate profiles into a single signature using
a weighted average.
Args:
mat (pandas df): a matrix of replicate profiles, where the columns are
samples and the rows are features; columns correspond to the
... | [
"def",
"agg_wt_avg",
"(",
"mat",
",",
"min_wt",
"=",
"0.01",
",",
"corr_metric",
"=",
"'spearman'",
")",
":",
"assert",
"mat",
".",
"shape",
"[",
"1",
"]",
">",
"0",
",",
"\"mat is empty! mat: {}\"",
".",
"format",
"(",
"mat",
")",
"if",
"mat",
".",
... | Aggregate a set of replicate profiles into a single signature using
a weighted average.
Args:
mat (pandas df): a matrix of replicate profiles, where the columns are
samples and the rows are features; columns correspond to the
replicates of a single perturbagen
min_wt (float): Minimum ra... | [
"Aggregate",
"a",
"set",
"of",
"replicate",
"profiles",
"into",
"a",
"single",
"signature",
"using",
"a",
"weighted",
"average",
"."
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/math/agg_wt_avg.py#L75-L118 | train |
cmap/cmapPy | cmapPy/pandasGEXpress/concat.py | get_file_list | def get_file_list(wildcard):
""" Search for files to be concatenated. Currently very basic, but could
expand to be more sophisticated.
Args:
wildcard (regular expression string)
Returns:
files (list of full file paths)
"""
files = glob.glob(os.path.expanduser(wildcard))
re... | python | def get_file_list(wildcard):
""" Search for files to be concatenated. Currently very basic, but could
expand to be more sophisticated.
Args:
wildcard (regular expression string)
Returns:
files (list of full file paths)
"""
files = glob.glob(os.path.expanduser(wildcard))
re... | [
"def",
"get_file_list",
"(",
"wildcard",
")",
":",
"files",
"=",
"glob",
".",
"glob",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"wildcard",
")",
")",
"return",
"files"
] | Search for files to be concatenated. Currently very basic, but could
expand to be more sophisticated.
Args:
wildcard (regular expression string)
Returns:
files (list of full file paths) | [
"Search",
"for",
"files",
"to",
"be",
"concatenated",
".",
"Currently",
"very",
"basic",
"but",
"could",
"expand",
"to",
"be",
"more",
"sophisticated",
"."
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/concat.py#L158-L170 | train |
cmap/cmapPy | cmapPy/pandasGEXpress/concat.py | hstack | def hstack(gctoos, remove_all_metadata_fields=False, error_report_file=None, fields_to_remove=[], reset_ids=False):
""" Horizontally concatenate gctoos.
Args:
gctoos (list of gctoo objects)
remove_all_metadata_fields (bool): ignore/strip all common metadata when combining gctoos
error_... | python | def hstack(gctoos, remove_all_metadata_fields=False, error_report_file=None, fields_to_remove=[], reset_ids=False):
""" Horizontally concatenate gctoos.
Args:
gctoos (list of gctoo objects)
remove_all_metadata_fields (bool): ignore/strip all common metadata when combining gctoos
error_... | [
"def",
"hstack",
"(",
"gctoos",
",",
"remove_all_metadata_fields",
"=",
"False",
",",
"error_report_file",
"=",
"None",
",",
"fields_to_remove",
"=",
"[",
"]",
",",
"reset_ids",
"=",
"False",
")",
":",
"row_meta_dfs",
"=",
"[",
"]",
"col_meta_dfs",
"=",
"[",... | Horizontally concatenate gctoos.
Args:
gctoos (list of gctoo objects)
remove_all_metadata_fields (bool): ignore/strip all common metadata when combining gctoos
error_report_file (string): path to write file containing error report indicating
problems that occurred during hsta... | [
"Horizontally",
"concatenate",
"gctoos",
"."
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/concat.py#L173-L224 | train |
cmap/cmapPy | cmapPy/pandasGEXpress/concat.py | assemble_concatenated_meta | def assemble_concatenated_meta(concated_meta_dfs, remove_all_metadata_fields):
""" Assemble the concatenated metadata dfs together. For example,
if horizontally concatenating, the concatenated metadata dfs are the
column metadata dfs. Both indices are sorted.
Args:
concated_meta_dfs (list of pa... | python | def assemble_concatenated_meta(concated_meta_dfs, remove_all_metadata_fields):
""" Assemble the concatenated metadata dfs together. For example,
if horizontally concatenating, the concatenated metadata dfs are the
column metadata dfs. Both indices are sorted.
Args:
concated_meta_dfs (list of pa... | [
"def",
"assemble_concatenated_meta",
"(",
"concated_meta_dfs",
",",
"remove_all_metadata_fields",
")",
":",
"if",
"remove_all_metadata_fields",
":",
"for",
"df",
"in",
"concated_meta_dfs",
":",
"df",
".",
"drop",
"(",
"df",
".",
"columns",
",",
"axis",
"=",
"1",
... | Assemble the concatenated metadata dfs together. For example,
if horizontally concatenating, the concatenated metadata dfs are the
column metadata dfs. Both indices are sorted.
Args:
concated_meta_dfs (list of pandas dfs)
Returns:
all_concated_meta_df_sorted (pandas df) | [
"Assemble",
"the",
"concatenated",
"metadata",
"dfs",
"together",
".",
"For",
"example",
"if",
"horizontally",
"concatenating",
"the",
"concatenated",
"metadata",
"dfs",
"are",
"the",
"column",
"metadata",
"dfs",
".",
"Both",
"indices",
"are",
"sorted",
"."
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/concat.py#L423-L452 | train |
cmap/cmapPy | cmapPy/pandasGEXpress/concat.py | assemble_data | def assemble_data(data_dfs, concat_direction):
""" Assemble the data dfs together. Both indices are sorted.
Args:
data_dfs (list of pandas dfs)
concat_direction (string): 'horiz' or 'vert'
Returns:
all_data_df_sorted (pandas df)
"""
if concat_direction == "horiz":
... | python | def assemble_data(data_dfs, concat_direction):
""" Assemble the data dfs together. Both indices are sorted.
Args:
data_dfs (list of pandas dfs)
concat_direction (string): 'horiz' or 'vert'
Returns:
all_data_df_sorted (pandas df)
"""
if concat_direction == "horiz":
... | [
"def",
"assemble_data",
"(",
"data_dfs",
",",
"concat_direction",
")",
":",
"if",
"concat_direction",
"==",
"\"horiz\"",
":",
"all_data_df",
"=",
"pd",
".",
"concat",
"(",
"data_dfs",
",",
"axis",
"=",
"1",
")",
"n_cols",
"=",
"all_data_df",
".",
"shape",
... | Assemble the data dfs together. Both indices are sorted.
Args:
data_dfs (list of pandas dfs)
concat_direction (string): 'horiz' or 'vert'
Returns:
all_data_df_sorted (pandas df) | [
"Assemble",
"the",
"data",
"dfs",
"together",
".",
"Both",
"indices",
"are",
"sorted",
"."
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/concat.py#L455-L492 | train |
cmap/cmapPy | cmapPy/pandasGEXpress/concat.py | do_reset_ids | def do_reset_ids(concatenated_meta_df, data_df, concat_direction):
""" Reset ids in concatenated metadata and data dfs to unique integers and
save the old ids in a metadata column.
Note that the dataframes are modified in-place.
Args:
concatenated_meta_df (pandas df)
data_df (pandas df... | python | def do_reset_ids(concatenated_meta_df, data_df, concat_direction):
""" Reset ids in concatenated metadata and data dfs to unique integers and
save the old ids in a metadata column.
Note that the dataframes are modified in-place.
Args:
concatenated_meta_df (pandas df)
data_df (pandas df... | [
"def",
"do_reset_ids",
"(",
"concatenated_meta_df",
",",
"data_df",
",",
"concat_direction",
")",
":",
"if",
"concat_direction",
"==",
"\"horiz\"",
":",
"assert",
"concatenated_meta_df",
".",
"index",
".",
"equals",
"(",
"data_df",
".",
"columns",
")",
",",
"(",... | Reset ids in concatenated metadata and data dfs to unique integers and
save the old ids in a metadata column.
Note that the dataframes are modified in-place.
Args:
concatenated_meta_df (pandas df)
data_df (pandas df)
concat_direction (string): 'horiz' or 'vert'
Returns:
... | [
"Reset",
"ids",
"in",
"concatenated",
"metadata",
"and",
"data",
"dfs",
"to",
"unique",
"integers",
"and",
"save",
"the",
"old",
"ids",
"in",
"a",
"metadata",
"column",
"."
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/concat.py#L495-L534 | train |
cmap/cmapPy | cmapPy/pandasGEXpress/concat.py | reset_ids_in_meta_df | def reset_ids_in_meta_df(meta_df):
""" Meta_df is modified inplace. """
# Record original index name, and then change it so that the column that it
# becomes will be appropriately named
original_index_name = meta_df.index.name
meta_df.index.name = "old_id"
# Reset index
meta_df.reset_index... | python | def reset_ids_in_meta_df(meta_df):
""" Meta_df is modified inplace. """
# Record original index name, and then change it so that the column that it
# becomes will be appropriately named
original_index_name = meta_df.index.name
meta_df.index.name = "old_id"
# Reset index
meta_df.reset_index... | [
"def",
"reset_ids_in_meta_df",
"(",
"meta_df",
")",
":",
"original_index_name",
"=",
"meta_df",
".",
"index",
".",
"name",
"meta_df",
".",
"index",
".",
"name",
"=",
"\"old_id\"",
"meta_df",
".",
"reset_index",
"(",
"inplace",
"=",
"True",
")",
"meta_df",
".... | Meta_df is modified inplace. | [
"Meta_df",
"is",
"modified",
"inplace",
"."
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/concat.py#L537-L549 | train |
cmap/cmapPy | cmapPy/pandasGEXpress/subset_gctoo.py | subset_gctoo | def subset_gctoo(gctoo, row_bool=None, col_bool=None, rid=None, cid=None,
ridx=None, cidx=None, exclude_rid=None, exclude_cid=None):
""" Extract a subset of data from a GCToo object in a variety of ways.
The order of rows and columns will be preserved.
Args:
gctoo (GCToo object)
... | python | def subset_gctoo(gctoo, row_bool=None, col_bool=None, rid=None, cid=None,
ridx=None, cidx=None, exclude_rid=None, exclude_cid=None):
""" Extract a subset of data from a GCToo object in a variety of ways.
The order of rows and columns will be preserved.
Args:
gctoo (GCToo object)
... | [
"def",
"subset_gctoo",
"(",
"gctoo",
",",
"row_bool",
"=",
"None",
",",
"col_bool",
"=",
"None",
",",
"rid",
"=",
"None",
",",
"cid",
"=",
"None",
",",
"ridx",
"=",
"None",
",",
"cidx",
"=",
"None",
",",
"exclude_rid",
"=",
"None",
",",
"exclude_cid"... | Extract a subset of data from a GCToo object in a variety of ways.
The order of rows and columns will be preserved.
Args:
gctoo (GCToo object)
row_bool (list of bools): length must equal gctoo.data_df.shape[0]
col_bool (list of bools): length must equal gctoo.data_df.shape[1]
ri... | [
"Extract",
"a",
"subset",
"of",
"data",
"from",
"a",
"GCToo",
"object",
"in",
"a",
"variety",
"of",
"ways",
".",
"The",
"order",
"of",
"rows",
"and",
"columns",
"will",
"be",
"preserved",
"."
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/subset_gctoo.py#L19-L65 | train |
cmap/cmapPy | cmapPy/pandasGEXpress/subset_gctoo.py | get_rows_to_keep | def get_rows_to_keep(gctoo, rid=None, row_bool=None, ridx=None, exclude_rid=None):
""" Figure out based on the possible row inputs which rows to keep.
Args:
gctoo (GCToo object):
rid (list of strings):
row_bool (boolean array):
ridx (list of integers):
exclude_rid (list ... | python | def get_rows_to_keep(gctoo, rid=None, row_bool=None, ridx=None, exclude_rid=None):
""" Figure out based on the possible row inputs which rows to keep.
Args:
gctoo (GCToo object):
rid (list of strings):
row_bool (boolean array):
ridx (list of integers):
exclude_rid (list ... | [
"def",
"get_rows_to_keep",
"(",
"gctoo",
",",
"rid",
"=",
"None",
",",
"row_bool",
"=",
"None",
",",
"ridx",
"=",
"None",
",",
"exclude_rid",
"=",
"None",
")",
":",
"if",
"rid",
"is",
"not",
"None",
":",
"assert",
"type",
"(",
"rid",
")",
"==",
"li... | Figure out based on the possible row inputs which rows to keep.
Args:
gctoo (GCToo object):
rid (list of strings):
row_bool (boolean array):
ridx (list of integers):
exclude_rid (list of strings):
Returns:
rows_to_keep (list of strings): row ids to be kept | [
"Figure",
"out",
"based",
"on",
"the",
"possible",
"row",
"inputs",
"which",
"rows",
"to",
"keep",
"."
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/subset_gctoo.py#L68-L126 | train |
cmap/cmapPy | cmapPy/pandasGEXpress/subset_gctoo.py | get_cols_to_keep | def get_cols_to_keep(gctoo, cid=None, col_bool=None, cidx=None, exclude_cid=None):
""" Figure out based on the possible columns inputs which columns to keep.
Args:
gctoo (GCToo object):
cid (list of strings):
col_bool (boolean array):
cidx (list of integers):
exclude_cid... | python | def get_cols_to_keep(gctoo, cid=None, col_bool=None, cidx=None, exclude_cid=None):
""" Figure out based on the possible columns inputs which columns to keep.
Args:
gctoo (GCToo object):
cid (list of strings):
col_bool (boolean array):
cidx (list of integers):
exclude_cid... | [
"def",
"get_cols_to_keep",
"(",
"gctoo",
",",
"cid",
"=",
"None",
",",
"col_bool",
"=",
"None",
",",
"cidx",
"=",
"None",
",",
"exclude_cid",
"=",
"None",
")",
":",
"if",
"cid",
"is",
"not",
"None",
":",
"assert",
"type",
"(",
"cid",
")",
"==",
"li... | Figure out based on the possible columns inputs which columns to keep.
Args:
gctoo (GCToo object):
cid (list of strings):
col_bool (boolean array):
cidx (list of integers):
exclude_cid (list of strings):
Returns:
cols_to_keep (list of strings): col ids to be kep... | [
"Figure",
"out",
"based",
"on",
"the",
"possible",
"columns",
"inputs",
"which",
"columns",
"to",
"keep",
"."
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/subset_gctoo.py#L129-L188 | train |
cmap/cmapPy | cmapPy/set_io/grp.py | read | def read(in_path):
""" Read a grp file at the path specified by in_path.
Args:
in_path (string): path to GRP file
Returns:
grp (list)
"""
assert os.path.exists(in_path), "The following GRP file can't be found. in_path: {}".format(in_path)
with open(in_path, "r") as f:
... | python | def read(in_path):
""" Read a grp file at the path specified by in_path.
Args:
in_path (string): path to GRP file
Returns:
grp (list)
"""
assert os.path.exists(in_path), "The following GRP file can't be found. in_path: {}".format(in_path)
with open(in_path, "r") as f:
... | [
"def",
"read",
"(",
"in_path",
")",
":",
"assert",
"os",
".",
"path",
".",
"exists",
"(",
"in_path",
")",
",",
"\"The following GRP file can't be found. in_path: {}\"",
".",
"format",
"(",
"in_path",
")",
"with",
"open",
"(",
"in_path",
",",
"\"r\"",
")",
"a... | Read a grp file at the path specified by in_path.
Args:
in_path (string): path to GRP file
Returns:
grp (list) | [
"Read",
"a",
"grp",
"file",
"at",
"the",
"path",
"specified",
"by",
"in_path",
"."
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/set_io/grp.py#L16-L33 | train |
cmap/cmapPy | cmapPy/set_io/grp.py | write | def write(grp, out_path):
""" Write a GRP to a text file.
Args:
grp (list): GRP object to write to new-line delimited text file
out_path (string): output path
Returns:
None
"""
with open(out_path, "w") as f:
for x in grp:
f.write(str(x) + "\n") | python | def write(grp, out_path):
""" Write a GRP to a text file.
Args:
grp (list): GRP object to write to new-line delimited text file
out_path (string): output path
Returns:
None
"""
with open(out_path, "w") as f:
for x in grp:
f.write(str(x) + "\n") | [
"def",
"write",
"(",
"grp",
",",
"out_path",
")",
":",
"with",
"open",
"(",
"out_path",
",",
"\"w\"",
")",
"as",
"f",
":",
"for",
"x",
"in",
"grp",
":",
"f",
".",
"write",
"(",
"str",
"(",
"x",
")",
"+",
"\"\\n\"",
")"
] | Write a GRP to a text file.
Args:
grp (list): GRP object to write to new-line delimited text file
out_path (string): output path
Returns:
None | [
"Write",
"a",
"GRP",
"to",
"a",
"text",
"file",
"."
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/set_io/grp.py#L36-L49 | train |
cmap/cmapPy | cmapPy/pandasGEXpress/random_slice.py | make_specified_size_gctoo | def make_specified_size_gctoo(og_gctoo, num_entries, dim):
"""
Subsets a GCToo instance along either rows or columns to obtain a specified size.
Input:
- og_gctoo (GCToo): a GCToo instance
- num_entries (int): the number of entries to keep
- dim (str): the dimension along which to subset. Must be "row" or... | python | def make_specified_size_gctoo(og_gctoo, num_entries, dim):
"""
Subsets a GCToo instance along either rows or columns to obtain a specified size.
Input:
- og_gctoo (GCToo): a GCToo instance
- num_entries (int): the number of entries to keep
- dim (str): the dimension along which to subset. Must be "row" or... | [
"def",
"make_specified_size_gctoo",
"(",
"og_gctoo",
",",
"num_entries",
",",
"dim",
")",
":",
"assert",
"dim",
"in",
"[",
"\"row\"",
",",
"\"col\"",
"]",
",",
"\"dim specified must be either 'row' or 'col'\"",
"dim_index",
"=",
"0",
"if",
"\"row\"",
"==",
"dim",
... | Subsets a GCToo instance along either rows or columns to obtain a specified size.
Input:
- og_gctoo (GCToo): a GCToo instance
- num_entries (int): the number of entries to keep
- dim (str): the dimension along which to subset. Must be "row" or "col"
Output:
- new_gctoo (GCToo): the GCToo instance subsetted... | [
"Subsets",
"a",
"GCToo",
"instance",
"along",
"either",
"rows",
"or",
"columns",
"to",
"obtain",
"a",
"specified",
"size",
"."
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/random_slice.py#L15-L55 | train |
cmap/cmapPy | cmapPy/pandasGEXpress/write_gctx.py | write | def write(gctoo_object, out_file_name, convert_back_to_neg_666=True, gzip_compression_level=6,
max_chunk_kb=1024, matrix_dtype=numpy.float32):
"""
Writes a GCToo instance to specified file.
Input:
- gctoo_object (GCToo): A GCToo instance.
- out_file_name (str): file name to write gctoo_object to.
... | python | def write(gctoo_object, out_file_name, convert_back_to_neg_666=True, gzip_compression_level=6,
max_chunk_kb=1024, matrix_dtype=numpy.float32):
"""
Writes a GCToo instance to specified file.
Input:
- gctoo_object (GCToo): A GCToo instance.
- out_file_name (str): file name to write gctoo_object to.
... | [
"def",
"write",
"(",
"gctoo_object",
",",
"out_file_name",
",",
"convert_back_to_neg_666",
"=",
"True",
",",
"gzip_compression_level",
"=",
"6",
",",
"max_chunk_kb",
"=",
"1024",
",",
"matrix_dtype",
"=",
"numpy",
".",
"float32",
")",
":",
"gctx_out_name",
"=",
... | Writes a GCToo instance to specified file.
Input:
- gctoo_object (GCToo): A GCToo instance.
- out_file_name (str): file name to write gctoo_object to.
- convert_back_to_neg_666 (bool): whether to convert np.NAN in metadata back to "-666"
- gzip_compression_level (int, default=6): Compression level... | [
"Writes",
"a",
"GCToo",
"instance",
"to",
"specified",
"file",
"."
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/write_gctx.py#L19-L61 | train |
cmap/cmapPy | cmapPy/pandasGEXpress/write_gctx.py | write_src | def write_src(hdf5_out, gctoo_object, out_file_name):
"""
Writes src as attribute of gctx out file.
Input:
- hdf5_out (h5py): hdf5 file to write to
- gctoo_object (GCToo): GCToo instance to be written to .gctx
- out_file_name (str): name of hdf5 out file.
"""
if gctoo_object.src == None:
hd... | python | def write_src(hdf5_out, gctoo_object, out_file_name):
"""
Writes src as attribute of gctx out file.
Input:
- hdf5_out (h5py): hdf5 file to write to
- gctoo_object (GCToo): GCToo instance to be written to .gctx
- out_file_name (str): name of hdf5 out file.
"""
if gctoo_object.src == None:
hd... | [
"def",
"write_src",
"(",
"hdf5_out",
",",
"gctoo_object",
",",
"out_file_name",
")",
":",
"if",
"gctoo_object",
".",
"src",
"==",
"None",
":",
"hdf5_out",
".",
"attrs",
"[",
"src_attr",
"]",
"=",
"out_file_name",
"else",
":",
"hdf5_out",
".",
"attrs",
"[",... | Writes src as attribute of gctx out file.
Input:
- hdf5_out (h5py): hdf5 file to write to
- gctoo_object (GCToo): GCToo instance to be written to .gctx
- out_file_name (str): name of hdf5 out file. | [
"Writes",
"src",
"as",
"attribute",
"of",
"gctx",
"out",
"file",
"."
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/write_gctx.py#L80-L92 | train |
cmap/cmapPy | cmapPy/pandasGEXpress/write_gctx.py | calculate_elem_per_kb | def calculate_elem_per_kb(max_chunk_kb, matrix_dtype):
"""
Calculates the number of elem per kb depending on the max chunk size set.
Input:
- max_chunk_kb (int, default=1024): The maximum number of KB a given chunk will occupy
- matrix_dtype (numpy dtype, default=numpy.float32): Storage d... | python | def calculate_elem_per_kb(max_chunk_kb, matrix_dtype):
"""
Calculates the number of elem per kb depending on the max chunk size set.
Input:
- max_chunk_kb (int, default=1024): The maximum number of KB a given chunk will occupy
- matrix_dtype (numpy dtype, default=numpy.float32): Storage d... | [
"def",
"calculate_elem_per_kb",
"(",
"max_chunk_kb",
",",
"matrix_dtype",
")",
":",
"if",
"matrix_dtype",
"==",
"numpy",
".",
"float32",
":",
"return",
"(",
"max_chunk_kb",
"*",
"8",
")",
"/",
"32",
"elif",
"matrix_dtype",
"==",
"numpy",
".",
"float64",
":",... | Calculates the number of elem per kb depending on the max chunk size set.
Input:
- max_chunk_kb (int, default=1024): The maximum number of KB a given chunk will occupy
- matrix_dtype (numpy dtype, default=numpy.float32): Storage data type for data matrix.
Currently needs to be np.flo... | [
"Calculates",
"the",
"number",
"of",
"elem",
"per",
"kb",
"depending",
"on",
"the",
"max",
"chunk",
"size",
"set",
"."
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/write_gctx.py#L104-L123 | train |
cmap/cmapPy | cmapPy/pandasGEXpress/write_gctx.py | set_data_matrix_chunk_size | def set_data_matrix_chunk_size(df_shape, max_chunk_kb, elem_per_kb):
"""
Sets chunk size to use for writing data matrix.
Note. Calculation used here is for compatibility with cmapM and cmapR.
Input:
- df_shape (tuple): shape of input data_df.
- max_chunk_kb (int, default=1024): The m... | python | def set_data_matrix_chunk_size(df_shape, max_chunk_kb, elem_per_kb):
"""
Sets chunk size to use for writing data matrix.
Note. Calculation used here is for compatibility with cmapM and cmapR.
Input:
- df_shape (tuple): shape of input data_df.
- max_chunk_kb (int, default=1024): The m... | [
"def",
"set_data_matrix_chunk_size",
"(",
"df_shape",
",",
"max_chunk_kb",
",",
"elem_per_kb",
")",
":",
"row_chunk_size",
"=",
"min",
"(",
"df_shape",
"[",
"0",
"]",
",",
"1000",
")",
"col_chunk_size",
"=",
"min",
"(",
"(",
"(",
"max_chunk_kb",
"*",
"elem_p... | Sets chunk size to use for writing data matrix.
Note. Calculation used here is for compatibility with cmapM and cmapR.
Input:
- df_shape (tuple): shape of input data_df.
- max_chunk_kb (int, default=1024): The maximum number of KB a given chunk will occupy
- elem_per_kb (int): Number... | [
"Sets",
"chunk",
"size",
"to",
"use",
"for",
"writing",
"data",
"matrix",
".",
"Note",
".",
"Calculation",
"used",
"here",
"is",
"for",
"compatibility",
"with",
"cmapM",
"and",
"cmapR",
"."
] | 59d833b64fd2c3a494cdf67fe1eb11fc8008bf76 | https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/write_gctx.py#L126-L141 | train |
danfairs/django-lazysignup | lazysignup/models.py | LazyUserManager.convert | def convert(self, form):
""" Convert a lazy user to a non-lazy one. The form passed
in is expected to be a ModelForm instance, bound to the user
to be converted.
The converted ``User`` object is returned.
Raises a TypeError if the user is not lazy.
"""
if not is... | python | def convert(self, form):
""" Convert a lazy user to a non-lazy one. The form passed
in is expected to be a ModelForm instance, bound to the user
to be converted.
The converted ``User`` object is returned.
Raises a TypeError if the user is not lazy.
"""
if not is... | [
"def",
"convert",
"(",
"self",
",",
"form",
")",
":",
"if",
"not",
"is_lazy_user",
"(",
"form",
".",
"instance",
")",
":",
"raise",
"NotLazyError",
"(",
"'You cannot convert a non-lazy user'",
")",
"user",
"=",
"form",
".",
"save",
"(",
")",
"self",
".",
... | Convert a lazy user to a non-lazy one. The form passed
in is expected to be a ModelForm instance, bound to the user
to be converted.
The converted ``User`` object is returned.
Raises a TypeError if the user is not lazy. | [
"Convert",
"a",
"lazy",
"user",
"to",
"a",
"non",
"-",
"lazy",
"one",
".",
"The",
"form",
"passed",
"in",
"is",
"expected",
"to",
"be",
"a",
"ModelForm",
"instance",
"bound",
"to",
"the",
"user",
"to",
"be",
"converted",
"."
] | cfe77e12976d439e1a5aae4387531b2f0f835c6a | https://github.com/danfairs/django-lazysignup/blob/cfe77e12976d439e1a5aae4387531b2f0f835c6a/lazysignup/models.py#L47-L65 | train |
danfairs/django-lazysignup | lazysignup/models.py | LazyUserManager.generate_username | def generate_username(self, user_class):
""" Generate a new username for a user
"""
m = getattr(user_class, 'generate_username', None)
if m:
return m()
else:
max_length = user_class._meta.get_field(
self.username_field).max_length
... | python | def generate_username(self, user_class):
""" Generate a new username for a user
"""
m = getattr(user_class, 'generate_username', None)
if m:
return m()
else:
max_length = user_class._meta.get_field(
self.username_field).max_length
... | [
"def",
"generate_username",
"(",
"self",
",",
"user_class",
")",
":",
"m",
"=",
"getattr",
"(",
"user_class",
",",
"'generate_username'",
",",
"None",
")",
"if",
"m",
":",
"return",
"m",
"(",
")",
"else",
":",
"max_length",
"=",
"user_class",
".",
"_meta... | Generate a new username for a user | [
"Generate",
"a",
"new",
"username",
"for",
"a",
"user"
] | cfe77e12976d439e1a5aae4387531b2f0f835c6a | https://github.com/danfairs/django-lazysignup/blob/cfe77e12976d439e1a5aae4387531b2f0f835c6a/lazysignup/models.py#L67-L76 | train |
danfairs/django-lazysignup | lazysignup/utils.py | is_lazy_user | def is_lazy_user(user):
""" Return True if the passed user is a lazy user. """
# Anonymous users are not lazy.
if user.is_anonymous:
return False
# Check the user backend. If the lazy signup backend
# authenticated them, then the user is lazy.
backend = getattr(user, 'backend', None)
... | python | def is_lazy_user(user):
""" Return True if the passed user is a lazy user. """
# Anonymous users are not lazy.
if user.is_anonymous:
return False
# Check the user backend. If the lazy signup backend
# authenticated them, then the user is lazy.
backend = getattr(user, 'backend', None)
... | [
"def",
"is_lazy_user",
"(",
"user",
")",
":",
"if",
"user",
".",
"is_anonymous",
":",
"return",
"False",
"backend",
"=",
"getattr",
"(",
"user",
",",
"'backend'",
",",
"None",
")",
"if",
"backend",
"==",
"'lazysignup.backends.LazySignupBackend'",
":",
"return"... | Return True if the passed user is a lazy user. | [
"Return",
"True",
"if",
"the",
"passed",
"user",
"is",
"a",
"lazy",
"user",
"."
] | cfe77e12976d439e1a5aae4387531b2f0f835c6a | https://github.com/danfairs/django-lazysignup/blob/cfe77e12976d439e1a5aae4387531b2f0f835c6a/lazysignup/utils.py#L1-L16 | train |
bslatkin/dpxdt | dpxdt/server/work_queue.py | add | def add(queue_name, payload=None, content_type=None, source=None, task_id=None,
build_id=None, release_id=None, run_id=None):
"""Adds a work item to a queue.
Args:
queue_name: Name of the queue to add the work item to.
payload: Optional. Payload that describes the work to do as a string... | python | def add(queue_name, payload=None, content_type=None, source=None, task_id=None,
build_id=None, release_id=None, run_id=None):
"""Adds a work item to a queue.
Args:
queue_name: Name of the queue to add the work item to.
payload: Optional. Payload that describes the work to do as a string... | [
"def",
"add",
"(",
"queue_name",
",",
"payload",
"=",
"None",
",",
"content_type",
"=",
"None",
",",
"source",
"=",
"None",
",",
"task_id",
"=",
"None",
",",
"build_id",
"=",
"None",
",",
"release_id",
"=",
"None",
",",
"run_id",
"=",
"None",
")",
":... | Adds a work item to a queue.
Args:
queue_name: Name of the queue to add the work item to.
payload: Optional. Payload that describes the work to do as a string.
If not a string and content_type is not provided, then this
function assumes the payload is a JSON-able Python obje... | [
"Adds",
"a",
"work",
"item",
"to",
"a",
"queue",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/work_queue.py#L100-L145 | train |
bslatkin/dpxdt | dpxdt/server/work_queue.py | _task_to_dict | def _task_to_dict(task):
"""Converts a WorkQueue to a JSON-able dictionary."""
payload = task.payload
if payload and task.content_type == 'application/json':
payload = json.loads(payload)
return dict(
task_id=task.task_id,
queue_name=task.queue_name,
eta=_datetime_to_epo... | python | def _task_to_dict(task):
"""Converts a WorkQueue to a JSON-able dictionary."""
payload = task.payload
if payload and task.content_type == 'application/json':
payload = json.loads(payload)
return dict(
task_id=task.task_id,
queue_name=task.queue_name,
eta=_datetime_to_epo... | [
"def",
"_task_to_dict",
"(",
"task",
")",
":",
"payload",
"=",
"task",
".",
"payload",
"if",
"payload",
"and",
"task",
".",
"content_type",
"==",
"'application/json'",
":",
"payload",
"=",
"json",
".",
"loads",
"(",
"payload",
")",
"return",
"dict",
"(",
... | Converts a WorkQueue to a JSON-able dictionary. | [
"Converts",
"a",
"WorkQueue",
"to",
"a",
"JSON",
"-",
"able",
"dictionary",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/work_queue.py#L155-L170 | train |
bslatkin/dpxdt | dpxdt/server/work_queue.py | lease | def lease(queue_name, owner, count=1, timeout_seconds=60):
"""Leases a work item from a queue, usually the oldest task available.
Args:
queue_name: Name of the queue to lease work from.
owner: Who or what is leasing the task.
count: Lease up to this many tasks. Return value will never h... | python | def lease(queue_name, owner, count=1, timeout_seconds=60):
"""Leases a work item from a queue, usually the oldest task available.
Args:
queue_name: Name of the queue to lease work from.
owner: Who or what is leasing the task.
count: Lease up to this many tasks. Return value will never h... | [
"def",
"lease",
"(",
"queue_name",
",",
"owner",
",",
"count",
"=",
"1",
",",
"timeout_seconds",
"=",
"60",
")",
":",
"now",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"query",
"=",
"(",
"WorkQueue",
".",
"query",
".",
"filter_by",
"(... | Leases a work item from a queue, usually the oldest task available.
Args:
queue_name: Name of the queue to lease work from.
owner: Who or what is leasing the task.
count: Lease up to this many tasks. Return value will never have more
than this many items present.
timeout... | [
"Leases",
"a",
"work",
"item",
"from",
"a",
"queue",
"usually",
"the",
"oldest",
"task",
"available",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/work_queue.py#L177-L216 | train |
bslatkin/dpxdt | dpxdt/server/work_queue.py | _get_task_with_policy | def _get_task_with_policy(queue_name, task_id, owner):
"""Fetches the specified task and enforces ownership policy.
Args:
queue_name: Name of the queue the work item is on.
task_id: ID of the task that is finished.
owner: Who or what has the current lease on the task.
Returns:
... | python | def _get_task_with_policy(queue_name, task_id, owner):
"""Fetches the specified task and enforces ownership policy.
Args:
queue_name: Name of the queue the work item is on.
task_id: ID of the task that is finished.
owner: Who or what has the current lease on the task.
Returns:
... | [
"def",
"_get_task_with_policy",
"(",
"queue_name",
",",
"task_id",
",",
"owner",
")",
":",
"now",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"task",
"=",
"(",
"WorkQueue",
".",
"query",
".",
"filter_by",
"(",
"queue_name",
"=",
"queue_name"... | Fetches the specified task and enforces ownership policy.
Args:
queue_name: Name of the queue the work item is on.
task_id: ID of the task that is finished.
owner: Who or what has the current lease on the task.
Returns:
The valid WorkQueue task that is currently owned.
Rai... | [
"Fetches",
"the",
"specified",
"task",
"and",
"enforces",
"ownership",
"policy",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/work_queue.py#L219-L256 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.